1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2008 Christian Kellner, Samuel Cormier-Iijima
4 * Copyright © 2009 Codethink Limited
5 * Copyright © 2009 Red Hat, Inc
6 * Copyright © 2015 Collabora, Ltd.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General
19 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 * Authors: Christian Kellner <gicmo@gnome.org>
22 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
23 * Ryan Lortie <desrt@desrt.ca>
24 * Alexander Larsson <alexl@redhat.com>
25 * Philip Withnall <philip.withnall@collabora.co.uk>
33 #include "glib-unix.h"
44 # include <sys/ioctl.h>
47 #ifdef HAVE_SIOCGIFADDR
51 #ifdef HAVE_SYS_FILIO_H
52 # include <sys/filio.h>
59 #define GOBJECT_COMPILATION
60 #include "gobject/gtype-private.h" /* For _PRELUDE type define */
61 #undef GOBJECT_COMPILATION
62 #include "gcancellable.h"
63 #include "gdatagrambased.h"
64 #include "gioenumtypes.h"
65 #include "ginetaddress.h"
66 #include "ginetsocketaddress.h"
67 #include "ginitable.h"
71 #include "gnetworkingprivate.h"
72 #include "gsocketaddress.h"
73 #include "gsocketcontrolmessage.h"
74 #include "gcredentials.h"
75 #include "gcredentialsprivate.h"
77 #include "gioprivate.h"
81 * @short_description: Low-level socket object
83 * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
85 * A #GSocket is a low-level networking primitive. It is a more or less
86 * direct mapping of the BSD socket API in a portable GObject based API.
87 * It supports both the UNIX socket implementations and winsock2 on Windows.
89 * #GSocket is the platform independent base upon which the higher level
90 * network primitives are based. Applications are not typically meant to
91 * use it directly, but rather through classes like #GSocketClient,
92 * #GSocketService and #GSocketConnection. However there may be cases where
93 * direct use of #GSocket is useful.
95 * #GSocket implements the #GInitable interface, so if it is manually constructed
96 * by e.g. g_object_new() you must call g_initable_init() and check the
97 * results before using the object. This is done automatically in
98 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
101 * Sockets operate in two general modes, blocking or non-blocking. When
102 * in blocking mode all operations (which don’t take an explicit blocking
103 * parameter) block until the requested operation
104 * is finished or there is an error. In non-blocking mode all calls that
105 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
106 * To know when a call would successfully run you can call g_socket_condition_check(),
107 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
108 * attach it to a #GMainContext to get callbacks when I/O is possible.
109 * Note that all sockets are always set to non blocking mode in the system, and
110 * blocking mode is emulated in GSocket.
112 * When working in non-blocking mode applications should always be able to
113 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
114 * function said that I/O was possible. This can easily happen in case
115 * of a race condition in the application, but it can also happen for other
116 * reasons. For instance, on Windows a socket is always seen as writable
117 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
119 * #GSockets can be either connection oriented or datagram based.
120 * For connection oriented types you must first establish a connection by
121 * either connecting to an address or accepting a connection from another
122 * address. For connectionless socket types the target/source address is
123 * specified or received in each I/O operation.
125 * All socket file descriptors are set to be close-on-exec.
127 * Note that creating a #GSocket causes the signal %SIGPIPE to be
128 * ignored for the remainder of the program. If you are writing a
129 * command-line utility that uses #GSocket, you may need to take into
130 * account the fact that your program will not automatically be killed
131 * if it tries to write to %stdout after it has been closed.
133 * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
134 * a #GSocket concurrently from multiple threads, you must implement your own
140 static void g_socket_initable_iface_init (GInitableIface *iface);
141 static gboolean g_socket_initable_init (GInitable *initable,
142 GCancellable *cancellable,
145 static void g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface);
146 static gint g_socket_datagram_based_receive_messages (GDatagramBased *self,
147 GInputMessage *messages,
151 GCancellable *cancellable,
153 static gint g_socket_datagram_based_send_messages (GDatagramBased *self,
154 GOutputMessage *messages,
158 GCancellable *cancellable,
160 static GSource *g_socket_datagram_based_create_source (GDatagramBased *self,
161 GIOCondition condition,
162 GCancellable *cancellable);
163 static GIOCondition g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
164 GIOCondition condition);
165 static gboolean g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
166 GIOCondition condition,
168 GCancellable *cancellable,
171 static GSocketAddress *
172 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len);
175 g_socket_receive_message_with_timeout (GSocket *socket,
176 GSocketAddress **address,
177 GInputVector *vectors,
179 GSocketControlMessage ***messages,
183 GCancellable *cancellable,
186 g_socket_receive_messages_with_timeout (GSocket *socket,
187 GInputMessage *messages,
191 GCancellable *cancellable,
194 g_socket_send_messages_with_timeout (GSocket *socket,
195 GOutputMessage *messages,
199 GCancellable *cancellable,
217 PROP_MULTICAST_LOOPBACK,
221 /* Size of the receiver cache for g_socket_receive_from() */
222 #define RECV_ADDR_CACHE_SIZE 8
224 struct _GSocketPrivate
226 GSocketFamily family;
228 GSocketProtocol protocol;
232 GError *construct_error;
233 GSocketAddress *remote_address;
238 guint connected_read : 1;
239 guint connected_write : 1;
242 guint connect_pending : 1;
246 DWORD waiting_result;
250 GList *requested_conditions; /* list of requested GIOCondition * */
251 GMutex win32_source_lock;
252 GCond win32_source_cond;
256 GSocketAddress *addr;
257 struct sockaddr *native;
260 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
263 _G_DEFINE_TYPE_EXTENDED_WITH_PRELUDE (GSocket, g_socket, G_TYPE_OBJECT, 0,
264 /* Need a prelude for https://bugzilla.gnome.org/show_bug.cgi?id=674885 */
265 g_type_ensure (G_TYPE_SOCKET_FAMILY);
266 g_type_ensure (G_TYPE_SOCKET_TYPE);
267 g_type_ensure (G_TYPE_SOCKET_PROTOCOL);
268 g_type_ensure (G_TYPE_SOCKET_ADDRESS);
269 /* And networking init is appropriate for the prelude */
270 g_networking_init ();
271 , /* And now the regular type init code */
272 G_ADD_PRIVATE (GSocket)
273 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
274 g_socket_initable_iface_init);
275 G_IMPLEMENT_INTERFACE (G_TYPE_DATAGRAM_BASED,
276 g_socket_datagram_based_iface_init));
279 get_socket_errno (void)
284 return WSAGetLastError ();
289 socket_io_error_from_errno (int err)
292 return g_io_error_from_win32_error (err);
294 return g_io_error_from_errno (err);
299 socket_strerror (int err)
302 return g_strerror (err);
307 msg = g_win32_error_message (err);
309 msg_ret = g_intern_string (msg);
316 /* Wrapper around g_set_error() to avoid doing excess work */
317 #define socket_set_error_lazy(err, errsv, fmt) \
319 GError **__err = (err); \
320 int __errsv = (errsv); \
324 int __code = socket_io_error_from_errno (__errsv); \
325 const char *__strerr = socket_strerror (__errsv); \
327 if (__code == G_IO_ERROR_WOULD_BLOCK) \
328 g_set_error_literal (__err, G_IO_ERROR, __code, __strerr); \
330 g_set_error (__err, G_IO_ERROR, __code, fmt, __strerr); \
335 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
337 _win32_unset_event_mask (GSocket *socket, int mask)
339 g_mutex_lock (&socket->priv->win32_source_lock);
340 socket->priv->current_events &= ~mask;
341 socket->priv->current_errors &= ~mask;
342 g_mutex_unlock (&socket->priv->win32_source_lock);
345 #define win32_unset_event_mask(_socket, _mask)
348 /* Windows has broken prototypes... */
350 #define getsockopt(sockfd, level, optname, optval, optlen) \
351 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
352 #define setsockopt(sockfd, level, optname, optval, optlen) \
353 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
354 #define getsockname(sockfd, addr, addrlen) \
355 getsockname (sockfd, addr, (int *)addrlen)
356 #define getpeername(sockfd, addr, addrlen) \
357 getpeername (sockfd, addr, (int *)addrlen)
358 #define recv(sockfd, buf, len, flags) \
359 recv (sockfd, (gpointer)buf, len, flags)
363 address_to_string (GSocketAddress *address)
365 GString *ret = g_string_new ("");
367 if (G_IS_INET_SOCKET_ADDRESS (address))
369 GInetSocketAddress *isa = G_INET_SOCKET_ADDRESS (address);
370 GInetAddress *ia = g_inet_socket_address_get_address (isa);
371 GSocketFamily family = g_inet_address_get_family (ia);
374 /* Represent IPv6 addresses in URL style:
375 * ::1 port 12345 -> [::1]:12345 */
376 if (family == G_SOCKET_FAMILY_IPV6)
377 g_string_append_c (ret, '[');
379 tmp = g_inet_address_to_string (ia);
380 g_string_append (ret, tmp);
383 if (family == G_SOCKET_FAMILY_IPV6)
385 guint32 scope = g_inet_socket_address_get_scope_id (isa);
388 g_string_append_printf (ret, "%%%u", scope);
390 g_string_append_c (ret, ']');
393 g_string_append_c (ret, ':');
395 g_string_append_printf (ret, "%u", g_inet_socket_address_get_port (isa));
399 /* For unknown address types, just show the type */
400 g_string_append_printf (ret, "(%s)", G_OBJECT_TYPE_NAME (address));
403 return g_string_free (ret, FALSE);
407 check_socket (GSocket *socket,
410 if (!socket->priv->inited)
412 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
413 _("Invalid socket, not initialized"));
417 if (socket->priv->construct_error)
419 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
420 _("Invalid socket, initialization failed due to: %s"),
421 socket->priv->construct_error->message);
425 if (socket->priv->closed)
427 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
428 _("Socket is already closed"));
436 check_timeout (GSocket *socket,
439 if (socket->priv->timed_out)
441 socket->priv->timed_out = FALSE;
442 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
443 _("Socket I/O timed out"));
451 g_socket_details_from_fd (GSocket *socket)
454 struct sockaddr_storage storage;
462 fd = socket->priv->fd;
463 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
465 errsv = get_socket_errno ();
472 socket->priv->type = G_SOCKET_TYPE_STREAM;
476 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
480 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
484 socket->priv->type = G_SOCKET_TYPE_INVALID;
488 addrlen = sizeof address;
489 if (getsockname (fd, &address.sa, &addrlen) != 0)
491 errsv = get_socket_errno ();
497 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
498 sizeof address.storage.ss_family <= addrlen);
499 family = address.storage.ss_family;
503 /* On Solaris, this happens if the socket is not yet connected.
504 * But we can use SO_DOMAIN as a workaround there.
507 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
509 errsv = get_socket_errno ();
513 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
521 case G_SOCKET_FAMILY_IPV4:
522 case G_SOCKET_FAMILY_IPV6:
523 socket->priv->family = address.storage.ss_family;
524 switch (socket->priv->type)
526 case G_SOCKET_TYPE_STREAM:
527 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
530 case G_SOCKET_TYPE_DATAGRAM:
531 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
534 case G_SOCKET_TYPE_SEQPACKET:
535 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
543 case G_SOCKET_FAMILY_UNIX:
544 socket->priv->family = G_SOCKET_FAMILY_UNIX;
545 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
549 socket->priv->family = G_SOCKET_FAMILY_INVALID;
553 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
555 addrlen = sizeof address;
556 if (getpeername (fd, &address.sa, &addrlen) >= 0)
558 socket->priv->connected_read = TRUE;
559 socket->priv->connected_write = TRUE;
563 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
565 socket->priv->keepalive = !!value;
569 /* Can't read, maybe not supported, assume FALSE */
570 socket->priv->keepalive = FALSE;
576 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
577 socket_io_error_from_errno (errsv),
578 _("creating GSocket from fd: %s"),
579 socket_strerror (errsv));
582 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
584 g_socket (gint domain,
592 fd = socket (domain, type | SOCK_CLOEXEC, protocol);
597 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
598 if (fd < 0 && (errsv == EINVAL || errsv == EPROTOTYPE))
600 fd = socket (domain, type, protocol);
604 errsv = get_socket_errno ();
606 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
607 _("Unable to create socket: %s"), socket_strerror (errsv));
616 /* We always want to set close-on-exec to protect users. If you
617 need to so some weird inheritance to exec you can re-enable this
618 using lower level hacks with g_socket_get_fd(). */
619 flags = fcntl (fd, F_GETFD, 0);
621 (flags & FD_CLOEXEC) == 0)
624 fcntl (fd, F_SETFD, flags);
633 g_socket_create_socket (GSocketFamily family,
642 case G_SOCKET_TYPE_STREAM:
643 native_type = SOCK_STREAM;
646 case G_SOCKET_TYPE_DATAGRAM:
647 native_type = SOCK_DGRAM;
650 case G_SOCKET_TYPE_SEQPACKET:
651 native_type = SOCK_SEQPACKET;
655 g_assert_not_reached ();
660 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
661 _("Unable to create socket: %s"), _("Unknown family was specified"));
667 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
668 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
672 return g_socket (family, native_type, protocol, error);
676 g_socket_constructed (GObject *object)
678 GSocket *socket = G_SOCKET (object);
680 if (socket->priv->fd >= 0)
681 /* create socket->priv info from the fd */
682 g_socket_details_from_fd (socket);
685 /* create the fd from socket->priv info */
686 socket->priv->fd = g_socket_create_socket (socket->priv->family,
688 socket->priv->protocol,
689 &socket->priv->construct_error);
691 if (socket->priv->fd != -1)
694 GError *error = NULL;
699 /* Always use native nonblocking sockets, as Windows sets sockets to
700 * nonblocking automatically in certain operations. This way we make
701 * things work the same on all platforms.
704 if (!g_unix_set_fd_nonblocking (socket->priv->fd, TRUE, &error))
706 g_warning ("Error setting socket nonblocking: %s", error->message);
707 g_clear_error (&error);
712 if (ioctlsocket (socket->priv->fd, FIONBIO, &arg) == SOCKET_ERROR)
714 int errsv = get_socket_errno ();
715 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
720 /* See note about SIGPIPE below. */
721 g_socket_set_option (socket, SOL_SOCKET, SO_NOSIGPIPE, TRUE, NULL);
727 g_socket_get_property (GObject *object,
732 GSocket *socket = G_SOCKET (object);
733 GSocketAddress *address;
738 g_value_set_enum (value, socket->priv->family);
742 g_value_set_enum (value, socket->priv->type);
746 g_value_set_enum (value, socket->priv->protocol);
750 g_value_set_int (value, socket->priv->fd);
754 g_value_set_boolean (value, socket->priv->blocking);
757 case PROP_LISTEN_BACKLOG:
758 g_value_set_int (value, socket->priv->listen_backlog);
762 g_value_set_boolean (value, socket->priv->keepalive);
765 case PROP_LOCAL_ADDRESS:
766 address = g_socket_get_local_address (socket, NULL);
767 g_value_take_object (value, address);
770 case PROP_REMOTE_ADDRESS:
771 address = g_socket_get_remote_address (socket, NULL);
772 g_value_take_object (value, address);
776 g_value_set_uint (value, socket->priv->timeout);
780 g_value_set_uint (value, g_socket_get_ttl (socket));
784 g_value_set_boolean (value, g_socket_get_broadcast (socket));
787 case PROP_MULTICAST_LOOPBACK:
788 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
791 case PROP_MULTICAST_TTL:
792 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
796 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
801 g_socket_set_property (GObject *object,
806 GSocket *socket = G_SOCKET (object);
811 socket->priv->family = g_value_get_enum (value);
815 socket->priv->type = g_value_get_enum (value);
819 socket->priv->protocol = g_value_get_enum (value);
823 socket->priv->fd = g_value_get_int (value);
827 g_socket_set_blocking (socket, g_value_get_boolean (value));
830 case PROP_LISTEN_BACKLOG:
831 g_socket_set_listen_backlog (socket, g_value_get_int (value));
835 g_socket_set_keepalive (socket, g_value_get_boolean (value));
839 g_socket_set_timeout (socket, g_value_get_uint (value));
843 g_socket_set_ttl (socket, g_value_get_uint (value));
847 g_socket_set_broadcast (socket, g_value_get_boolean (value));
850 case PROP_MULTICAST_LOOPBACK:
851 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
854 case PROP_MULTICAST_TTL:
855 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
859 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
864 g_socket_finalize (GObject *object)
866 GSocket *socket = G_SOCKET (object);
869 g_clear_error (&socket->priv->construct_error);
871 if (socket->priv->fd != -1 &&
872 !socket->priv->closed)
873 g_socket_close (socket, NULL);
875 if (socket->priv->remote_address)
876 g_object_unref (socket->priv->remote_address);
879 if (socket->priv->event != WSA_INVALID_EVENT)
881 WSACloseEvent (socket->priv->event);
882 socket->priv->event = WSA_INVALID_EVENT;
885 g_assert (socket->priv->requested_conditions == NULL);
886 g_mutex_clear (&socket->priv->win32_source_lock);
887 g_cond_clear (&socket->priv->win32_source_cond);
890 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
892 if (socket->priv->recv_addr_cache[i].addr)
894 g_object_unref (socket->priv->recv_addr_cache[i].addr);
895 g_free (socket->priv->recv_addr_cache[i].native);
899 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
900 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
904 g_socket_class_init (GSocketClass *klass)
906 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
909 /* There is no portable, thread-safe way to avoid having the process
910 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
911 * forced to simply ignore the signal process-wide.
913 * Even if we ignore it though, gdb will still stop if the app
914 * receives a SIGPIPE, which can be confusing and annoying. So when
915 * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
916 * prevent the signal from occurring at all.
918 signal (SIGPIPE, SIG_IGN);
921 gobject_class->finalize = g_socket_finalize;
922 gobject_class->constructed = g_socket_constructed;
923 gobject_class->set_property = g_socket_set_property;
924 gobject_class->get_property = g_socket_get_property;
926 g_object_class_install_property (gobject_class, PROP_FAMILY,
927 g_param_spec_enum ("family",
929 P_("The sockets address family"),
930 G_TYPE_SOCKET_FAMILY,
931 G_SOCKET_FAMILY_INVALID,
932 G_PARAM_CONSTRUCT_ONLY |
934 G_PARAM_STATIC_STRINGS));
936 g_object_class_install_property (gobject_class, PROP_TYPE,
937 g_param_spec_enum ("type",
939 P_("The sockets type"),
941 G_SOCKET_TYPE_STREAM,
942 G_PARAM_CONSTRUCT_ONLY |
944 G_PARAM_STATIC_STRINGS));
946 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
947 g_param_spec_enum ("protocol",
948 P_("Socket protocol"),
949 P_("The id of the protocol to use, or -1 for unknown"),
950 G_TYPE_SOCKET_PROTOCOL,
951 G_SOCKET_PROTOCOL_UNKNOWN,
952 G_PARAM_CONSTRUCT_ONLY |
954 G_PARAM_STATIC_STRINGS));
956 g_object_class_install_property (gobject_class, PROP_FD,
957 g_param_spec_int ("fd",
958 P_("File descriptor"),
959 P_("The sockets file descriptor"),
963 G_PARAM_CONSTRUCT_ONLY |
965 G_PARAM_STATIC_STRINGS));
967 g_object_class_install_property (gobject_class, PROP_BLOCKING,
968 g_param_spec_boolean ("blocking",
970 P_("Whether or not I/O on this socket is blocking"),
973 G_PARAM_STATIC_STRINGS));
975 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
976 g_param_spec_int ("listen-backlog",
977 P_("Listen backlog"),
978 P_("Outstanding connections in the listen queue"),
983 G_PARAM_STATIC_STRINGS));
985 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
986 g_param_spec_boolean ("keepalive",
987 P_("Keep connection alive"),
988 P_("Keep connection alive by sending periodic pings"),
991 G_PARAM_STATIC_STRINGS));
993 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
994 g_param_spec_object ("local-address",
996 P_("The local address the socket is bound to"),
997 G_TYPE_SOCKET_ADDRESS,
999 G_PARAM_STATIC_STRINGS));
1001 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
1002 g_param_spec_object ("remote-address",
1003 P_("Remote address"),
1004 P_("The remote address the socket is connected to"),
1005 G_TYPE_SOCKET_ADDRESS,
1007 G_PARAM_STATIC_STRINGS));
1012 * The timeout in seconds on socket I/O
1016 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
1017 g_param_spec_uint ("timeout",
1019 P_("The timeout in seconds on socket I/O"),
1024 G_PARAM_STATIC_STRINGS));
1027 * GSocket:broadcast:
1029 * Whether the socket should allow sending to broadcast addresses.
1033 g_object_class_install_property (gobject_class, PROP_BROADCAST,
1034 g_param_spec_boolean ("broadcast",
1036 P_("Whether to allow sending to broadcast addresses"),
1039 G_PARAM_STATIC_STRINGS));
1044 * Time-to-live for outgoing unicast packets
1048 g_object_class_install_property (gobject_class, PROP_TTL,
1049 g_param_spec_uint ("ttl",
1051 P_("Time-to-live of outgoing unicast packets"),
1054 G_PARAM_STATIC_STRINGS));
1057 * GSocket:multicast-loopback:
1059 * Whether outgoing multicast packets loop back to the local host.
1063 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
1064 g_param_spec_boolean ("multicast-loopback",
1065 P_("Multicast loopback"),
1066 P_("Whether outgoing multicast packets loop back to the local host"),
1069 G_PARAM_STATIC_STRINGS));
1072 * GSocket:multicast-ttl:
1074 * Time-to-live out outgoing multicast packets
1078 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
1079 g_param_spec_uint ("multicast-ttl",
1080 P_("Multicast TTL"),
1081 P_("Time-to-live of outgoing multicast packets"),
1084 G_PARAM_STATIC_STRINGS));
1088 g_socket_initable_iface_init (GInitableIface *iface)
1090 iface->init = g_socket_initable_init;
1094 g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface)
1096 iface->receive_messages = g_socket_datagram_based_receive_messages;
1097 iface->send_messages = g_socket_datagram_based_send_messages;
1098 iface->create_source = g_socket_datagram_based_create_source;
1099 iface->condition_check = g_socket_datagram_based_condition_check;
1100 iface->condition_wait = g_socket_datagram_based_condition_wait;
1104 g_socket_init (GSocket *socket)
1106 socket->priv = g_socket_get_instance_private (socket);
1108 socket->priv->fd = -1;
1109 socket->priv->blocking = TRUE;
1110 socket->priv->listen_backlog = 10;
1111 socket->priv->construct_error = NULL;
1113 socket->priv->event = WSA_INVALID_EVENT;
1114 g_mutex_init (&socket->priv->win32_source_lock);
1115 g_cond_init (&socket->priv->win32_source_cond);
1120 g_socket_initable_init (GInitable *initable,
1121 GCancellable *cancellable,
1126 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
1128 socket = G_SOCKET (initable);
1130 if (cancellable != NULL)
1132 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1133 _("Cancellable initialization not supported"));
1137 socket->priv->inited = TRUE;
1139 if (socket->priv->construct_error)
1142 *error = g_error_copy (socket->priv->construct_error);
1151 check_datagram_based (GDatagramBased *self,
1154 switch (g_socket_get_socket_type (G_SOCKET (self)))
1156 case G_SOCKET_TYPE_INVALID:
1157 case G_SOCKET_TYPE_STREAM:
1158 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1159 _("Cannot use datagram operations on a non-datagram "
1162 case G_SOCKET_TYPE_DATAGRAM:
1163 case G_SOCKET_TYPE_SEQPACKET:
1168 /* Due to us sharing #GSocketSource with the #GSocket implementation, it is
1169 * pretty tricky to split out #GSocket:timeout so that it does not affect
1170 * #GDatagramBased operations (but still affects #GSocket operations). It is
1171 * not worth that effort — just disallow it and require the user to specify
1172 * timeouts on a per-operation basis. */
1173 if (g_socket_get_timeout (G_SOCKET (self)) != 0)
1175 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1176 _("Cannot use datagram operations on a socket with a "
1185 g_socket_datagram_based_receive_messages (GDatagramBased *self,
1186 GInputMessage *messages,
1190 GCancellable *cancellable,
1193 if (!check_datagram_based (self, error))
1196 return g_socket_receive_messages_with_timeout (G_SOCKET (self), messages,
1197 num_messages, flags, timeout_us,
1198 cancellable, error);
1202 g_socket_datagram_based_send_messages (GDatagramBased *self,
1203 GOutputMessage *messages,
1207 GCancellable *cancellable,
1210 if (!check_datagram_based (self, error))
1213 return g_socket_send_messages_with_timeout (G_SOCKET (self), messages,
1214 num_messages, flags, timeout_us,
1215 cancellable, error);
1219 g_socket_datagram_based_create_source (GDatagramBased *self,
1220 GIOCondition condition,
1221 GCancellable *cancellable)
1223 if (!check_datagram_based (self, NULL))
1226 return g_socket_create_source (G_SOCKET (self), condition, cancellable);
1230 g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
1231 GIOCondition condition)
1233 if (!check_datagram_based (datagram_based, NULL))
1236 return g_socket_condition_check (G_SOCKET (datagram_based), condition);
1240 g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
1241 GIOCondition condition,
1243 GCancellable *cancellable,
1246 if (!check_datagram_based (datagram_based, error))
1249 return g_socket_condition_timed_wait (G_SOCKET (datagram_based), condition,
1250 timeout_us, cancellable, error);
1255 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1256 * @type: the socket type to use.
1257 * @protocol: the id of the protocol to use, or 0 for default.
1258 * @error: #GError for error reporting, or %NULL to ignore.
1260 * Creates a new #GSocket with the defined family, type and protocol.
1261 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1262 * for the family and type is used.
1264 * The @protocol is a family and type specific int that specifies what
1265 * kind of protocol to use. #GSocketProtocol lists several common ones.
1266 * Many families only support one protocol, and use 0 for this, others
1267 * support several and using 0 means to use the default protocol for
1268 * the family and type.
1270 * The protocol id is passed directly to the operating
1271 * system, so you can use protocols not listed in #GSocketProtocol if you
1272 * know the protocol number used for it.
1274 * Returns: a #GSocket or %NULL on error.
1275 * Free the returned object with g_object_unref().
1280 g_socket_new (GSocketFamily family,
1282 GSocketProtocol protocol,
1285 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1289 "protocol", protocol,
1294 * g_socket_new_from_fd:
1295 * @fd: a native socket file descriptor.
1296 * @error: #GError for error reporting, or %NULL to ignore.
1298 * Creates a new #GSocket from a native file descriptor
1299 * or winsock SOCKET handle.
1301 * This reads all the settings from the file descriptor so that
1302 * all properties should work. Note that the file descriptor
1303 * will be set to non-blocking mode, independent on the blocking
1304 * mode of the #GSocket.
1306 * On success, the returned #GSocket takes ownership of @fd. On failure, the
1307 * caller must close @fd themselves.
1309 * Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
1310 * descriptor. Instead, a GError will be set with code %G_IO_ERROR_FAILED
1312 * Returns: a #GSocket or %NULL on error.
1313 * Free the returned object with g_object_unref().
1318 g_socket_new_from_fd (gint fd,
1321 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1328 * g_socket_set_blocking:
1329 * @socket: a #GSocket.
1330 * @blocking: Whether to use blocking I/O or not.
1332 * Sets the blocking mode of the socket. In blocking mode
1333 * all operations (which don’t take an explicit blocking parameter) block until
1334 * they succeed or there is an error. In
1335 * non-blocking mode all functions return results immediately or
1336 * with a %G_IO_ERROR_WOULD_BLOCK error.
1338 * All sockets are created in blocking mode. However, note that the
1339 * platform level socket is always non-blocking, and blocking mode
1340 * is a GSocket level feature.
1345 g_socket_set_blocking (GSocket *socket,
1348 g_return_if_fail (G_IS_SOCKET (socket));
1350 blocking = !!blocking;
1352 if (socket->priv->blocking == blocking)
1355 socket->priv->blocking = blocking;
1356 g_object_notify (G_OBJECT (socket), "blocking");
1360 * g_socket_get_blocking:
1361 * @socket: a #GSocket.
1363 * Gets the blocking mode of the socket. For details on blocking I/O,
1364 * see g_socket_set_blocking().
1366 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1371 g_socket_get_blocking (GSocket *socket)
1373 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1375 return socket->priv->blocking;
1379 * g_socket_set_keepalive:
1380 * @socket: a #GSocket.
1381 * @keepalive: Value for the keepalive flag
1383 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1384 * this flag is set on a socket, the system will attempt to verify that the
1385 * remote socket endpoint is still present if a sufficiently long period of
1386 * time passes with no data being exchanged. If the system is unable to
1387 * verify the presence of the remote endpoint, it will automatically close
1390 * This option is only functional on certain kinds of sockets. (Notably,
1391 * %G_SOCKET_PROTOCOL_TCP sockets.)
1393 * The exact time between pings is system- and protocol-dependent, but will
1394 * normally be at least two hours. Most commonly, you would set this flag
1395 * on a server socket if you want to allow clients to remain idle for long
1396 * periods of time, but also want to ensure that connections are eventually
1397 * garbage-collected if clients crash or become unreachable.
1402 g_socket_set_keepalive (GSocket *socket,
1405 GError *error = NULL;
1407 g_return_if_fail (G_IS_SOCKET (socket));
1409 keepalive = !!keepalive;
1410 if (socket->priv->keepalive == keepalive)
1413 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1416 g_warning ("error setting keepalive: %s", error->message);
1417 g_error_free (error);
1421 socket->priv->keepalive = keepalive;
1422 g_object_notify (G_OBJECT (socket), "keepalive");
1426 * g_socket_get_keepalive:
1427 * @socket: a #GSocket.
1429 * Gets the keepalive mode of the socket. For details on this,
1430 * see g_socket_set_keepalive().
1432 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1437 g_socket_get_keepalive (GSocket *socket)
1439 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1441 return socket->priv->keepalive;
1445 * g_socket_get_listen_backlog:
1446 * @socket: a #GSocket.
1448 * Gets the listen backlog setting of the socket. For details on this,
1449 * see g_socket_set_listen_backlog().
1451 * Returns: the maximum number of pending connections.
1456 g_socket_get_listen_backlog (GSocket *socket)
1458 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1460 return socket->priv->listen_backlog;
1464 * g_socket_set_listen_backlog:
1465 * @socket: a #GSocket.
1466 * @backlog: the maximum number of pending connections.
1468 * Sets the maximum number of outstanding connections allowed
1469 * when listening on this socket. If more clients than this are
1470 * connecting to the socket and the application is not handling them
1471 * on time then the new connections will be refused.
1473 * Note that this must be called before g_socket_listen() and has no
1474 * effect if called after that.
1479 g_socket_set_listen_backlog (GSocket *socket,
1482 g_return_if_fail (G_IS_SOCKET (socket));
1483 g_return_if_fail (!socket->priv->listening);
1485 if (backlog != socket->priv->listen_backlog)
1487 socket->priv->listen_backlog = backlog;
1488 g_object_notify (G_OBJECT (socket), "listen-backlog");
1493 * g_socket_get_timeout:
1494 * @socket: a #GSocket.
1496 * Gets the timeout setting of the socket. For details on this, see
1497 * g_socket_set_timeout().
1499 * Returns: the timeout in seconds
1504 g_socket_get_timeout (GSocket *socket)
1506 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1508 return socket->priv->timeout;
1512 * g_socket_set_timeout:
1513 * @socket: a #GSocket.
1514 * @timeout: the timeout for @socket, in seconds, or 0 for none
1516 * Sets the time in seconds after which I/O operations on @socket will
1517 * time out if they have not yet completed.
1519 * On a blocking socket, this means that any blocking #GSocket
1520 * operation will time out after @timeout seconds of inactivity,
1521 * returning %G_IO_ERROR_TIMED_OUT.
1523 * On a non-blocking socket, calls to g_socket_condition_wait() will
1524 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1525 * created with g_socket_create_source() will trigger after
1526 * @timeout seconds of inactivity, with the requested condition
1527 * set, at which point calling g_socket_receive(), g_socket_send(),
1528 * g_socket_check_connect_result(), etc, will fail with
1529 * %G_IO_ERROR_TIMED_OUT.
1531 * If @timeout is 0 (the default), operations will never time out
1534 * Note that if an I/O operation is interrupted by a signal, this may
1535 * cause the timeout to be reset.
1540 g_socket_set_timeout (GSocket *socket,
1543 g_return_if_fail (G_IS_SOCKET (socket));
1545 if (timeout != socket->priv->timeout)
1547 socket->priv->timeout = timeout;
1548 g_object_notify (G_OBJECT (socket), "timeout");
1554 * @socket: a #GSocket.
1556 * Gets the unicast time-to-live setting on @socket; see
1557 * g_socket_set_ttl() for more details.
1559 * Returns: the time-to-live setting on @socket
1564 g_socket_get_ttl (GSocket *socket)
1566 GError *error = NULL;
1569 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1571 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1573 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1576 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1578 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1582 g_return_val_if_reached (0);
1586 g_warning ("error getting unicast ttl: %s", error->message);
1587 g_error_free (error);
1596 * @socket: a #GSocket.
1597 * @ttl: the time-to-live value for all unicast packets on @socket
1599 * Sets the time-to-live for outgoing unicast packets on @socket.
1600 * By default the platform-specific default value is used.
1605 g_socket_set_ttl (GSocket *socket,
1608 GError *error = NULL;
1610 g_return_if_fail (G_IS_SOCKET (socket));
1612 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1614 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1617 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1619 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1621 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1625 g_return_if_reached ();
1629 g_warning ("error setting unicast ttl: %s", error->message);
1630 g_error_free (error);
1634 g_object_notify (G_OBJECT (socket), "ttl");
1638 * g_socket_get_broadcast:
1639 * @socket: a #GSocket.
1641 * Gets the broadcast setting on @socket; if %TRUE,
1642 * it is possible to send packets to broadcast
1645 * Returns: the broadcast setting on @socket
1650 g_socket_get_broadcast (GSocket *socket)
1652 GError *error = NULL;
1655 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1657 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1660 g_warning ("error getting broadcast: %s", error->message);
1661 g_error_free (error);
1669 * g_socket_set_broadcast:
1670 * @socket: a #GSocket.
1671 * @broadcast: whether @socket should allow sending to broadcast
1674 * Sets whether @socket should allow sending to broadcast addresses.
1675 * This is %FALSE by default.
1680 g_socket_set_broadcast (GSocket *socket,
1683 GError *error = NULL;
1685 g_return_if_fail (G_IS_SOCKET (socket));
1687 broadcast = !!broadcast;
1689 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1692 g_warning ("error setting broadcast: %s", error->message);
1693 g_error_free (error);
1697 g_object_notify (G_OBJECT (socket), "broadcast");
1701 * g_socket_get_multicast_loopback:
1702 * @socket: a #GSocket.
1704 * Gets the multicast loopback setting on @socket; if %TRUE (the
1705 * default), outgoing multicast packets will be looped back to
1706 * multicast listeners on the same host.
1708 * Returns: the multicast loopback setting on @socket
1713 g_socket_get_multicast_loopback (GSocket *socket)
1715 GError *error = NULL;
1718 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1720 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1722 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1725 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1727 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1731 g_return_val_if_reached (FALSE);
1735 g_warning ("error getting multicast loopback: %s", error->message);
1736 g_error_free (error);
1744 * g_socket_set_multicast_loopback:
1745 * @socket: a #GSocket.
1746 * @loopback: whether @socket should receive messages sent to its
1747 * multicast groups from the local host
1749 * Sets whether outgoing multicast packets will be received by sockets
1750 * listening on that multicast address on the same host. This is %TRUE
1756 g_socket_set_multicast_loopback (GSocket *socket,
1759 GError *error = NULL;
1761 g_return_if_fail (G_IS_SOCKET (socket));
1763 loopback = !!loopback;
1765 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1767 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1770 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1772 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1774 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1778 g_return_if_reached ();
1782 g_warning ("error setting multicast loopback: %s", error->message);
1783 g_error_free (error);
1787 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1791 * g_socket_get_multicast_ttl:
1792 * @socket: a #GSocket.
1794 * Gets the multicast time-to-live setting on @socket; see
1795 * g_socket_set_multicast_ttl() for more details.
1797 * Returns: the multicast time-to-live setting on @socket
1802 g_socket_get_multicast_ttl (GSocket *socket)
1804 GError *error = NULL;
1807 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1809 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1811 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1814 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1816 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1820 g_return_val_if_reached (FALSE);
1824 g_warning ("error getting multicast ttl: %s", error->message);
1825 g_error_free (error);
1833 * g_socket_set_multicast_ttl:
1834 * @socket: a #GSocket.
1835 * @ttl: the time-to-live value for all multicast datagrams on @socket
1837 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1838 * By default, this is 1, meaning that multicast packets will not leave
1839 * the local network.
1844 g_socket_set_multicast_ttl (GSocket *socket,
1847 GError *error = NULL;
1849 g_return_if_fail (G_IS_SOCKET (socket));
1851 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1853 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1856 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1858 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1860 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1864 g_return_if_reached ();
1868 g_warning ("error setting multicast ttl: %s", error->message);
1869 g_error_free (error);
1873 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1877 * g_socket_get_family:
1878 * @socket: a #GSocket.
1880 * Gets the socket family of the socket.
1882 * Returns: a #GSocketFamily
1887 g_socket_get_family (GSocket *socket)
1889 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1891 return socket->priv->family;
1895 * g_socket_get_socket_type:
1896 * @socket: a #GSocket.
1898 * Gets the socket type of the socket.
1900 * Returns: a #GSocketType
1905 g_socket_get_socket_type (GSocket *socket)
1907 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1909 return socket->priv->type;
1913 * g_socket_get_protocol:
1914 * @socket: a #GSocket.
1916 * Gets the socket protocol id the socket was created with.
1917 * In case the protocol is unknown, -1 is returned.
1919 * Returns: a protocol id, or -1 if unknown
1924 g_socket_get_protocol (GSocket *socket)
1926 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1928 return socket->priv->protocol;
1933 * @socket: a #GSocket.
1935 * Returns the underlying OS socket object. On unix this
1936 * is a socket file descriptor, and on Windows this is
1937 * a Winsock2 SOCKET handle. This may be useful for
1938 * doing platform specific or otherwise unusual operations
1941 * Returns: the file descriptor of the socket.
1946 g_socket_get_fd (GSocket *socket)
1948 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1950 return socket->priv->fd;
1954 * g_socket_get_local_address:
1955 * @socket: a #GSocket.
1956 * @error: #GError for error reporting, or %NULL to ignore.
1958 * Try to get the local address of a bound socket. This is only
1959 * useful if the socket has been bound to a local address,
1960 * either explicitly or implicitly when connecting.
1962 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1963 * Free the returned object with g_object_unref().
1968 g_socket_get_local_address (GSocket *socket,
1972 struct sockaddr_storage storage;
1975 guint len = sizeof (buffer);
1977 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1979 if (getsockname (socket->priv->fd, &buffer.sa, &len) < 0)
1981 int errsv = get_socket_errno ();
1982 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1983 _("could not get local address: %s"), socket_strerror (errsv));
1987 return g_socket_address_new_from_native (&buffer.storage, len);
1991 * g_socket_get_remote_address:
1992 * @socket: a #GSocket.
1993 * @error: #GError for error reporting, or %NULL to ignore.
1995 * Try to get the remote address of a connected socket. This is only
1996 * useful for connection oriented sockets that have been connected.
1998 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1999 * Free the returned object with g_object_unref().
2004 g_socket_get_remote_address (GSocket *socket,
2008 struct sockaddr_storage storage;
2011 guint len = sizeof (buffer);
2013 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2015 if (socket->priv->connect_pending)
2017 if (!g_socket_check_connect_result (socket, error))
2020 socket->priv->connect_pending = FALSE;
2023 if (!socket->priv->remote_address)
2025 if (getpeername (socket->priv->fd, &buffer.sa, &len) < 0)
2027 int errsv = get_socket_errno ();
2028 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2029 _("could not get remote address: %s"), socket_strerror (errsv));
2033 socket->priv->remote_address = g_socket_address_new_from_native (&buffer.storage, len);
2036 return g_object_ref (socket->priv->remote_address);
2040 * g_socket_is_connected:
2041 * @socket: a #GSocket.
2043 * Check whether the socket is connected. This is only useful for
2044 * connection-oriented sockets.
2046 * If using g_socket_shutdown(), this function will return %TRUE until the
2047 * socket has been shut down for reading and writing. If you do a non-blocking
2048 * connect, this function will not return %TRUE until after you call
2049 * g_socket_check_connect_result().
2051 * Returns: %TRUE if socket is connected, %FALSE otherwise.
2056 g_socket_is_connected (GSocket *socket)
2058 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2060 return (socket->priv->connected_read || socket->priv->connected_write);
2065 * @socket: a #GSocket.
2066 * @error: #GError for error reporting, or %NULL to ignore.
2068 * Marks the socket as a server socket, i.e. a socket that is used
2069 * to accept incoming requests using g_socket_accept().
2071 * Before calling this the socket must be bound to a local address using
2074 * To set the maximum amount of outstanding clients, use
2075 * g_socket_set_listen_backlog().
2077 * Returns: %TRUE on success, %FALSE on error.
2082 g_socket_listen (GSocket *socket,
2085 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2087 if (!check_socket (socket, error))
2090 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
2092 int errsv = get_socket_errno ();
2094 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2095 _("could not listen: %s"), socket_strerror (errsv));
2099 socket->priv->listening = TRUE;
2106 * @socket: a #GSocket.
2107 * @address: a #GSocketAddress specifying the local address.
2108 * @allow_reuse: whether to allow reusing this address
2109 * @error: #GError for error reporting, or %NULL to ignore.
2111 * When a socket is created it is attached to an address family, but it
2112 * doesn't have an address in this family. g_socket_bind() assigns the
2113 * address (sometimes called name) of the socket.
2115 * It is generally required to bind to a local address before you can
2116 * receive connections. (See g_socket_listen() and g_socket_accept() ).
2117 * In certain situations, you may also want to bind a socket that will be
2118 * used to initiate connections, though this is not normally required.
2120 * If @socket is a TCP socket, then @allow_reuse controls the setting
2121 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
2122 * server sockets (sockets that you will eventually call
2123 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
2124 * set this flag on a server socket may cause g_socket_bind() to return
2125 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
2126 * immediately restarted.)
2128 * If @socket is a UDP socket, then @allow_reuse determines whether or
2129 * not other UDP sockets can be bound to the same address at the same
2130 * time. In particular, you can have several UDP sockets bound to the
2131 * same address, and they will all receive all of the multicast and
2132 * broadcast packets sent to that address. (The behavior of unicast
2133 * UDP packets to an address with multiple listeners is not defined.)
2135 * Returns: %TRUE on success, %FALSE on error.
2140 g_socket_bind (GSocket *socket,
2141 GSocketAddress *address,
2142 gboolean reuse_address,
2146 struct sockaddr_storage storage;
2149 gboolean so_reuseaddr;
2151 gboolean so_reuseport;
2154 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2156 if (!check_socket (socket, error))
2159 if (!g_socket_address_to_native (address, &addr.storage, sizeof addr, error))
2162 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
2163 * sockets, but has nasty side effects we don't want for TCP
2166 * On other platforms, we set SO_REUSEPORT, if it exists, for
2167 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
2168 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
2169 * the desired semantics on UDP (as it does on Linux, although
2170 * Linux has SO_REUSEPORT too as of 3.9).
2174 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2176 so_reuseaddr = !!reuse_address;
2180 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2183 /* Ignore errors here, the only likely error is "not supported", and
2184 * this is a "best effort" thing mainly.
2186 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
2188 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
2191 if (bind (socket->priv->fd, &addr.sa,
2192 g_socket_address_get_native_size (address)) < 0)
2194 int errsv = get_socket_errno ();
2195 gchar *address_string = address_to_string (address);
2198 G_IO_ERROR, socket_io_error_from_errno (errsv),
2199 _("Error binding to address %s: %s"),
2200 address_string, socket_strerror (errsv));
2201 g_free (address_string);
2210 g_socket_w32_get_adapter_ipv4_addr (const gchar *name_or_ip)
2212 ULONG bufsize = 15000; /* MS-recommended initial bufsize */
2213 DWORD ret = ERROR_BUFFER_OVERFLOW;
2214 unsigned int malloc_iterations = 0;
2215 PIP_ADAPTER_ADDRESSES addr_buf = NULL, eth_adapter;
2216 wchar_t *wchar_name_or_ip = NULL;
2218 NET_IFINDEX if_index;
2221 * For Windows OS only - return adapter IPv4 address in network byte order.
2223 * Input string can be either friendly name of adapter, IP address of adapter,
2224 * indextoname, or fullname of adapter.
2226 * 192.168.1.109 ===> IP address given directly,
2227 * convert directly with inet_addr() function
2228 * Wi-Fi ===> Adapter friendly name "Wi-Fi",
2229 * scan with GetAdapterAddresses and adapter->FriendlyName
2230 * ethernet_32774 ===> Adapter name as returned by if_indextoname
2231 * {33E8F5CD-BAEA-4214-BE13-B79AB8080CAB} ===> Adaptername,
2232 * as returned in GetAdapterAddresses and adapter->AdapterName
2235 /* Step 1: Check if string is an IP address: */
2236 ip_result = inet_addr (name_or_ip);
2237 if (ip_result != INADDR_NONE)
2238 return ip_result; /* Success, IP address string was given directly */
2241 * Step 2: Check if name represents a valid Interface index (e.g. ethernet_75521)
2242 * function if_nametoindex will return >=1 if a valid index, or 0=no match
2243 * valid index will be used later in GetAdaptersAddress loop for lookup of adapter IP address
2245 if_index = if_nametoindex (name_or_ip);
2247 /* Step 3: Prepare wchar string for friendly name comparison */
2250 size_t if_name_len = strlen (name_or_ip);
2251 if (if_name_len >= MAX_ADAPTER_NAME_LENGTH + 4)
2253 /* Name-check only needed if index=0... */
2254 wchar_name_or_ip = (wchar_t *) g_try_malloc ((if_name_len + 1) * sizeof(wchar_t));
2255 if (wchar_name_or_ip)
2256 mbstowcs (wchar_name_or_ip, name_or_ip, if_name_len + 1);
2257 /* NOTE: Even if malloc fails here, some comparisons can still be done later... so no exit here! */
2261 * Step 4: Allocate memory and get adapter addresses.
2262 * Buffer allocation loop recommended by MS, since size can be dynamic
2263 * https://docs.microsoft.com/en-us/windows/desktop/api/iphlpapi/nf-iphlpapi-getadaptersaddresses
2265 #define MAX_ALLOC_ITERATIONS 3
2268 malloc_iterations++;
2269 addr_buf = (PIP_ADAPTER_ADDRESSES) g_try_realloc (addr_buf, bufsize);
2271 ret = GetAdaptersAddresses (AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, addr_buf, &bufsize);
2274 ret == ERROR_BUFFER_OVERFLOW &&
2275 malloc_iterations < MAX_ALLOC_ITERATIONS);
2276 #undef MAX_ALLOC_ITERATIONS
2278 if (addr_buf == 0 || ret != NO_ERROR)
2281 g_free (wchar_name_or_ip);
2285 /* Step 5: Loop through adapters and check match for index or name */
2286 for (eth_adapter = addr_buf; eth_adapter != NULL; eth_adapter = eth_adapter->Next)
2288 /* Check if match for interface index/name: */
2289 gboolean any_match = (if_index > 0) && (eth_adapter->IfIndex == if_index);
2291 /* Check if match for friendly name - but only if NO if_index! */
2292 if (!any_match && if_index == 0 && eth_adapter->FriendlyName &&
2293 eth_adapter->FriendlyName[0] != 0 && wchar_name_or_ip != NULL)
2294 any_match = (_wcsicmp (eth_adapter->FriendlyName, wchar_name_or_ip) == 0);
2296 /* Check if match for adapter low level name - but only if NO if_index: */
2297 if (!any_match && if_index == 0 && eth_adapter->AdapterName &&
2298 eth_adapter->AdapterName[0] != 0)
2299 any_match = (stricmp (eth_adapter->AdapterName, name_or_ip) == 0);
2303 /* We have match for this adapter, lets get its local unicast IP address! */
2304 PIP_ADAPTER_UNICAST_ADDRESS uni_addr;
2305 for (uni_addr = eth_adapter->FirstUnicastAddress;
2306 uni_addr != NULL; uni_addr = uni_addr->Next)
2308 if (uni_addr->Address.lpSockaddr->sa_family == AF_INET)
2310 ip_result = ((PSOCKADDR_IN) uni_addr->Address.lpSockaddr)->sin_addr.S_un.S_addr;
2311 break; /* finished, exit unicast addr loop */
2318 g_free (wchar_name_or_ip);
2325 g_socket_multicast_group_operation (GSocket *socket,
2326 GInetAddress *group,
2327 gboolean source_specific,
2329 gboolean join_group,
2332 const guint8 *native_addr;
2333 gint optname, result;
2335 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2336 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2337 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2339 if (!check_socket (socket, error))
2342 native_addr = g_inet_address_to_bytes (group);
2343 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2345 #ifdef HAVE_IP_MREQN
2346 struct ip_mreqn mc_req;
2348 struct ip_mreq mc_req;
2351 memset (&mc_req, 0, sizeof (mc_req));
2352 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2354 #ifdef HAVE_IP_MREQN
2356 mc_req.imr_ifindex = if_nametoindex (iface);
2358 mc_req.imr_ifindex = 0; /* Pick any. */
2359 #elif defined(G_OS_WIN32)
2361 mc_req.imr_interface.s_addr = g_socket_w32_get_adapter_ipv4_addr (iface);
2363 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2365 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2368 if (source_specific)
2370 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2371 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2373 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2375 _("Error joining multicast group: %s") :
2376 _("Error leaving multicast group: %s"),
2377 _("No support for source-specific multicast"));
2382 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2383 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2384 &mc_req, sizeof (mc_req));
2386 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2388 struct ipv6_mreq mc_req_ipv6;
2390 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2391 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2392 #ifdef HAVE_IF_NAMETOINDEX
2394 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2397 mc_req_ipv6.ipv6mr_interface = 0;
2399 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2400 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2401 &mc_req_ipv6, sizeof (mc_req_ipv6));
2404 g_return_val_if_reached (FALSE);
2408 int errsv = get_socket_errno ();
2410 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2412 _("Error joining multicast group: %s") :
2413 _("Error leaving multicast group: %s"),
2414 socket_strerror (errsv));
2422 * g_socket_join_multicast_group:
2423 * @socket: a #GSocket.
2424 * @group: a #GInetAddress specifying the group address to join.
2425 * @iface: (nullable): Name of the interface to use, or %NULL
2426 * @source_specific: %TRUE if source-specific multicast should be used
2427 * @error: #GError for error reporting, or %NULL to ignore.
2429 * Registers @socket to receive multicast messages sent to @group.
2430 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2431 * been bound to an appropriate interface and port with
2434 * If @iface is %NULL, the system will automatically pick an interface
2435 * to bind to based on @group.
2437 * If @source_specific is %TRUE, source-specific multicast as defined
2438 * in RFC 4604 is used. Note that on older platforms this may fail
2439 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2441 * To bind to a given source-specific multicast address, use
2442 * g_socket_join_multicast_group_ssm() instead.
2444 * Returns: %TRUE on success, %FALSE on error.
2449 g_socket_join_multicast_group (GSocket *socket,
2450 GInetAddress *group,
2451 gboolean source_specific,
2455 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2459 * g_socket_leave_multicast_group:
2460 * @socket: a #GSocket.
2461 * @group: a #GInetAddress specifying the group address to leave.
2462 * @iface: (nullable): Interface used
2463 * @source_specific: %TRUE if source-specific multicast was used
2464 * @error: #GError for error reporting, or %NULL to ignore.
2466 * Removes @socket from the multicast group defined by @group, @iface,
2467 * and @source_specific (which must all have the same values they had
2468 * when you joined the group).
2470 * @socket remains bound to its address and port, and can still receive
2471 * unicast messages after calling this.
2473 * To unbind to a given source-specific multicast address, use
2474 * g_socket_leave_multicast_group_ssm() instead.
2476 * Returns: %TRUE on success, %FALSE on error.
2481 g_socket_leave_multicast_group (GSocket *socket,
2482 GInetAddress *group,
2483 gboolean source_specific,
2487 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2491 g_socket_multicast_group_operation_ssm (GSocket *socket,
2492 GInetAddress *group,
2493 GInetAddress *source_specific,
2495 gboolean join_group,
2500 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2501 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2502 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2503 g_return_val_if_fail (iface == NULL || *iface != '\0', FALSE);
2504 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2506 if (!source_specific)
2508 return g_socket_multicast_group_operation (socket, group, FALSE, iface,
2512 if (!check_socket (socket, error))
2515 switch (g_inet_address_get_family (group))
2517 case G_SOCKET_FAMILY_INVALID:
2518 case G_SOCKET_FAMILY_UNIX:
2520 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2522 _("Error joining multicast group: %s") :
2523 _("Error leaving multicast group: %s"),
2524 _("Unsupported socket family"));
2529 case G_SOCKET_FAMILY_IPV4:
2531 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2533 #ifdef BROKEN_IP_MREQ_SOURCE_STRUCT
2534 #define S_ADDR_FIELD(src) src.imr_interface
2536 #define S_ADDR_FIELD(src) src.imr_interface.s_addr
2540 struct ip_mreq_source mc_req_src;
2542 if (g_inet_address_get_family (source_specific) !=
2543 G_SOCKET_FAMILY_IPV4)
2545 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2547 _("Error joining multicast group: %s") :
2548 _("Error leaving multicast group: %s"),
2549 _("source-specific not an IPv4 address"));
2553 memset (&mc_req_src, 0, sizeof (mc_req_src));
2555 /* By default use the default IPv4 multicast interface. */
2556 S_ADDR_FIELD(mc_req_src) = g_htonl (INADDR_ANY);
2560 #if defined(G_OS_WIN32)
2561 S_ADDR_FIELD(mc_req_src) = g_socket_w32_get_adapter_ipv4_addr (iface);
2562 #elif defined (HAVE_SIOCGIFADDR)
2565 struct sockaddr_in *iface_addr;
2566 size_t if_name_len = strlen (iface);
2568 memset (&ifr, 0, sizeof (ifr));
2570 if (if_name_len >= sizeof (ifr.ifr_name))
2572 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FILENAME_TOO_LONG,
2573 _("Interface name too long"));
2577 memcpy (ifr.ifr_name, iface, if_name_len);
2579 /* Get the IPv4 address of the given network interface name. */
2580 ret = ioctl (socket->priv->fd, SIOCGIFADDR, &ifr);
2585 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2586 _("Interface not found: %s"), g_strerror (errsv));
2590 iface_addr = (struct sockaddr_in *) &ifr.ifr_addr;
2591 S_ADDR_FIELD(mc_req_src) = iface_addr->sin_addr.s_addr;
2592 #endif /* defined(G_OS_WIN32) && defined (HAVE_IF_NAMETOINDEX) */
2594 memcpy (&mc_req_src.imr_multiaddr, g_inet_address_to_bytes (group),
2595 g_inet_address_get_native_size (group));
2596 memcpy (&mc_req_src.imr_sourceaddr,
2597 g_inet_address_to_bytes (source_specific),
2598 g_inet_address_get_native_size (source_specific));
2601 join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2602 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2603 &mc_req_src, sizeof (mc_req_src));
2608 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2610 _("Error joining multicast group: %s") :
2611 _("Error leaving multicast group: %s"),
2612 _("No support for IPv4 source-specific multicast"));
2614 #endif /* IP_ADD_SOURCE_MEMBERSHIP */
2618 case G_SOCKET_FAMILY_IPV6:
2620 #ifdef MCAST_JOIN_SOURCE_GROUP
2623 struct group_source_req mc_req_src;
2624 GSocketAddress *saddr_group, *saddr_source_specific;
2625 guint iface_index = 0;
2627 #if defined (HAVE_IF_NAMETOINDEX)
2630 iface_index = if_nametoindex (iface);
2631 if (iface_index == 0)
2635 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2636 _("Interface not found: %s"), g_strerror (errsv));
2640 #endif /* defined (HAVE_IF_NAMETOINDEX) */
2641 mc_req_src.gsr_interface = iface_index;
2643 saddr_group = g_inet_socket_address_new (group, 0);
2644 res = g_socket_address_to_native (saddr_group, &mc_req_src.gsr_group,
2645 sizeof (mc_req_src.gsr_group),
2647 g_object_unref (saddr_group);
2651 saddr_source_specific = g_inet_socket_address_new (source_specific, 0);
2652 res = g_socket_address_to_native (saddr_source_specific,
2653 &mc_req_src.gsr_source,
2654 sizeof (mc_req_src.gsr_source),
2656 g_object_unref (saddr_source_specific);
2662 join_group ? MCAST_JOIN_SOURCE_GROUP : MCAST_LEAVE_SOURCE_GROUP;
2663 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2664 &mc_req_src, sizeof (mc_req_src));
2666 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2668 _("Error joining multicast group: %s") :
2669 _("Error leaving multicast group: %s"),
2670 _("No support for IPv6 source-specific multicast"));
2672 #endif /* MCAST_JOIN_SOURCE_GROUP */
2677 g_return_val_if_reached (FALSE);
2682 int errsv = get_socket_errno ();
2684 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2686 _("Error joining multicast group: %s") :
2687 _("Error leaving multicast group: %s"),
2688 socket_strerror (errsv));
2696 * g_socket_join_multicast_group_ssm:
2697 * @socket: a #GSocket.
2698 * @group: a #GInetAddress specifying the group address to join.
2699 * @source_specific: (nullable): a #GInetAddress specifying the
2700 * source-specific multicast address or %NULL to ignore.
2701 * @iface: (nullable): Name of the interface to use, or %NULL
2702 * @error: #GError for error reporting, or %NULL to ignore.
2704 * Registers @socket to receive multicast messages sent to @group.
2705 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2706 * been bound to an appropriate interface and port with
2709 * If @iface is %NULL, the system will automatically pick an interface
2710 * to bind to based on @group.
2712 * If @source_specific is not %NULL, use source-specific multicast as
2713 * defined in RFC 4604. Note that on older platforms this may fail
2714 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2716 * Note that this function can be called multiple times for the same
2717 * @group with different @source_specific in order to receive multicast
2718 * packets from more than one source.
2720 * Returns: %TRUE on success, %FALSE on error.
2725 g_socket_join_multicast_group_ssm (GSocket *socket,
2726 GInetAddress *group,
2727 GInetAddress *source_specific,
2731 return g_socket_multicast_group_operation_ssm (socket, group,
2732 source_specific, iface, TRUE, error);
2736 * g_socket_leave_multicast_group_ssm:
2737 * @socket: a #GSocket.
2738 * @group: a #GInetAddress specifying the group address to leave.
2739 * @source_specific: (nullable): a #GInetAddress specifying the
2740 * source-specific multicast address or %NULL to ignore.
2741 * @iface: (nullable): Name of the interface to use, or %NULL
2742 * @error: #GError for error reporting, or %NULL to ignore.
2744 * Removes @socket from the multicast group defined by @group, @iface,
2745 * and @source_specific (which must all have the same values they had
2746 * when you joined the group).
2748 * @socket remains bound to its address and port, and can still receive
2749 * unicast messages after calling this.
2751 * Returns: %TRUE on success, %FALSE on error.
2756 g_socket_leave_multicast_group_ssm (GSocket *socket,
2757 GInetAddress *group,
2758 GInetAddress *source_specific,
2762 return g_socket_multicast_group_operation_ssm (socket, group,
2763 source_specific, iface, FALSE, error);
2767 * g_socket_speaks_ipv4:
2768 * @socket: a #GSocket
2770 * Checks if a socket is capable of speaking IPv4.
2772 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2773 * and under some combinations of circumstances IPv6 sockets are also
2774 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2777 * No other types of sockets are currently considered as being capable
2780 * Returns: %TRUE if this socket can be used with IPv4.
2785 g_socket_speaks_ipv4 (GSocket *socket)
2787 switch (socket->priv->family)
2789 case G_SOCKET_FAMILY_IPV4:
2792 case G_SOCKET_FAMILY_IPV6:
2793 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2797 if (!g_socket_get_option (socket,
2798 IPPROTO_IPV6, IPV6_V6ONLY,
2815 * @socket: a #GSocket.
2816 * @cancellable: (nullable): a %GCancellable or %NULL
2817 * @error: #GError for error reporting, or %NULL to ignore.
2819 * Accept incoming connections on a connection-based socket. This removes
2820 * the first outstanding connection request from the listening socket and
2821 * creates a #GSocket object for it.
2823 * The @socket must be bound to a local address with g_socket_bind() and
2824 * must be listening for incoming connections (g_socket_listen()).
2826 * If there are no outstanding connections then the operation will block
2827 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2828 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2830 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2831 * Free the returned object with g_object_unref().
2836 g_socket_accept (GSocket *socket,
2837 GCancellable *cancellable,
2840 GSocket *new_socket;
2843 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2845 if (!check_socket (socket, error))
2848 if (!check_timeout (socket, error))
2853 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2855 int errsv = get_socket_errno ();
2860 #ifdef WSAEWOULDBLOCK
2861 if (errsv == WSAEWOULDBLOCK)
2863 if (errsv == EWOULDBLOCK ||
2867 win32_unset_event_mask (socket, FD_ACCEPT);
2869 if (socket->priv->blocking)
2871 if (!g_socket_condition_wait (socket,
2872 G_IO_IN, cancellable, error))
2879 socket_set_error_lazy (error, errsv, _("Error accepting connection: %s"));
2885 win32_unset_event_mask (socket, FD_ACCEPT);
2889 /* The socket inherits the accepting sockets event mask and even object,
2890 we need to remove that */
2891 WSAEventSelect (ret, NULL, 0);
2897 /* We always want to set close-on-exec to protect users. If you
2898 need to so some weird inheritance to exec you can re-enable this
2899 using lower level hacks with g_socket_get_fd(). */
2900 flags = fcntl (ret, F_GETFD, 0);
2902 (flags & FD_CLOEXEC) == 0)
2904 flags |= FD_CLOEXEC;
2905 fcntl (ret, F_SETFD, flags);
2910 new_socket = g_socket_new_from_fd (ret, error);
2911 if (new_socket == NULL)
2920 new_socket->priv->protocol = socket->priv->protocol;
2927 * @socket: a #GSocket.
2928 * @address: a #GSocketAddress specifying the remote address.
2929 * @cancellable: (nullable): a %GCancellable or %NULL
2930 * @error: #GError for error reporting, or %NULL to ignore.
2932 * Connect the socket to the specified remote address.
2934 * For connection oriented socket this generally means we attempt to make
2935 * a connection to the @address. For a connection-less socket it sets
2936 * the default address for g_socket_send() and discards all incoming datagrams
2937 * from other sources.
2939 * Generally connection oriented sockets can only connect once, but
2940 * connection-less sockets can connect multiple times to change the
2943 * If the connect call needs to do network I/O it will block, unless
2944 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2945 * and the user can be notified of the connection finishing by waiting
2946 * for the G_IO_OUT condition. The result of the connection must then be
2947 * checked with g_socket_check_connect_result().
2949 * Returns: %TRUE if connected, %FALSE on error.
2954 g_socket_connect (GSocket *socket,
2955 GSocketAddress *address,
2956 GCancellable *cancellable,
2960 struct sockaddr_storage storage;
2964 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2966 if (!check_socket (socket, error))
2969 if (!g_socket_address_to_native (address, &buffer.storage, sizeof buffer, error))
2972 if (socket->priv->remote_address)
2973 g_object_unref (socket->priv->remote_address);
2974 socket->priv->remote_address = g_object_ref (address);
2978 if (connect (socket->priv->fd, &buffer.sa,
2979 g_socket_address_get_native_size (address)) < 0)
2981 int errsv = get_socket_errno ();
2987 if (errsv == EINPROGRESS)
2989 if (errsv == WSAEWOULDBLOCK)
2992 win32_unset_event_mask (socket, FD_CONNECT);
2994 if (socket->priv->blocking)
2996 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2998 if (g_socket_check_connect_result (socket, error))
3004 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
3005 _("Connection in progress"));
3006 socket->priv->connect_pending = TRUE;
3010 g_set_error_literal (error, G_IO_ERROR,
3011 socket_io_error_from_errno (errsv),
3012 socket_strerror (errsv));
3019 win32_unset_event_mask (socket, FD_CONNECT);
3021 socket->priv->connected_read = TRUE;
3022 socket->priv->connected_write = TRUE;
3028 * g_socket_check_connect_result:
3029 * @socket: a #GSocket
3030 * @error: #GError for error reporting, or %NULL to ignore.
3032 * Checks and resets the pending connect error for the socket.
3033 * This is used to check for errors when g_socket_connect() is
3034 * used in non-blocking mode.
3036 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
3041 g_socket_check_connect_result (GSocket *socket,
3046 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3048 if (!check_socket (socket, error))
3051 if (!check_timeout (socket, error))
3054 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
3056 g_prefix_error (error, _("Unable to get pending error: "));
3062 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
3063 socket_strerror (value));
3064 if (socket->priv->remote_address)
3066 g_object_unref (socket->priv->remote_address);
3067 socket->priv->remote_address = NULL;
3072 socket->priv->connected_read = TRUE;
3073 socket->priv->connected_write = TRUE;
3079 * g_socket_get_available_bytes:
3080 * @socket: a #GSocket
3082 * Get the amount of data pending in the OS input buffer, without blocking.
3084 * If @socket is a UDP or SCTP socket, this will return the size of
3085 * just the next packet, even if additional packets are buffered after
3088 * Note that on Windows, this function is rather inefficient in the
3089 * UDP case, and so if you know any plausible upper bound on the size
3090 * of the incoming packet, it is better to just do a
3091 * g_socket_receive() with a buffer of that size, rather than calling
3092 * g_socket_get_available_bytes() first and then doing a receive of
3093 * exactly the right size.
3095 * Returns: the number of bytes that can be read from the socket
3096 * without blocking or truncating, or -1 on error.
3101 g_socket_get_available_bytes (GSocket *socket)
3104 const gint bufsize = 64 * 1024;
3105 static guchar *buf = NULL;
3113 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3115 if (!check_socket (socket, NULL))
3119 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
3122 if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
3124 if (G_UNLIKELY (g_once_init_enter (&buf)))
3125 g_once_init_leave (&buf, g_malloc (bufsize));
3127 /* On datagram sockets, FIONREAD ioctl is not reliable because many
3128 * systems add internal header size to the reported size, making it
3129 * unusable for this function. */
3130 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
3133 int errsv = get_socket_errno ();
3135 if (errsv == WSAEWOULDBLOCK)
3137 if (errsv == EWOULDBLOCK || errsv == EAGAIN)
3145 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
3147 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
3156 /* Block on a timed wait for @condition until (@start_time + @timeout).
3157 * Return %G_IO_ERROR_TIMED_OUT if the timeout is reached; otherwise %TRUE.
3160 block_on_timeout (GSocket *socket,
3161 GIOCondition condition,
3164 GCancellable *cancellable,
3167 gint64 wait_timeout = -1;
3169 g_return_val_if_fail (timeout_us != 0, TRUE);
3171 /* check if we've timed out or how much time to wait at most */
3172 if (timeout_us >= 0)
3174 gint64 elapsed = g_get_monotonic_time () - start_time;
3176 if (elapsed >= timeout_us)
3178 g_set_error_literal (error,
3179 G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3180 _("Socket I/O timed out"));
3184 wait_timeout = timeout_us - elapsed;
3187 return g_socket_condition_timed_wait (socket, condition, wait_timeout,
3188 cancellable, error);
3192 g_socket_receive_with_timeout (GSocket *socket,
3196 GCancellable *cancellable,
3202 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3204 start_time = g_get_monotonic_time ();
3206 if (!check_socket (socket, error))
3209 if (!check_timeout (socket, error))
3212 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3217 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
3219 int errsv = get_socket_errno ();
3224 #ifdef WSAEWOULDBLOCK
3225 if (errsv == WSAEWOULDBLOCK)
3227 if (errsv == EWOULDBLOCK ||
3231 win32_unset_event_mask (socket, FD_READ);
3233 if (timeout_us != 0)
3235 if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
3236 cancellable, error))
3243 win32_unset_event_mask (socket, FD_READ);
3245 socket_set_error_lazy (error, errsv, _("Error receiving data: %s"));
3249 win32_unset_event_mask (socket, FD_READ);
3259 * @socket: a #GSocket
3260 * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3261 * a buffer to read data into (which should be at least @size bytes long).
3262 * @size: the number of bytes you want to read from the socket
3263 * @cancellable: (nullable): a %GCancellable or %NULL
3264 * @error: #GError for error reporting, or %NULL to ignore.
3266 * Receive data (up to @size bytes) from a socket. This is mainly used by
3267 * connection-oriented sockets; it is identical to g_socket_receive_from()
3268 * with @address set to %NULL.
3270 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
3271 * g_socket_receive() will always read either 0 or 1 complete messages from
3272 * the socket. If the received message is too large to fit in @buffer, then
3273 * the data beyond @size bytes will be discarded, without any explicit
3274 * indication that this has occurred.
3276 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
3277 * number of bytes, up to @size. If more than @size bytes have been
3278 * received, the additional data will be returned in future calls to
3279 * g_socket_receive().
3281 * If the socket is in blocking mode the call will block until there
3282 * is some data to receive, the connection is closed, or there is an
3283 * error. If there is no data available and the socket is in
3284 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3285 * returned. To be notified when data is available, wait for the
3286 * %G_IO_IN condition.
3288 * On error -1 is returned and @error is set accordingly.
3290 * Returns: Number of bytes read, or 0 if the connection was closed by
3291 * the peer, or -1 on error
3296 g_socket_receive (GSocket *socket,
3299 GCancellable *cancellable,
3302 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3303 socket->priv->blocking ? -1 : 0,
3304 cancellable, error);
3308 * g_socket_receive_with_blocking:
3309 * @socket: a #GSocket
3310 * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3311 * a buffer to read data into (which should be at least @size bytes long).
3312 * @size: the number of bytes you want to read from the socket
3313 * @blocking: whether to do blocking or non-blocking I/O
3314 * @cancellable: (nullable): a %GCancellable or %NULL
3315 * @error: #GError for error reporting, or %NULL to ignore.
3317 * This behaves exactly the same as g_socket_receive(), except that
3318 * the choice of blocking or non-blocking behavior is determined by
3319 * the @blocking argument rather than by @socket's properties.
3321 * Returns: Number of bytes read, or 0 if the connection was closed by
3322 * the peer, or -1 on error
3327 g_socket_receive_with_blocking (GSocket *socket,
3331 GCancellable *cancellable,
3334 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3335 blocking ? -1 : 0, cancellable, error);
3339 * g_socket_receive_from:
3340 * @socket: a #GSocket
3341 * @address: (out) (optional): a pointer to a #GSocketAddress
3343 * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3344 * a buffer to read data into (which should be at least @size bytes long).
3345 * @size: the number of bytes you want to read from the socket
3346 * @cancellable: (nullable): a %GCancellable or %NULL
3347 * @error: #GError for error reporting, or %NULL to ignore.
3349 * Receive data (up to @size bytes) from a socket.
3351 * If @address is non-%NULL then @address will be set equal to the
3352 * source address of the received packet.
3353 * @address is owned by the caller.
3355 * See g_socket_receive() for additional information.
3357 * Returns: Number of bytes read, or 0 if the connection was closed by
3358 * the peer, or -1 on error
3363 g_socket_receive_from (GSocket *socket,
3364 GSocketAddress **address,
3367 GCancellable *cancellable,
3375 return g_socket_receive_message (socket,
3383 /* See the comment about SIGPIPE above. */
3385 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
3387 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
3391 g_socket_send_with_timeout (GSocket *socket,
3392 const guint8 *buffer,
3395 GCancellable *cancellable,
3401 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3403 start_time = g_get_monotonic_time ();
3405 if (!check_socket (socket, error))
3408 if (!check_timeout (socket, error))
3411 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3416 if ((ret = send (socket->priv->fd, (const char *)buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
3418 int errsv = get_socket_errno ();
3423 #ifdef WSAEWOULDBLOCK
3424 if (errsv == WSAEWOULDBLOCK)
3426 if (errsv == EWOULDBLOCK ||
3430 win32_unset_event_mask (socket, FD_WRITE);
3432 if (timeout_us != 0)
3434 if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
3435 cancellable, error))
3442 socket_set_error_lazy (error, errsv, _("Error sending data: %s"));
3453 * @socket: a #GSocket
3454 * @buffer: (array length=size) (element-type guint8): the buffer
3455 * containing the data to send.
3456 * @size: the number of bytes to send
3457 * @cancellable: (nullable): a %GCancellable or %NULL
3458 * @error: #GError for error reporting, or %NULL to ignore.
3460 * Tries to send @size bytes from @buffer on the socket. This is
3461 * mainly used by connection-oriented sockets; it is identical to
3462 * g_socket_send_to() with @address set to %NULL.
3464 * If the socket is in blocking mode the call will block until there is
3465 * space for the data in the socket queue. If there is no space available
3466 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3467 * will be returned. To be notified when space is available, wait for the
3468 * %G_IO_OUT condition. Note though that you may still receive
3469 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3470 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3471 * very common due to the way the underlying APIs work.)
3473 * On error -1 is returned and @error is set accordingly.
3475 * Returns: Number of bytes written (which may be less than @size), or -1
3481 g_socket_send (GSocket *socket,
3482 const gchar *buffer,
3484 GCancellable *cancellable,
3487 return g_socket_send_with_blocking (socket, buffer, size,
3488 socket->priv->blocking,
3489 cancellable, error);
3493 * g_socket_send_with_blocking:
3494 * @socket: a #GSocket
3495 * @buffer: (array length=size) (element-type guint8): the buffer
3496 * containing the data to send.
3497 * @size: the number of bytes to send
3498 * @blocking: whether to do blocking or non-blocking I/O
3499 * @cancellable: (nullable): a %GCancellable or %NULL
3500 * @error: #GError for error reporting, or %NULL to ignore.
3502 * This behaves exactly the same as g_socket_send(), except that
3503 * the choice of blocking or non-blocking behavior is determined by
3504 * the @blocking argument rather than by @socket's properties.
3506 * Returns: Number of bytes written (which may be less than @size), or -1
3512 g_socket_send_with_blocking (GSocket *socket,
3513 const gchar *buffer,
3516 GCancellable *cancellable,
3519 return g_socket_send_with_timeout (socket, (const guint8 *) buffer, size,
3520 blocking ? -1 : 0, cancellable, error);
3525 * @socket: a #GSocket
3526 * @address: (nullable): a #GSocketAddress, or %NULL
3527 * @buffer: (array length=size) (element-type guint8): the buffer
3528 * containing the data to send.
3529 * @size: the number of bytes to send
3530 * @cancellable: (nullable): a %GCancellable or %NULL
3531 * @error: #GError for error reporting, or %NULL to ignore.
3533 * Tries to send @size bytes from @buffer to @address. If @address is
3534 * %NULL then the message is sent to the default receiver (set by
3535 * g_socket_connect()).
3537 * See g_socket_send() for additional information.
3539 * Returns: Number of bytes written (which may be less than @size), or -1
3545 g_socket_send_to (GSocket *socket,
3546 GSocketAddress *address,
3547 const gchar *buffer,
3549 GCancellable *cancellable,
3557 return g_socket_send_message (socket,
3567 * g_socket_shutdown:
3568 * @socket: a #GSocket
3569 * @shutdown_read: whether to shut down the read side
3570 * @shutdown_write: whether to shut down the write side
3571 * @error: #GError for error reporting, or %NULL to ignore.
3573 * Shut down part or all of a full-duplex connection.
3575 * If @shutdown_read is %TRUE then the receiving side of the connection
3576 * is shut down, and further reading is disallowed.
3578 * If @shutdown_write is %TRUE then the sending side of the connection
3579 * is shut down, and further writing is disallowed.
3581 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
3583 * One example where it is useful to shut down only one side of a connection is
3584 * graceful disconnect for TCP connections where you close the sending side,
3585 * then wait for the other side to close the connection, thus ensuring that the
3586 * other side saw all sent data.
3588 * Returns: %TRUE on success, %FALSE on error
3593 g_socket_shutdown (GSocket *socket,
3594 gboolean shutdown_read,
3595 gboolean shutdown_write,
3600 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3602 if (!check_socket (socket, error))
3606 if (!shutdown_read && !shutdown_write)
3610 if (shutdown_read && shutdown_write)
3612 else if (shutdown_read)
3617 if (shutdown_read && shutdown_write)
3619 else if (shutdown_read)
3625 if (shutdown (socket->priv->fd, how) != 0)
3627 int errsv = get_socket_errno ();
3628 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
3629 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
3634 socket->priv->connected_read = FALSE;
3636 socket->priv->connected_write = FALSE;
3643 * @socket: a #GSocket
3644 * @error: #GError for error reporting, or %NULL to ignore.
3646 * Closes the socket, shutting down any active connection.
3648 * Closing a socket does not wait for all outstanding I/O operations
3649 * to finish, so the caller should not rely on them to be guaranteed
3650 * to complete even if the close returns with no error.
3652 * Once the socket is closed, all other operations will return
3653 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
3656 * Sockets will be automatically closed when the last reference
3657 * is dropped, but you might want to call this function to make sure
3658 * resources are released as early as possible.
3660 * Beware that due to the way that TCP works, it is possible for
3661 * recently-sent data to be lost if either you close a socket while the
3662 * %G_IO_IN condition is set, or else if the remote connection tries to
3663 * send something to you after you close the socket but before it has
3664 * finished reading all of the data you sent. There is no easy generic
3665 * way to avoid this problem; the easiest fix is to design the network
3666 * protocol such that the client will never send data "out of turn".
3667 * Another solution is for the server to half-close the connection by
3668 * calling g_socket_shutdown() with only the @shutdown_write flag set,
3669 * and then wait for the client to notice this and close its side of the
3670 * connection, after which the server can safely call g_socket_close().
3671 * (This is what #GTcpConnection does if you call
3672 * g_tcp_connection_set_graceful_disconnect(). But of course, this
3673 * only works if the client will close its connection after the server
3676 * Returns: %TRUE on success, %FALSE on error
3681 g_socket_close (GSocket *socket,
3686 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3688 if (socket->priv->closed)
3689 return TRUE; /* Multiple close not an error */
3691 if (!check_socket (socket, error))
3697 res = closesocket (socket->priv->fd);
3699 res = close (socket->priv->fd);
3703 int errsv = get_socket_errno ();
3708 g_set_error (error, G_IO_ERROR,
3709 socket_io_error_from_errno (errsv),
3710 _("Error closing socket: %s"),
3711 socket_strerror (errsv));
3717 socket->priv->fd = -1;
3718 socket->priv->connected_read = FALSE;
3719 socket->priv->connected_write = FALSE;
3720 socket->priv->closed = TRUE;
3721 if (socket->priv->remote_address)
3723 g_object_unref (socket->priv->remote_address);
3724 socket->priv->remote_address = NULL;
3731 * g_socket_is_closed:
3732 * @socket: a #GSocket
3734 * Checks whether a socket is closed.
3736 * Returns: %TRUE if socket is closed, %FALSE otherwise
3741 g_socket_is_closed (GSocket *socket)
3743 return socket->priv->closed;
3746 /* Broken source, used on errors */
3748 broken_dispatch (GSource *source,
3749 GSourceFunc callback,
3755 static GSourceFuncs broken_funcs =
3765 network_events_for_condition (GIOCondition condition)
3769 if (condition & G_IO_IN)
3770 event_mask |= (FD_READ | FD_ACCEPT);
3771 if (condition & G_IO_OUT)
3772 event_mask |= (FD_WRITE | FD_CONNECT);
3773 event_mask |= FD_CLOSE;
3779 ensure_event (GSocket *socket)
3781 if (socket->priv->event == WSA_INVALID_EVENT)
3782 socket->priv->event = WSACreateEvent();
3786 update_select_events (GSocket *socket)
3793 ensure_event (socket);
3796 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3799 event_mask |= network_events_for_condition (*ptr);
3802 if (event_mask != socket->priv->selected_events)
3804 /* If no events selected, disable event so we can unset
3807 if (event_mask == 0)
3810 event = socket->priv->event;
3812 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3813 socket->priv->selected_events = event_mask;
3818 add_condition_watch (GSocket *socket,
3819 GIOCondition *condition)
3821 g_mutex_lock (&socket->priv->win32_source_lock);
3822 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3824 socket->priv->requested_conditions =
3825 g_list_prepend (socket->priv->requested_conditions, condition);
3827 update_select_events (socket);
3828 g_mutex_unlock (&socket->priv->win32_source_lock);
3832 remove_condition_watch (GSocket *socket,
3833 GIOCondition *condition)
3835 g_mutex_lock (&socket->priv->win32_source_lock);
3836 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3838 socket->priv->requested_conditions =
3839 g_list_remove (socket->priv->requested_conditions, condition);
3841 update_select_events (socket);
3842 g_mutex_unlock (&socket->priv->win32_source_lock);
3846 update_condition_unlocked (GSocket *socket)
3848 WSANETWORKEVENTS events;
3849 GIOCondition condition;
3851 if (WSAEnumNetworkEvents (socket->priv->fd,
3852 socket->priv->event,
3855 socket->priv->current_events |= events.lNetworkEvents;
3856 if (events.lNetworkEvents & FD_WRITE &&
3857 events.iErrorCode[FD_WRITE_BIT] != 0)
3858 socket->priv->current_errors |= FD_WRITE;
3859 if (events.lNetworkEvents & FD_CONNECT &&
3860 events.iErrorCode[FD_CONNECT_BIT] != 0)
3861 socket->priv->current_errors |= FD_CONNECT;
3865 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3866 condition |= G_IO_IN;
3868 if (socket->priv->current_events & FD_CLOSE)
3870 int r, errsv, buffer;
3872 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3874 errsv = get_socket_errno ();
3877 (r < 0 && errsv == WSAENOTCONN))
3878 condition |= G_IO_IN;
3880 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3881 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3882 condition |= G_IO_HUP;
3884 condition |= G_IO_ERR;
3887 if (socket->priv->closed)
3888 condition |= G_IO_HUP;
3890 /* Never report both G_IO_OUT and HUP, these are
3891 mutually exclusive (can't write to a closed socket) */
3892 if ((condition & G_IO_HUP) == 0 &&
3893 socket->priv->current_events & FD_WRITE)
3895 if (socket->priv->current_errors & FD_WRITE)
3896 condition |= G_IO_ERR;
3898 condition |= G_IO_OUT;
3902 if (socket->priv->current_events & FD_CONNECT)
3904 if (socket->priv->current_errors & FD_CONNECT)
3905 condition |= (G_IO_HUP | G_IO_ERR);
3907 condition |= G_IO_OUT;
3915 update_condition (GSocket *socket)
3918 g_mutex_lock (&socket->priv->win32_source_lock);
3919 res = update_condition_unlocked (socket);
3920 g_mutex_unlock (&socket->priv->win32_source_lock);
3933 GIOCondition condition;
3937 socket_source_prepare (GSource *source,
3940 GSocketSource *socket_source = (GSocketSource *)source;
3945 if ((socket_source->pollfd.revents & G_IO_NVAL) != 0)
3948 if (g_socket_is_closed (socket_source->socket))
3950 g_source_remove_poll (source, &socket_source->pollfd);
3951 socket_source->pollfd.revents = G_IO_NVAL;
3955 return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3957 return g_socket_is_closed (socket_source->socket) && socket_source->fd_tag != NULL;
3963 socket_source_check_win32 (GSource *source)
3967 return socket_source_prepare (source, &timeout);
3972 socket_source_dispatch (GSource *source,
3973 GSourceFunc callback,
3976 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3977 GSocketSource *socket_source = (GSocketSource *)source;
3978 GSocket *socket = socket_source->socket;
3984 events = update_condition (socket_source->socket);
3986 if (g_socket_is_closed (socket_source->socket))
3988 if (socket_source->fd_tag)
3989 g_source_remove_unix_fd (source, socket_source->fd_tag);
3990 socket_source->fd_tag = NULL;
3995 events = g_source_query_unix_fd (source, socket_source->fd_tag);
3999 timeout = g_source_get_ready_time (source);
4000 if (timeout >= 0 && timeout < g_source_get_time (source) &&
4001 !g_socket_is_closed (socket_source->socket))
4003 socket->priv->timed_out = TRUE;
4004 events |= (G_IO_IN | G_IO_OUT);
4007 ret = (*func) (socket, events & socket_source->condition, user_data);
4009 if (socket->priv->timeout && !g_socket_is_closed (socket_source->socket))
4010 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
4012 g_source_set_ready_time (source, -1);
4018 socket_source_finalize (GSource *source)
4020 GSocketSource *socket_source = (GSocketSource *)source;
4023 socket = socket_source->socket;
4026 remove_condition_watch (socket, &socket_source->condition);
4029 g_object_unref (socket);
4033 socket_source_closure_callback (GSocket *socket,
4034 GIOCondition condition,
4037 GClosure *closure = data;
4039 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
4040 GValue result_value = G_VALUE_INIT;
4043 g_value_init (&result_value, G_TYPE_BOOLEAN);
4045 g_value_init (¶ms[0], G_TYPE_SOCKET);
4046 g_value_set_object (¶ms[0], socket);
4047 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
4048 g_value_set_flags (¶ms[1], condition);
4050 g_closure_invoke (closure, &result_value, 2, params, NULL);
4052 result = g_value_get_boolean (&result_value);
4053 g_value_unset (&result_value);
4054 g_value_unset (¶ms[0]);
4055 g_value_unset (¶ms[1]);
4060 static GSourceFuncs socket_source_funcs =
4062 socket_source_prepare,
4064 socket_source_check_win32,
4068 socket_source_dispatch,
4069 socket_source_finalize,
4070 (GSourceFunc)socket_source_closure_callback,
4074 socket_source_new (GSocket *socket,
4075 GIOCondition condition,
4076 GCancellable *cancellable)
4079 GSocketSource *socket_source;
4082 ensure_event (socket);
4084 if (socket->priv->event == WSA_INVALID_EVENT)
4086 g_warning ("Failed to create WSAEvent");
4087 return g_source_new (&broken_funcs, sizeof (GSource));
4091 if (!check_socket (socket, NULL))
4093 g_warning ("Socket check failed");
4094 return g_source_new (&broken_funcs, sizeof (GSource));
4097 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
4099 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
4100 g_source_set_name (source, "GSocket");
4101 socket_source = (GSocketSource *)source;
4103 socket_source->socket = g_object_ref (socket);
4104 socket_source->condition = condition;
4108 GSource *cancellable_source;
4110 cancellable_source = g_cancellable_source_new (cancellable);
4111 g_source_add_child_source (source, cancellable_source);
4112 g_source_set_dummy_callback (cancellable_source);
4113 g_source_unref (cancellable_source);
4117 add_condition_watch (socket, &socket_source->condition);
4118 socket_source->pollfd.fd = (gintptr) socket->priv->event;
4119 socket_source->pollfd.events = condition;
4120 socket_source->pollfd.revents = 0;
4121 g_source_add_poll (source, &socket_source->pollfd);
4123 socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
4126 if (socket->priv->timeout)
4127 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
4129 g_source_set_ready_time (source, -1);
4135 * g_socket_create_source: (skip)
4136 * @socket: a #GSocket
4137 * @condition: a #GIOCondition mask to monitor
4138 * @cancellable: (nullable): a %GCancellable or %NULL
4140 * Creates a #GSource that can be attached to a %GMainContext to monitor
4141 * for the availability of the specified @condition on the socket. The #GSource
4142 * keeps a reference to the @socket.
4144 * The callback on the source is of the #GSocketSourceFunc type.
4146 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
4147 * these conditions will always be reported output if they are true.
4149 * @cancellable if not %NULL can be used to cancel the source, which will
4150 * cause the source to trigger, reporting the current condition (which
4151 * is likely 0 unless cancellation happened at the same time as a
4152 * condition change). You can check for this in the callback using
4153 * g_cancellable_is_cancelled().
4155 * If @socket has a timeout set, and it is reached before @condition
4156 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
4157 * %G_IO_OUT depending on @condition. However, @socket will have been
4158 * marked as having had a timeout, and so the next #GSocket I/O method
4159 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
4161 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
4166 g_socket_create_source (GSocket *socket,
4167 GIOCondition condition,
4168 GCancellable *cancellable)
4170 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
4172 return socket_source_new (socket, condition, cancellable);
4176 * g_socket_condition_check:
4177 * @socket: a #GSocket
4178 * @condition: a #GIOCondition mask to check
4180 * Checks on the readiness of @socket to perform operations.
4181 * The operations specified in @condition are checked for and masked
4182 * against the currently-satisfied conditions on @socket. The result
4185 * Note that on Windows, it is possible for an operation to return
4186 * %G_IO_ERROR_WOULD_BLOCK even immediately after
4187 * g_socket_condition_check() has claimed that the socket is ready for
4188 * writing. Rather than calling g_socket_condition_check() and then
4189 * writing to the socket if it succeeds, it is generally better to
4190 * simply try writing to the socket right away, and try again later if
4191 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
4193 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
4194 * these conditions will always be set in the output if they are true.
4196 * This call never blocks.
4198 * Returns: the @GIOCondition mask of the current state
4203 g_socket_condition_check (GSocket *socket,
4204 GIOCondition condition)
4206 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
4208 if (!check_socket (socket, NULL))
4213 GIOCondition current_condition;
4215 condition |= G_IO_ERR | G_IO_HUP;
4217 add_condition_watch (socket, &condition);
4218 current_condition = update_condition (socket);
4219 remove_condition_watch (socket, &condition);
4220 return condition & current_condition;
4226 poll_fd.fd = socket->priv->fd;
4227 poll_fd.events = condition;
4228 poll_fd.revents = 0;
4231 result = g_poll (&poll_fd, 1, 0);
4232 while (result == -1 && get_socket_errno () == EINTR);
4234 return poll_fd.revents;
4240 * g_socket_condition_wait:
4241 * @socket: a #GSocket
4242 * @condition: a #GIOCondition mask to wait for
4243 * @cancellable: (nullable): a #GCancellable, or %NULL
4244 * @error: a #GError pointer, or %NULL
4246 * Waits for @condition to become true on @socket. When the condition
4247 * is met, %TRUE is returned.
4249 * If @cancellable is cancelled before the condition is met, or if the
4250 * socket has a timeout set and it is reached before the condition is
4251 * met, then %FALSE is returned and @error, if non-%NULL, is set to
4252 * the appropriate value (%G_IO_ERROR_CANCELLED or
4253 * %G_IO_ERROR_TIMED_OUT).
4255 * See also g_socket_condition_timed_wait().
4257 * Returns: %TRUE if the condition was met, %FALSE otherwise
4262 g_socket_condition_wait (GSocket *socket,
4263 GIOCondition condition,
4264 GCancellable *cancellable,
4267 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4269 return g_socket_condition_timed_wait (socket, condition, -1,
4270 cancellable, error);
4274 * g_socket_condition_timed_wait:
4275 * @socket: a #GSocket
4276 * @condition: a #GIOCondition mask to wait for
4277 * @timeout_us: the maximum time (in microseconds) to wait, or -1
4278 * @cancellable: (nullable): a #GCancellable, or %NULL
4279 * @error: a #GError pointer, or %NULL
4281 * Waits for up to @timeout_us microseconds for @condition to become true
4282 * on @socket. If the condition is met, %TRUE is returned.
4284 * If @cancellable is cancelled before the condition is met, or if
4285 * @timeout_us (or the socket's #GSocket:timeout) is reached before the
4286 * condition is met, then %FALSE is returned and @error, if non-%NULL,
4287 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
4288 * %G_IO_ERROR_TIMED_OUT).
4290 * If you don't want a timeout, use g_socket_condition_wait().
4291 * (Alternatively, you can pass -1 for @timeout_us.)
4293 * Note that although @timeout_us is in microseconds for consistency with
4294 * other GLib APIs, this function actually only has millisecond
4295 * resolution, and the behavior is undefined if @timeout_us is not an
4296 * exact number of milliseconds.
4298 * Returns: %TRUE if the condition was met, %FALSE otherwise
4303 g_socket_condition_timed_wait (GSocket *socket,
4304 GIOCondition condition,
4306 GCancellable *cancellable,
4312 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4314 if (!check_socket (socket, error))
4317 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4320 if (socket->priv->timeout &&
4321 (timeout_us < 0 || socket->priv->timeout < timeout_us / G_USEC_PER_SEC))
4322 timeout_ms = (gint64) socket->priv->timeout * 1000;
4323 else if (timeout_us != -1)
4324 timeout_ms = timeout_us / 1000;
4328 start_time = g_get_monotonic_time ();
4332 GIOCondition current_condition;
4338 /* Always check these */
4339 condition |= G_IO_ERR | G_IO_HUP;
4341 add_condition_watch (socket, &condition);
4344 events[num_events++] = socket->priv->event;
4346 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
4347 events[num_events++] = (WSAEVENT)cancel_fd.fd;
4349 if (timeout_ms == -1)
4350 timeout_ms = WSA_INFINITE;
4352 g_mutex_lock (&socket->priv->win32_source_lock);
4353 current_condition = update_condition_unlocked (socket);
4354 while ((condition & current_condition) == 0)
4356 if (!socket->priv->waiting)
4358 socket->priv->waiting = TRUE;
4359 socket->priv->waiting_result = 0;
4360 g_mutex_unlock (&socket->priv->win32_source_lock);
4362 res = WSAWaitForMultipleEvents (num_events, events, FALSE, timeout_ms, FALSE);
4364 g_mutex_lock (&socket->priv->win32_source_lock);
4365 socket->priv->waiting = FALSE;
4366 socket->priv->waiting_result = res;
4367 g_cond_broadcast (&socket->priv->win32_source_cond);
4371 if (timeout_ms != WSA_INFINITE)
4373 if (!g_cond_wait_until (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock, timeout_ms))
4375 res = WSA_WAIT_TIMEOUT;
4380 res = socket->priv->waiting_result;
4385 g_cond_wait (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock);
4386 res = socket->priv->waiting_result;
4390 if (res == WSA_WAIT_FAILED)
4392 int errsv = get_socket_errno ();
4394 g_set_error (error, G_IO_ERROR,
4395 socket_io_error_from_errno (errsv),
4396 _("Waiting for socket condition: %s"),
4397 socket_strerror (errsv));
4400 else if (res == WSA_WAIT_TIMEOUT)
4402 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4403 _("Socket I/O timed out"));
4407 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4410 current_condition = update_condition_unlocked (socket);
4412 if (timeout_ms != WSA_INFINITE)
4414 timeout_ms -= (g_get_monotonic_time () - start_time) * 1000;
4419 g_mutex_unlock (&socket->priv->win32_source_lock);
4420 remove_condition_watch (socket, &condition);
4422 g_cancellable_release_fd (cancellable);
4424 return (condition & current_condition) != 0;
4432 poll_fd[0].fd = socket->priv->fd;
4433 poll_fd[0].events = condition;
4436 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
4442 result = g_poll (poll_fd, num, timeout_ms);
4444 if (result != -1 || errsv != EINTR)
4447 if (timeout_ms != -1)
4449 timeout_ms -= (g_get_monotonic_time () - start_time) / 1000;
4456 g_cancellable_release_fd (cancellable);
4460 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4461 _("Socket I/O timed out"));
4465 return !g_cancellable_set_error_if_cancelled (cancellable, error);
4472 /* Unfortunately these have to be macros rather than inline functions due to
4473 * using alloca(). */
4474 #define output_message_to_msghdr(message, prev_message, msg, prev_msg, error) \
4476 const GOutputMessage *_message = (message); \
4477 const GOutputMessage *_prev_message = (prev_message); \
4478 struct msghdr *_msg = (msg); \
4479 const struct msghdr *_prev_msg = (prev_msg); \
4480 GError **_error = (error); \
4482 _msg->msg_flags = 0; \
4485 if (_prev_message != NULL && _prev_message->address == _message->address) \
4487 _msg->msg_name = _prev_msg->msg_name; \
4488 _msg->msg_namelen = _prev_msg->msg_namelen; \
4490 else if (_message->address != NULL) \
4492 _msg->msg_namelen = g_socket_address_get_native_size (_message->address); \
4493 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4494 if (!g_socket_address_to_native (_message->address, _msg->msg_name, \
4495 _msg->msg_namelen, _error)) \
4500 _msg->msg_name = NULL; \
4501 _msg->msg_namelen = 0; \
4506 /* this entire expression will be evaluated at compile time */ \
4507 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4508 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4509 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4510 G_STRUCT_OFFSET (GOutputVector, buffer) && \
4511 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4512 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4513 G_STRUCT_OFFSET (GOutputVector, size)) \
4514 /* ABI is compatible */ \
4516 _msg->msg_iov = (struct iovec *) _message->vectors; \
4517 _msg->msg_iovlen = _message->num_vectors; \
4520 /* ABI is incompatible */ \
4524 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4525 for (i = 0; i < _message->num_vectors; i++) \
4527 _msg->msg_iov[i].iov_base = (void *) _message->vectors[i].buffer; \
4528 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4530 _msg->msg_iovlen = _message->num_vectors; \
4536 struct cmsghdr *cmsg; \
4539 _msg->msg_controllen = 0; \
4540 for (i = 0; i < _message->num_control_messages; i++) \
4541 _msg->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (_message->control_messages[i])); \
4543 if (_msg->msg_controllen == 0) \
4544 _msg->msg_control = NULL; \
4547 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4548 memset (_msg->msg_control, '\0', _msg->msg_controllen); \
4551 cmsg = CMSG_FIRSTHDR (_msg); \
4552 for (i = 0; i < _message->num_control_messages; i++) \
4554 cmsg->cmsg_level = g_socket_control_message_get_level (_message->control_messages[i]); \
4555 cmsg->cmsg_type = g_socket_control_message_get_msg_type (_message->control_messages[i]); \
4556 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (_message->control_messages[i])); \
4557 g_socket_control_message_serialize (_message->control_messages[i], \
4558 CMSG_DATA (cmsg)); \
4559 cmsg = CMSG_NXTHDR (_msg, cmsg); \
4561 g_assert (cmsg == NULL); \
4565 #define input_message_to_msghdr(message, msg) \
4567 const GInputMessage *_message = (message); \
4568 struct msghdr *_msg = (msg); \
4571 if (_message->address) \
4573 _msg->msg_namelen = sizeof (struct sockaddr_storage); \
4574 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4578 _msg->msg_name = NULL; \
4579 _msg->msg_namelen = 0; \
4583 /* this entire expression will be evaluated at compile time */ \
4584 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4585 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4586 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4587 G_STRUCT_OFFSET (GInputVector, buffer) && \
4588 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4589 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4590 G_STRUCT_OFFSET (GInputVector, size)) \
4591 /* ABI is compatible */ \
4593 _msg->msg_iov = (struct iovec *) _message->vectors; \
4594 _msg->msg_iovlen = _message->num_vectors; \
4597 /* ABI is incompatible */ \
4601 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4602 for (i = 0; i < _message->num_vectors; i++) \
4604 _msg->msg_iov[i].iov_base = _message->vectors[i].buffer; \
4605 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4607 _msg->msg_iovlen = _message->num_vectors; \
4611 if (_message->control_messages == NULL) \
4613 _msg->msg_controllen = 0; \
4614 _msg->msg_control = NULL; \
4618 _msg->msg_controllen = 2048; \
4619 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4623 _msg->msg_flags = _message->flags; \
4627 input_message_from_msghdr (const struct msghdr *msg,
4628 GInputMessage *message,
4631 /* decode address */
4632 if (message->address != NULL)
4634 *message->address = cache_recv_address (socket, msg->msg_name,
4638 /* decode control messages */
4640 GPtrArray *my_messages = NULL;
4641 struct cmsghdr *cmsg;
4643 if (msg->msg_controllen >= sizeof (struct cmsghdr))
4645 g_assert (message->control_messages != NULL);
4646 for (cmsg = CMSG_FIRSTHDR (msg);
4648 cmsg = CMSG_NXTHDR ((struct msghdr *) msg, cmsg))
4650 GSocketControlMessage *control_message;
4652 control_message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4654 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4656 if (control_message == NULL)
4657 /* We've already spewed about the problem in the
4658 deserialization code, so just continue */
4661 if (my_messages == NULL)
4662 my_messages = g_ptr_array_new ();
4663 g_ptr_array_add (my_messages, control_message);
4667 if (message->num_control_messages)
4668 *message->num_control_messages = my_messages != NULL ? my_messages->len : 0;
4670 if (message->control_messages)
4672 if (my_messages == NULL)
4674 *message->control_messages = NULL;
4678 g_ptr_array_add (my_messages, NULL);
4679 *message->control_messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4684 g_assert (my_messages == NULL);
4688 /* capture the flags */
4689 message->flags = msg->msg_flags;
4694 * g_socket_send_message:
4695 * @socket: a #GSocket
4696 * @address: (nullable): a #GSocketAddress, or %NULL
4697 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4698 * @num_vectors: the number of elements in @vectors, or -1
4699 * @messages: (array length=num_messages) (nullable): a pointer to an
4700 * array of #GSocketControlMessages, or %NULL.
4701 * @num_messages: number of elements in @messages, or -1.
4702 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
4703 * contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
4704 * @cancellable: (nullable): a %GCancellable or %NULL
4705 * @error: #GError for error reporting, or %NULL to ignore.
4707 * Send data to @address on @socket. For sending multiple messages see
4708 * g_socket_send_messages(); for easier use, see
4709 * g_socket_send() and g_socket_send_to().
4711 * If @address is %NULL then the message is sent to the default receiver
4712 * (set by g_socket_connect()).
4714 * @vectors must point to an array of #GOutputVector structs and
4715 * @num_vectors must be the length of this array. (If @num_vectors is -1,
4716 * then @vectors is assumed to be terminated by a #GOutputVector with a
4717 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
4718 * that the sent data will be gathered from. Using multiple
4719 * #GOutputVectors is more memory-efficient than manually copying
4720 * data from multiple sources into a single buffer, and more
4721 * network-efficient than making multiple calls to g_socket_send().
4723 * @messages, if non-%NULL, is taken to point to an array of @num_messages
4724 * #GSocketControlMessage instances. These correspond to the control
4725 * messages to be sent on the socket.
4726 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
4729 * @flags modify how the message is sent. The commonly available arguments
4730 * for this are available in the #GSocketMsgFlags enum, but the
4731 * values there are the same as the system values, and the flags
4732 * are passed in as-is, so you can pass in system-specific flags too.
4734 * If the socket is in blocking mode the call will block until there is
4735 * space for the data in the socket queue. If there is no space available
4736 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4737 * will be returned. To be notified when space is available, wait for the
4738 * %G_IO_OUT condition. Note though that you may still receive
4739 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4740 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4741 * very common due to the way the underlying APIs work.)
4743 * On error -1 is returned and @error is set accordingly.
4745 * Returns: Number of bytes written (which may be less than @size), or -1
4751 g_socket_send_message (GSocket *socket,
4752 GSocketAddress *address,
4753 GOutputVector *vectors,
4755 GSocketControlMessage **messages,
4758 GCancellable *cancellable,
4761 GPollableReturn res;
4762 gsize bytes_written = 0;
4764 res = g_socket_send_message_with_timeout (socket, address,
4765 vectors, num_vectors,
4766 messages, num_messages, flags,
4767 socket->priv->blocking ? -1 : 0,
4769 cancellable, error);
4771 if (res == G_POLLABLE_RETURN_WOULD_BLOCK)
4774 socket_set_error_lazy (error, EWOULDBLOCK, _("Error sending message: %s"));
4776 socket_set_error_lazy (error, WSAEWOULDBLOCK, _("Error sending message: %s"));
4780 return res == G_POLLABLE_RETURN_OK ? bytes_written : -1;
4784 * g_socket_send_message_with_timeout:
4785 * @socket: a #GSocket
4786 * @address: (nullable): a #GSocketAddress, or %NULL
4787 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4788 * @num_vectors: the number of elements in @vectors, or -1
4789 * @messages: (array length=num_messages) (nullable): a pointer to an
4790 * array of #GSocketControlMessages, or %NULL.
4791 * @num_messages: number of elements in @messages, or -1.
4792 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
4793 * contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
4794 * @timeout_us: the maximum time (in microseconds) to wait, or -1
4795 * @bytes_written: (out) (optional): location to store the number of bytes that were written to the socket
4796 * @cancellable: (nullable): a %GCancellable or %NULL
4797 * @error: #GError for error reporting, or %NULL to ignore.
4799 * This behaves exactly the same as g_socket_send_message(), except that
4800 * the choice of timeout behavior is determined by the @timeout_us argument
4801 * rather than by @socket's properties.
4803 * On error %G_POLLABLE_RETURN_FAILED is returned and @error is set accordingly, or
4804 * if the socket is currently not writable %G_POLLABLE_RETURN_WOULD_BLOCK is
4805 * returned. @bytes_written will contain 0 in both cases.
4807 * Returns: %G_POLLABLE_RETURN_OK if all data was successfully written,
4808 * %G_POLLABLE_RETURN_WOULD_BLOCK if the socket is currently not writable, or
4809 * %G_POLLABLE_RETURN_FAILED if an error happened and @error is set.
4814 g_socket_send_message_with_timeout (GSocket *socket,
4815 GSocketAddress *address,
4816 const GOutputVector *vectors,
4818 GSocketControlMessage **messages,
4822 gsize *bytes_written,
4823 GCancellable *cancellable,
4826 GOutputVector one_vector;
4833 g_return_val_if_fail (G_IS_SOCKET (socket), G_POLLABLE_RETURN_FAILED);
4834 g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), G_POLLABLE_RETURN_FAILED);
4835 g_return_val_if_fail (num_vectors == 0 || vectors != NULL, G_POLLABLE_RETURN_FAILED);
4836 g_return_val_if_fail (num_messages == 0 || messages != NULL, G_POLLABLE_RETURN_FAILED);
4837 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), G_POLLABLE_RETURN_FAILED);
4838 g_return_val_if_fail (error == NULL || *error == NULL, G_POLLABLE_RETURN_FAILED);
4840 start_time = g_get_monotonic_time ();
4842 if (!check_socket (socket, error))
4843 return G_POLLABLE_RETURN_FAILED;
4845 if (!check_timeout (socket, error))
4846 return G_POLLABLE_RETURN_FAILED;
4848 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4849 return G_POLLABLE_RETURN_FAILED;
4851 if (num_vectors == -1)
4853 for (num_vectors = 0;
4854 vectors[num_vectors].buffer != NULL;
4859 if (num_messages == -1)
4861 for (num_messages = 0;
4862 messages != NULL && messages[num_messages] != NULL;
4867 if (num_vectors == 0)
4871 one_vector.buffer = &zero;
4872 one_vector.size = 1;
4874 vectors = &one_vector;
4879 GOutputMessage output_message;
4882 GError *child_error = NULL;
4884 output_message.address = address;
4885 output_message.vectors = (GOutputVector *) vectors;
4886 output_message.num_vectors = num_vectors;
4887 output_message.bytes_sent = 0;
4888 output_message.control_messages = messages;
4889 output_message.num_control_messages = num_messages;
4891 output_message_to_msghdr (&output_message, NULL, &msg, NULL, &child_error);
4893 if (child_error != NULL)
4895 g_propagate_error (error, child_error);
4896 return G_POLLABLE_RETURN_FAILED;
4901 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4904 int errsv = get_socket_errno ();
4909 if (errsv == EWOULDBLOCK || errsv == EAGAIN)
4911 if (timeout_us != 0)
4913 if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
4914 cancellable, error))
4915 return G_POLLABLE_RETURN_FAILED;
4920 return G_POLLABLE_RETURN_WOULD_BLOCK;
4923 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4924 return G_POLLABLE_RETURN_FAILED;
4930 *bytes_written = result;
4932 return G_POLLABLE_RETURN_OK;
4936 struct sockaddr_storage addr;
4943 /* Win32 doesn't support control messages.
4944 Actually this is possible for raw and datagram sockets
4945 via WSASendMessage on Vista or later, but that doesn't
4947 if (num_messages != 0)
4949 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
4950 _("GSocketControlMessage not supported on Windows"));
4951 return G_POLLABLE_RETURN_FAILED;
4955 bufs = g_newa (WSABUF, num_vectors);
4956 for (i = 0; i < num_vectors; i++)
4958 bufs[i].buf = (char *)vectors[i].buffer;
4959 bufs[i].len = (gulong)vectors[i].size;
4963 addrlen = 0; /* Avoid warning */
4966 addrlen = g_socket_address_get_native_size (address);
4967 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
4968 return G_POLLABLE_RETURN_FAILED;
4974 result = WSASendTo (socket->priv->fd,
4977 (const struct sockaddr *)&addr, addrlen,
4980 result = WSASend (socket->priv->fd,
4987 int errsv = get_socket_errno ();
4989 if (errsv == WSAEINTR)
4992 if (errsv == WSAEWOULDBLOCK)
4994 win32_unset_event_mask (socket, FD_WRITE);
4996 if (timeout_us != 0)
4998 if (!block_on_timeout (socket, G_IO_OUT, timeout_us,
4999 start_time, cancellable, error))
5000 return G_POLLABLE_RETURN_FAILED;
5005 return G_POLLABLE_RETURN_WOULD_BLOCK;
5008 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5009 return G_POLLABLE_RETURN_FAILED;
5015 *bytes_written = bytes_sent;
5016 return G_POLLABLE_RETURN_OK;
5022 * g_socket_send_messages:
5023 * @socket: a #GSocket
5024 * @messages: (array length=num_messages): an array of #GOutputMessage structs
5025 * @num_messages: the number of elements in @messages
5026 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
5027 * contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5028 * @cancellable: (nullable): a %GCancellable or %NULL
5029 * @error: #GError for error reporting, or %NULL to ignore.
5031 * Send multiple data messages from @socket in one go. This is the most
5032 * complicated and fully-featured version of this call. For easier use, see
5033 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
5035 * @messages must point to an array of #GOutputMessage structs and
5036 * @num_messages must be the length of this array. Each #GOutputMessage
5037 * contains an address to send the data to, and a pointer to an array of
5038 * #GOutputVector structs to describe the buffers that the data to be sent
5039 * for each message will be gathered from. Using multiple #GOutputVectors is
5040 * more memory-efficient than manually copying data from multiple sources
5041 * into a single buffer, and more network-efficient than making multiple
5042 * calls to g_socket_send(). Sending multiple messages in one go avoids the
5043 * overhead of making a lot of syscalls in scenarios where a lot of data
5044 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
5045 * or where the same data needs to be sent to multiple recipients.
5047 * @flags modify how the message is sent. The commonly available arguments
5048 * for this are available in the #GSocketMsgFlags enum, but the
5049 * values there are the same as the system values, and the flags
5050 * are passed in as-is, so you can pass in system-specific flags too.
5052 * If the socket is in blocking mode the call will block until there is
5053 * space for all the data in the socket queue. If there is no space available
5054 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
5055 * will be returned if no data was written at all, otherwise the number of
5056 * messages sent will be returned. To be notified when space is available,
5057 * wait for the %G_IO_OUT condition. Note though that you may still receive
5058 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
5059 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
5060 * very common due to the way the underlying APIs work.)
5062 * On error -1 is returned and @error is set accordingly. An error will only
5063 * be returned if zero messages could be sent; otherwise the number of messages
5064 * successfully sent before the error will be returned.
5066 * Returns: number of messages sent, or -1 on error. Note that the number of
5067 * messages sent may be smaller than @num_messages if the socket is
5068 * non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
5069 * in which case the caller may re-try to send the remaining messages.
5074 g_socket_send_messages (GSocket *socket,
5075 GOutputMessage *messages,
5078 GCancellable *cancellable,
5081 return g_socket_send_messages_with_timeout (socket, messages, num_messages,
5083 socket->priv->blocking ? -1 : 0,
5084 cancellable, error);
5088 g_socket_send_messages_with_timeout (GSocket *socket,
5089 GOutputMessage *messages,
5093 GCancellable *cancellable,
5098 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5099 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5100 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
5101 g_return_val_if_fail (error == NULL || *error == NULL, -1);
5103 start_time = g_get_monotonic_time ();
5105 if (!check_socket (socket, error))
5108 if (!check_timeout (socket, error))
5111 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5114 if (num_messages == 0)
5117 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
5119 struct mmsghdr *msgvec;
5122 /* Clamp the number of vectors if more given than we can write in one go.
5123 * The caller has to handle short writes anyway.
5125 if (num_messages > G_IOV_MAX)
5126 num_messages = G_IOV_MAX;
5128 msgvec = g_newa (struct mmsghdr, num_messages);
5130 for (i = 0; i < num_messages; ++i)
5132 GOutputMessage *msg = &messages[i];
5133 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5134 GError *child_error = NULL;
5136 msgvec[i].msg_len = 0;
5138 output_message_to_msghdr (msg, (i > 0) ? &messages[i - 1] : NULL,
5139 msg_hdr, (i > 0) ? &msgvec[i - 1].msg_hdr : NULL,
5142 if (child_error != NULL)
5144 g_propagate_error (error, child_error);
5149 for (num_sent = 0; num_sent < num_messages;)
5153 ret = sendmmsg (socket->priv->fd, msgvec + num_sent, num_messages - num_sent,
5154 flags | G_SOCKET_DEFAULT_SEND_FLAGS);
5158 int errsv = get_socket_errno ();
5163 if (timeout_us != 0 &&
5164 (errsv == EWOULDBLOCK ||
5167 if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
5168 cancellable, error))
5172 g_clear_error (error);
5182 /* If any messages were successfully sent, do not error. */
5186 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5194 for (i = 0; i < num_sent; ++i)
5195 messages[i].bytes_sent = msgvec[i].msg_len;
5203 gint64 wait_timeout;
5205 wait_timeout = timeout_us;
5207 for (i = 0; i < num_messages; ++i)
5209 GOutputMessage *msg = &messages[i];
5210 GError *msg_error = NULL;
5211 GPollableReturn pollable_result;
5212 gsize bytes_written = 0;
5214 pollable_result = g_socket_send_message_with_timeout (socket, msg->address,
5217 msg->control_messages,
5218 msg->num_control_messages,
5219 flags, wait_timeout,
5221 cancellable, &msg_error);
5223 if (pollable_result == G_POLLABLE_RETURN_WOULD_BLOCK)
5226 socket_set_error_lazy (&msg_error, EWOULDBLOCK, _("Error sending message: %s"));
5228 socket_set_error_lazy (&msg_error, WSAEWOULDBLOCK, _("Error sending message: %s"));
5232 result = pollable_result == G_POLLABLE_RETURN_OK ? bytes_written : -1;
5234 /* check if we've timed out or how much time to wait at most */
5237 gint64 elapsed = g_get_monotonic_time () - start_time;
5238 wait_timeout = MAX (timeout_us - elapsed, 1);
5243 /* if we couldn't send all messages, just return how many we did
5244 * manage to send, provided we managed to send at least one */
5247 g_error_free (msg_error);
5252 g_propagate_error (error, msg_error);
5257 msg->bytes_sent = result;
5265 static GSocketAddress *
5266 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
5268 GSocketAddress *saddr;
5270 guint64 oldest_time = G_MAXUINT64;
5271 gint oldest_index = 0;
5273 if (native_len <= 0)
5277 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
5279 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
5280 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
5281 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
5286 if (tmp_native_len != native_len)
5289 if (memcmp (tmp_native, native, native_len) == 0)
5291 saddr = g_object_ref (tmp);
5292 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
5296 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
5298 oldest_time = socket->priv->recv_addr_cache[i].last_used;
5303 saddr = g_socket_address_new_from_native (native, native_len);
5305 if (socket->priv->recv_addr_cache[oldest_index].addr)
5307 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
5308 g_free (socket->priv->recv_addr_cache[oldest_index].native);
5311 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
5312 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
5313 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
5314 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
5320 g_socket_receive_message_with_timeout (GSocket *socket,
5321 GSocketAddress **address,
5322 GInputVector *vectors,
5324 GSocketControlMessage ***messages,
5328 GCancellable *cancellable,
5331 GInputVector one_vector;
5335 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5337 start_time = g_get_monotonic_time ();
5339 if (!check_socket (socket, error))
5342 if (!check_timeout (socket, error))
5345 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5348 if (num_vectors == -1)
5350 for (num_vectors = 0;
5351 vectors[num_vectors].buffer != NULL;
5356 if (num_vectors == 0)
5358 one_vector.buffer = &one_byte;
5359 one_vector.size = 1;
5361 vectors = &one_vector;
5366 GInputMessage input_message;
5370 input_message.address = address;
5371 input_message.vectors = vectors;
5372 input_message.num_vectors = num_vectors;
5373 input_message.bytes_received = 0;
5374 input_message.flags = (flags != NULL) ? *flags : 0;
5375 input_message.control_messages = messages;
5376 input_message.num_control_messages = (guint *) num_messages;
5378 /* We always set the close-on-exec flag so we don't leak file
5379 * descriptors into child processes. Note that gunixfdmessage.c
5380 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5382 #ifdef MSG_CMSG_CLOEXEC
5383 input_message.flags |= MSG_CMSG_CLOEXEC;
5386 input_message_to_msghdr (&input_message, &msg);
5391 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5392 #ifdef MSG_CMSG_CLOEXEC
5393 if (result < 0 && get_socket_errno () == EINVAL)
5395 /* We must be running on an old kernel. Call without the flag. */
5396 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
5397 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5403 int errsv = get_socket_errno ();
5408 if (timeout_us != 0 &&
5409 (errsv == EWOULDBLOCK ||
5412 if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
5413 cancellable, error))
5419 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5425 input_message_from_msghdr (&msg, &input_message, socket);
5428 *flags = input_message.flags;
5434 struct sockaddr_storage addr;
5436 DWORD bytes_received;
5443 bufs = g_newa (WSABUF, num_vectors);
5444 for (i = 0; i < num_vectors; i++)
5446 bufs[i].buf = (char *)vectors[i].buffer;
5447 bufs[i].len = (gulong)vectors[i].size;
5459 addrlen = sizeof addr;
5461 result = WSARecvFrom (socket->priv->fd,
5463 &bytes_received, &win_flags,
5464 (struct sockaddr *)&addr, &addrlen,
5467 result = WSARecv (socket->priv->fd,
5469 &bytes_received, &win_flags,
5473 int errsv = get_socket_errno ();
5475 if (errsv == WSAEINTR)
5478 win32_unset_event_mask (socket, FD_READ);
5480 if (errsv == WSAEWOULDBLOCK)
5482 if (timeout_us != 0)
5484 if (!block_on_timeout (socket, G_IO_IN, timeout_us,
5485 start_time, cancellable, error))
5492 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5495 win32_unset_event_mask (socket, FD_READ);
5499 /* decode address */
5500 if (address != NULL)
5502 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
5505 /* capture the flags */
5509 if (messages != NULL)
5511 if (num_messages != NULL)
5514 return bytes_received;
5520 * g_socket_receive_messages:
5521 * @socket: a #GSocket
5522 * @messages: (array length=num_messages): an array of #GInputMessage structs
5523 * @num_messages: the number of elements in @messages
5524 * @flags: an int containing #GSocketMsgFlags flags for the overall operation,
5525 * which may additionally contain
5526 * [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5527 * @cancellable: (nullable): a %GCancellable or %NULL
5528 * @error: #GError for error reporting, or %NULL to ignore
5530 * Receive multiple data messages from @socket in one go. This is the most
5531 * complicated and fully-featured version of this call. For easier use, see
5532 * g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
5534 * @messages must point to an array of #GInputMessage structs and
5535 * @num_messages must be the length of this array. Each #GInputMessage
5536 * contains a pointer to an array of #GInputVector structs describing the
5537 * buffers that the data received in each message will be written to. Using
5538 * multiple #GInputVectors is more memory-efficient than manually copying data
5539 * out of a single buffer to multiple sources, and more system-call-efficient
5540 * than making multiple calls to g_socket_receive(), such as in scenarios where
5541 * a lot of data packets need to be received (e.g. high-bandwidth video
5542 * streaming over RTP/UDP).
5544 * @flags modify how all messages are received. The commonly available
5545 * arguments for this are available in the #GSocketMsgFlags enum, but the
5546 * values there are the same as the system values, and the flags
5547 * are passed in as-is, so you can pass in system-specific flags too. These
5548 * flags affect the overall receive operation. Flags affecting individual
5549 * messages are returned in #GInputMessage.flags.
5551 * The other members of #GInputMessage are treated as described in its
5554 * If #GSocket:blocking is %TRUE the call will block until @num_messages have
5555 * been received, or the end of the stream is reached.
5557 * If #GSocket:blocking is %FALSE the call will return up to @num_messages
5558 * without blocking, or %G_IO_ERROR_WOULD_BLOCK if no messages are queued in the
5559 * operating system to be received.
5561 * In blocking mode, if #GSocket:timeout is positive and is reached before any
5562 * messages are received, %G_IO_ERROR_TIMED_OUT is returned, otherwise up to
5563 * @num_messages are returned. (Note: This is effectively the
5564 * behaviour of `MSG_WAITFORONE` with recvmmsg().)
5566 * To be notified when messages are available, wait for the
5567 * %G_IO_IN condition. Note though that you may still receive
5568 * %G_IO_ERROR_WOULD_BLOCK from g_socket_receive_messages() even if you were
5569 * previously notified of a %G_IO_IN condition.
5571 * If the remote peer closes the connection, any messages queued in the
5572 * operating system will be returned, and subsequent calls to
5573 * g_socket_receive_messages() will return 0 (with no error set).
5575 * On error -1 is returned and @error is set accordingly. An error will only
5576 * be returned if zero messages could be received; otherwise the number of
5577 * messages successfully received before the error will be returned.
5579 * Returns: number of messages received, or -1 on error. Note that the number
5580 * of messages received may be smaller than @num_messages if in non-blocking
5581 * mode, if the peer closed the connection, or if @num_messages
5582 * was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
5583 * to receive the remaining messages.
5588 g_socket_receive_messages (GSocket *socket,
5589 GInputMessage *messages,
5592 GCancellable *cancellable,
5595 if (!check_socket (socket, error) ||
5596 !check_timeout (socket, error))
5599 return g_socket_receive_messages_with_timeout (socket, messages, num_messages,
5601 socket->priv->blocking ? -1 : 0,
5602 cancellable, error);
5606 g_socket_receive_messages_with_timeout (GSocket *socket,
5607 GInputMessage *messages,
5611 GCancellable *cancellable,
5616 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5617 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5618 g_return_val_if_fail (cancellable == NULL ||
5619 G_IS_CANCELLABLE (cancellable), -1);
5620 g_return_val_if_fail (error == NULL || *error == NULL, -1);
5622 start_time = g_get_monotonic_time ();
5624 if (!check_socket (socket, error))
5627 if (!check_timeout (socket, error))
5630 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5633 if (num_messages == 0)
5636 #if !defined (G_OS_WIN32) && defined (HAVE_RECVMMSG)
5638 struct mmsghdr *msgvec;
5639 guint i, num_received;
5641 /* Clamp the number of vectors if more given than we can write in one go.
5642 * The caller has to handle short writes anyway.
5644 if (num_messages > G_IOV_MAX)
5645 num_messages = G_IOV_MAX;
5647 msgvec = g_newa (struct mmsghdr, num_messages);
5649 for (i = 0; i < num_messages; ++i)
5651 GInputMessage *msg = &messages[i];
5652 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5654 input_message_to_msghdr (msg, msg_hdr);
5655 msgvec[i].msg_len = 0;
5658 /* We always set the close-on-exec flag so we don't leak file
5659 * descriptors into child processes. Note that gunixfdmessage.c
5660 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5662 #ifdef MSG_CMSG_CLOEXEC
5663 flags |= MSG_CMSG_CLOEXEC;
5666 for (num_received = 0; num_received < num_messages;)
5670 /* We operate in non-blocking mode and handle the timeout ourselves. */
5671 ret = recvmmsg (socket->priv->fd,
5672 msgvec + num_received,
5673 num_messages - num_received,
5674 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5675 #ifdef MSG_CMSG_CLOEXEC
5676 if (ret < 0 && get_socket_errno () == EINVAL)
5678 /* We must be running on an old kernel. Call without the flag. */
5679 flags &= ~(MSG_CMSG_CLOEXEC);
5680 ret = recvmmsg (socket->priv->fd,
5681 msgvec + num_received,
5682 num_messages - num_received,
5683 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5689 int errsv = get_socket_errno ();
5694 if (timeout_us != 0 &&
5695 (errsv == EWOULDBLOCK ||
5698 if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
5699 cancellable, error))
5701 if (num_received > 0)
5703 g_clear_error (error);
5713 /* If any messages were successfully received, do not error. */
5714 if (num_received > 0)
5717 socket_set_error_lazy (error, errsv,
5718 _("Error receiving message: %s"));
5728 num_received += ret;
5731 for (i = 0; i < num_received; ++i)
5733 input_message_from_msghdr (&msgvec[i].msg_hdr, &messages[i], socket);
5734 messages[i].bytes_received = msgvec[i].msg_len;
5737 return num_received;
5742 gint64 wait_timeout;
5744 wait_timeout = timeout_us;
5746 for (i = 0; i < num_messages; i++)
5748 GInputMessage *msg = &messages[i];
5750 GError *msg_error = NULL;
5752 msg->flags = flags; /* in-out parameter */
5754 len = g_socket_receive_message_with_timeout (socket,
5758 msg->control_messages,
5759 (gint *) msg->num_control_messages,
5765 /* check if we've timed out or how much time to wait at most */
5768 gint64 elapsed = g_get_monotonic_time () - start_time;
5769 wait_timeout = MAX (timeout_us - elapsed, 1);
5773 msg->bytes_received = len;
5776 (g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK) ||
5777 g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)))
5779 g_clear_error (&msg_error);
5783 if (msg_error != NULL)
5785 g_propagate_error (error, msg_error);
5799 * g_socket_receive_message:
5800 * @socket: a #GSocket
5801 * @address: (out) (optional): a pointer to a #GSocketAddress
5803 * @vectors: (array length=num_vectors): an array of #GInputVector structs
5804 * @num_vectors: the number of elements in @vectors, or -1
5805 * @messages: (array length=num_messages) (out) (optional) (nullable): a pointer
5806 * which may be filled with an array of #GSocketControlMessages, or %NULL
5807 * @num_messages: (out): a pointer which will be filled with the number of
5808 * elements in @messages, or %NULL
5809 * @flags: (inout): a pointer to an int containing #GSocketMsgFlags flags,
5810 * which may additionally contain
5811 * [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5812 * @cancellable: a %GCancellable or %NULL
5813 * @error: a #GError pointer, or %NULL
5815 * Receive data from a socket. For receiving multiple messages, see
5816 * g_socket_receive_messages(); for easier use, see
5817 * g_socket_receive() and g_socket_receive_from().
5819 * If @address is non-%NULL then @address will be set equal to the
5820 * source address of the received packet.
5821 * @address is owned by the caller.
5823 * @vector must point to an array of #GInputVector structs and
5824 * @num_vectors must be the length of this array. These structs
5825 * describe the buffers that received data will be scattered into.
5826 * If @num_vectors is -1, then @vectors is assumed to be terminated
5827 * by a #GInputVector with a %NULL buffer pointer.
5829 * As a special case, if @num_vectors is 0 (in which case, @vectors
5830 * may of course be %NULL), then a single byte is received and
5831 * discarded. This is to facilitate the common practice of sending a
5832 * single '\0' byte for the purposes of transferring ancillary data.
5834 * @messages, if non-%NULL, will be set to point to a newly-allocated
5835 * array of #GSocketControlMessage instances or %NULL if no such
5836 * messages was received. These correspond to the control messages
5837 * received from the kernel, one #GSocketControlMessage per message
5838 * from the kernel. This array is %NULL-terminated and must be freed
5839 * by the caller using g_free() after calling g_object_unref() on each
5840 * element. If @messages is %NULL, any control messages received will
5843 * @num_messages, if non-%NULL, will be set to the number of control
5844 * messages received.
5846 * If both @messages and @num_messages are non-%NULL, then
5847 * @num_messages gives the number of #GSocketControlMessage instances
5848 * in @messages (ie: not including the %NULL terminator).
5850 * @flags is an in/out parameter. The commonly available arguments
5851 * for this are available in the #GSocketMsgFlags enum, but the
5852 * values there are the same as the system values, and the flags
5853 * are passed in as-is, so you can pass in system-specific flags too
5854 * (and g_socket_receive_message() may pass system-specific flags out).
5855 * Flags passed in to the parameter affect the receive operation; flags returned
5856 * out of it are relevant to the specific returned message.
5858 * As with g_socket_receive(), data may be discarded if @socket is
5859 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
5860 * provide enough buffer space to read a complete message. You can pass
5861 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
5862 * removing it from the receive queue, but there is no portable way to find
5863 * out the length of the message other than by reading it into a
5864 * sufficiently-large buffer.
5866 * If the socket is in blocking mode the call will block until there
5867 * is some data to receive, the connection is closed, or there is an
5868 * error. If there is no data available and the socket is in
5869 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
5870 * returned. To be notified when data is available, wait for the
5871 * %G_IO_IN condition.
5873 * On error -1 is returned and @error is set accordingly.
5875 * Returns: Number of bytes read, or 0 if the connection was closed by
5876 * the peer, or -1 on error
5881 g_socket_receive_message (GSocket *socket,
5882 GSocketAddress **address,
5883 GInputVector *vectors,
5885 GSocketControlMessage ***messages,
5888 GCancellable *cancellable,
5891 return g_socket_receive_message_with_timeout (socket, address, vectors,
5892 num_vectors, messages,
5893 num_messages, flags,
5894 socket->priv->blocking ? -1 : 0,
5895 cancellable, error);
5899 * g_socket_get_credentials:
5900 * @socket: a #GSocket.
5901 * @error: #GError for error reporting, or %NULL to ignore.
5903 * Returns the credentials of the foreign process connected to this
5904 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
5907 * If this operation isn't supported on the OS, the method fails with
5908 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
5909 * by reading the %SO_PEERCRED option on the underlying socket.
5911 * This method can be expected to be available on the following platforms:
5913 * - Linux since GLib 2.26
5914 * - OpenBSD since GLib 2.30
5915 * - Solaris, Illumos and OpenSolaris since GLib 2.40
5916 * - NetBSD since GLib 2.42
5917 * - macOS, tvOS, iOS since GLib 2.66
5919 * Other ways to obtain credentials from a foreign peer includes the
5920 * #GUnixCredentialsMessage type and
5921 * g_unix_connection_send_credentials() /
5922 * g_unix_connection_receive_credentials() functions.
5924 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
5925 * that must be freed with g_object_unref().
5930 g_socket_get_credentials (GSocket *socket,
5935 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
5936 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5938 if (!check_socket (socket, error))
5943 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
5947 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
5948 socklen_t optlen = sizeof (native_creds_buf);
5950 if (getsockopt (socket->priv->fd,
5956 ret = g_credentials_new ();
5957 g_credentials_set_native (ret,
5958 G_CREDENTIALS_NATIVE_TYPE,
5962 #elif G_CREDENTIALS_USE_APPLE_XUCRED
5965 socklen_t optlen = sizeof (cred);
5967 if (getsockopt (socket->priv->fd,
5973 if (cred.cr_version == XUCRED_VERSION)
5975 ret = g_credentials_new ();
5976 g_credentials_set_native (ret,
5977 G_CREDENTIALS_NATIVE_TYPE,
5984 G_IO_ERROR_NOT_SUPPORTED,
5985 /* No point in translating this! */
5986 "struct xucred cr_version %u != %u",
5987 cred.cr_version, XUCRED_VERSION);
5988 /* Reuse a translatable string we already have */
5989 g_prefix_error (error,
5990 _("Unable to read socket credentials: %s"),
5997 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
5999 struct unpcbid cred;
6000 socklen_t optlen = sizeof (cred);
6002 if (getsockopt (socket->priv->fd,
6008 ret = g_credentials_new ();
6009 g_credentials_set_native (ret,
6010 G_CREDENTIALS_NATIVE_TYPE,
6014 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
6016 ucred_t *ucred = NULL;
6018 if (getpeerucred (socket->priv->fd, &ucred) == 0)
6020 ret = g_credentials_new ();
6021 g_credentials_set_native (ret,
6022 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
6028 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
6033 int errsv = get_socket_errno ();
6037 socket_io_error_from_errno (errsv),
6038 _("Unable to read socket credentials: %s"),
6039 socket_strerror (errsv));
6044 g_set_error_literal (error,
6046 G_IO_ERROR_NOT_SUPPORTED,
6047 _("g_socket_get_credentials not implemented for this OS"));
6054 * g_socket_get_option:
6055 * @socket: a #GSocket
6056 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
6057 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
6058 * @value: (out): return location for the option value
6059 * @error: #GError for error reporting, or %NULL to ignore.
6061 * Gets the value of an integer-valued option on @socket, as with
6062 * getsockopt(). (If you need to fetch a non-integer-valued option,
6063 * you will need to call getsockopt() directly.)
6065 * The [<gio/gnetworking.h>][gio-gnetworking.h]
6066 * header pulls in system headers that will define most of the
6067 * standard/portable socket options. For unusual socket protocols or
6068 * platform-dependent options, you may need to include additional
6071 * Note that even for socket options that are a single byte in size,
6072 * @value is still a pointer to a #gint variable, not a #guchar;
6073 * g_socket_get_option() will handle the conversion internally.
6075 * Returns: success or failure. On failure, @error will be set, and
6076 * the system error value (`errno` or WSAGetLastError()) will still
6077 * be set to the result of the getsockopt() call.
6082 g_socket_get_option (GSocket *socket,
6090 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
6092 /* g_socket_get_option() is called during socket init, so skip the init checks
6093 * in check_socket() */
6094 if (socket->priv->inited && !check_socket (socket, error))
6098 size = sizeof (gint);
6099 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
6101 int errsv = get_socket_errno ();
6103 g_set_error_literal (error,
6105 socket_io_error_from_errno (errsv),
6106 socket_strerror (errsv));
6108 /* Reset errno in case the caller wants to look at it */
6114 #if G_BYTE_ORDER == G_BIG_ENDIAN
6115 /* If the returned value is smaller than an int then we need to
6116 * slide it over into the low-order bytes of *value.
6118 if (size != sizeof (gint))
6119 *value = *value >> (8 * (sizeof (gint) - size));
6126 * g_socket_set_option:
6127 * @socket: a #GSocket
6128 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
6129 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
6130 * @value: the value to set the option to
6131 * @error: #GError for error reporting, or %NULL to ignore.
6133 * Sets the value of an integer-valued option on @socket, as with
6134 * setsockopt(). (If you need to set a non-integer-valued option,
6135 * you will need to call setsockopt() directly.)
6137 * The [<gio/gnetworking.h>][gio-gnetworking.h]
6138 * header pulls in system headers that will define most of the
6139 * standard/portable socket options. For unusual socket protocols or
6140 * platform-dependent options, you may need to include additional
6143 * Returns: success or failure. On failure, @error will be set, and
6144 * the system error value (`errno` or WSAGetLastError()) will still
6145 * be set to the result of the setsockopt() call.
6150 g_socket_set_option (GSocket *socket,
6158 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
6160 if (!check_socket (socket, error))
6163 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
6166 #if !defined (__linux__) && !defined (G_OS_WIN32)
6167 /* Linux and Windows let you set a single-byte value from an int,
6168 * but most other platforms don't.
6170 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
6172 #if G_BYTE_ORDER == G_BIG_ENDIAN
6173 value = value << (8 * (sizeof (gint) - 1));
6175 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
6180 errsv = get_socket_errno ();
6182 g_set_error_literal (error,
6184 socket_io_error_from_errno (errsv),
6185 socket_strerror (errsv));