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"
79 /* For Windows XP runtime compatibility, but use the system's if_nametoindex() if available */
80 #include "gwin32networking.h"
85 * @short_description: Low-level socket object
87 * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
89 * A #GSocket is a low-level networking primitive. It is a more or less
90 * direct mapping of the BSD socket API in a portable GObject based API.
91 * It supports both the UNIX socket implementations and winsock2 on Windows.
93 * #GSocket is the platform independent base upon which the higher level
94 * network primitives are based. Applications are not typically meant to
95 * use it directly, but rather through classes like #GSocketClient,
96 * #GSocketService and #GSocketConnection. However there may be cases where
97 * direct use of #GSocket is useful.
99 * #GSocket implements the #GInitable interface, so if it is manually constructed
100 * by e.g. g_object_new() you must call g_initable_init() and check the
101 * results before using the object. This is done automatically in
102 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
105 * Sockets operate in two general modes, blocking or non-blocking. When
106 * in blocking mode all operations (which don’t take an explicit blocking
107 * parameter) block until the requested operation
108 * is finished or there is an error. In non-blocking mode all calls that
109 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
110 * To know when a call would successfully run you can call g_socket_condition_check(),
111 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
112 * attach it to a #GMainContext to get callbacks when I/O is possible.
113 * Note that all sockets are always set to non blocking mode in the system, and
114 * blocking mode is emulated in GSocket.
116 * When working in non-blocking mode applications should always be able to
117 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
118 * function said that I/O was possible. This can easily happen in case
119 * of a race condition in the application, but it can also happen for other
120 * reasons. For instance, on Windows a socket is always seen as writable
121 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
123 * #GSockets can be either connection oriented or datagram based.
124 * For connection oriented types you must first establish a connection by
125 * either connecting to an address or accepting a connection from another
126 * address. For connectionless socket types the target/source address is
127 * specified or received in each I/O operation.
129 * All socket file descriptors are set to be close-on-exec.
131 * Note that creating a #GSocket causes the signal %SIGPIPE to be
132 * ignored for the remainder of the program. If you are writing a
133 * command-line utility that uses #GSocket, you may need to take into
134 * account the fact that your program will not automatically be killed
135 * if it tries to write to %stdout after it has been closed.
137 * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
138 * a #GSocket concurrently from multiple threads, you must implement your own
144 static void g_socket_initable_iface_init (GInitableIface *iface);
145 static gboolean g_socket_initable_init (GInitable *initable,
146 GCancellable *cancellable,
149 static void g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface);
150 static gint g_socket_datagram_based_receive_messages (GDatagramBased *self,
151 GInputMessage *messages,
155 GCancellable *cancellable,
157 static gint g_socket_datagram_based_send_messages (GDatagramBased *self,
158 GOutputMessage *messages,
162 GCancellable *cancellable,
164 static GSource *g_socket_datagram_based_create_source (GDatagramBased *self,
165 GIOCondition condition,
166 GCancellable *cancellable);
167 static GIOCondition g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
168 GIOCondition condition);
169 static gboolean g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
170 GIOCondition condition,
172 GCancellable *cancellable,
175 static GSocketAddress *
176 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len);
179 g_socket_receive_message_with_timeout (GSocket *socket,
180 GSocketAddress **address,
181 GInputVector *vectors,
183 GSocketControlMessage ***messages,
187 GCancellable *cancellable,
190 g_socket_receive_messages_with_timeout (GSocket *socket,
191 GInputMessage *messages,
195 GCancellable *cancellable,
198 g_socket_send_messages_with_timeout (GSocket *socket,
199 GOutputMessage *messages,
203 GCancellable *cancellable,
221 PROP_MULTICAST_LOOPBACK,
225 /* Size of the receiver cache for g_socket_receive_from() */
226 #define RECV_ADDR_CACHE_SIZE 8
228 struct _GSocketPrivate
230 GSocketFamily family;
232 GSocketProtocol protocol;
236 GError *construct_error;
237 GSocketAddress *remote_address;
242 guint connected_read : 1;
243 guint connected_write : 1;
246 guint connect_pending : 1;
250 DWORD waiting_result;
254 GList *requested_conditions; /* list of requested GIOCondition * */
255 GMutex win32_source_lock;
256 GCond win32_source_cond;
260 GSocketAddress *addr;
261 struct sockaddr *native;
264 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
267 _G_DEFINE_TYPE_EXTENDED_WITH_PRELUDE (GSocket, g_socket, G_TYPE_OBJECT, 0,
268 /* Need a prelude for https://bugzilla.gnome.org/show_bug.cgi?id=674885 */
269 g_type_ensure (G_TYPE_SOCKET_FAMILY);
270 g_type_ensure (G_TYPE_SOCKET_TYPE);
271 g_type_ensure (G_TYPE_SOCKET_PROTOCOL);
272 g_type_ensure (G_TYPE_SOCKET_ADDRESS);
273 /* And networking init is appropriate for the prelude */
274 g_networking_init ();
275 , /* And now the regular type init code */
276 G_ADD_PRIVATE (GSocket)
277 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
278 g_socket_initable_iface_init);
279 G_IMPLEMENT_INTERFACE (G_TYPE_DATAGRAM_BASED,
280 g_socket_datagram_based_iface_init));
283 get_socket_errno (void)
288 return WSAGetLastError ();
293 socket_io_error_from_errno (int err)
296 return g_io_error_from_win32_error (err);
298 return g_io_error_from_errno (err);
303 socket_strerror (int err)
306 return g_strerror (err);
311 msg = g_win32_error_message (err);
313 msg_ret = g_intern_string (msg);
320 /* Wrapper around g_set_error() to avoid doing excess work */
321 #define socket_set_error_lazy(err, errsv, fmt) \
323 GError **__err = (err); \
324 int __errsv = (errsv); \
328 int __code = socket_io_error_from_errno (__errsv); \
329 const char *__strerr = socket_strerror (__errsv); \
331 if (__code == G_IO_ERROR_WOULD_BLOCK) \
332 g_set_error_literal (__err, G_IO_ERROR, __code, __strerr); \
334 g_set_error (__err, G_IO_ERROR, __code, fmt, __strerr); \
339 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
341 _win32_unset_event_mask (GSocket *socket, int mask)
343 g_mutex_lock (&socket->priv->win32_source_lock);
344 socket->priv->current_events &= ~mask;
345 socket->priv->current_errors &= ~mask;
346 g_mutex_unlock (&socket->priv->win32_source_lock);
349 #define win32_unset_event_mask(_socket, _mask)
352 /* Windows has broken prototypes... */
354 #define getsockopt(sockfd, level, optname, optval, optlen) \
355 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
356 #define setsockopt(sockfd, level, optname, optval, optlen) \
357 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
358 #define getsockname(sockfd, addr, addrlen) \
359 getsockname (sockfd, addr, (int *)addrlen)
360 #define getpeername(sockfd, addr, addrlen) \
361 getpeername (sockfd, addr, (int *)addrlen)
362 #define recv(sockfd, buf, len, flags) \
363 recv (sockfd, (gpointer)buf, len, flags)
367 check_socket (GSocket *socket,
370 if (!socket->priv->inited)
372 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
373 _("Invalid socket, not initialized"));
377 if (socket->priv->construct_error)
379 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
380 _("Invalid socket, initialization failed due to: %s"),
381 socket->priv->construct_error->message);
385 if (socket->priv->closed)
387 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
388 _("Socket is already closed"));
396 check_timeout (GSocket *socket,
399 if (socket->priv->timed_out)
401 socket->priv->timed_out = FALSE;
402 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
403 _("Socket I/O timed out"));
411 g_socket_details_from_fd (GSocket *socket)
414 struct sockaddr_storage storage;
422 fd = socket->priv->fd;
423 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
425 errsv = get_socket_errno ();
432 socket->priv->type = G_SOCKET_TYPE_STREAM;
436 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
440 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
444 socket->priv->type = G_SOCKET_TYPE_INVALID;
448 addrlen = sizeof address;
449 if (getsockname (fd, &address.sa, &addrlen) != 0)
451 errsv = get_socket_errno ();
457 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
458 sizeof address.storage.ss_family <= addrlen);
459 family = address.storage.ss_family;
463 /* On Solaris, this happens if the socket is not yet connected.
464 * But we can use SO_DOMAIN as a workaround there.
467 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
469 errsv = get_socket_errno ();
473 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
481 case G_SOCKET_FAMILY_IPV4:
482 case G_SOCKET_FAMILY_IPV6:
483 socket->priv->family = address.storage.ss_family;
484 switch (socket->priv->type)
486 case G_SOCKET_TYPE_STREAM:
487 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
490 case G_SOCKET_TYPE_DATAGRAM:
491 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
494 case G_SOCKET_TYPE_SEQPACKET:
495 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
503 case G_SOCKET_FAMILY_UNIX:
504 socket->priv->family = G_SOCKET_FAMILY_UNIX;
505 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
509 socket->priv->family = G_SOCKET_FAMILY_INVALID;
513 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
515 addrlen = sizeof address;
516 if (getpeername (fd, &address.sa, &addrlen) >= 0)
518 socket->priv->connected_read = TRUE;
519 socket->priv->connected_write = TRUE;
523 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
525 socket->priv->keepalive = !!value;
529 /* Can't read, maybe not supported, assume FALSE */
530 socket->priv->keepalive = FALSE;
536 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
537 socket_io_error_from_errno (errsv),
538 _("creating GSocket from fd: %s"),
539 socket_strerror (errsv));
542 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
544 g_socket (gint domain,
552 fd = socket (domain, type | SOCK_CLOEXEC, protocol);
557 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
558 if (fd < 0 && (errsv == EINVAL || errsv == EPROTOTYPE))
560 fd = socket (domain, type, protocol);
564 errsv = get_socket_errno ();
566 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
567 _("Unable to create socket: %s"), socket_strerror (errsv));
576 /* We always want to set close-on-exec to protect users. If you
577 need to so some weird inheritance to exec you can re-enable this
578 using lower level hacks with g_socket_get_fd(). */
579 flags = fcntl (fd, F_GETFD, 0);
581 (flags & FD_CLOEXEC) == 0)
584 fcntl (fd, F_SETFD, flags);
593 g_socket_create_socket (GSocketFamily family,
602 case G_SOCKET_TYPE_STREAM:
603 native_type = SOCK_STREAM;
606 case G_SOCKET_TYPE_DATAGRAM:
607 native_type = SOCK_DGRAM;
610 case G_SOCKET_TYPE_SEQPACKET:
611 native_type = SOCK_SEQPACKET;
615 g_assert_not_reached ();
620 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
621 _("Unable to create socket: %s"), _("Unknown family was specified"));
627 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
628 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
632 return g_socket (family, native_type, protocol, error);
636 g_socket_constructed (GObject *object)
638 GSocket *socket = G_SOCKET (object);
640 if (socket->priv->fd >= 0)
641 /* create socket->priv info from the fd */
642 g_socket_details_from_fd (socket);
645 /* create the fd from socket->priv info */
646 socket->priv->fd = g_socket_create_socket (socket->priv->family,
648 socket->priv->protocol,
649 &socket->priv->construct_error);
651 if (socket->priv->fd != -1)
654 GError *error = NULL;
659 /* Always use native nonblocking sockets, as Windows sets sockets to
660 * nonblocking automatically in certain operations. This way we make
661 * things work the same on all platforms.
664 if (!g_unix_set_fd_nonblocking (socket->priv->fd, TRUE, &error))
666 g_warning ("Error setting socket nonblocking: %s", error->message);
667 g_clear_error (&error);
672 if (ioctlsocket (socket->priv->fd, FIONBIO, &arg) == SOCKET_ERROR)
674 int errsv = get_socket_errno ();
675 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
680 /* See note about SIGPIPE below. */
681 g_socket_set_option (socket, SOL_SOCKET, SO_NOSIGPIPE, TRUE, NULL);
687 g_socket_get_property (GObject *object,
692 GSocket *socket = G_SOCKET (object);
693 GSocketAddress *address;
698 g_value_set_enum (value, socket->priv->family);
702 g_value_set_enum (value, socket->priv->type);
706 g_value_set_enum (value, socket->priv->protocol);
710 g_value_set_int (value, socket->priv->fd);
714 g_value_set_boolean (value, socket->priv->blocking);
717 case PROP_LISTEN_BACKLOG:
718 g_value_set_int (value, socket->priv->listen_backlog);
722 g_value_set_boolean (value, socket->priv->keepalive);
725 case PROP_LOCAL_ADDRESS:
726 address = g_socket_get_local_address (socket, NULL);
727 g_value_take_object (value, address);
730 case PROP_REMOTE_ADDRESS:
731 address = g_socket_get_remote_address (socket, NULL);
732 g_value_take_object (value, address);
736 g_value_set_uint (value, socket->priv->timeout);
740 g_value_set_uint (value, g_socket_get_ttl (socket));
744 g_value_set_boolean (value, g_socket_get_broadcast (socket));
747 case PROP_MULTICAST_LOOPBACK:
748 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
751 case PROP_MULTICAST_TTL:
752 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
756 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
761 g_socket_set_property (GObject *object,
766 GSocket *socket = G_SOCKET (object);
771 socket->priv->family = g_value_get_enum (value);
775 socket->priv->type = g_value_get_enum (value);
779 socket->priv->protocol = g_value_get_enum (value);
783 socket->priv->fd = g_value_get_int (value);
787 g_socket_set_blocking (socket, g_value_get_boolean (value));
790 case PROP_LISTEN_BACKLOG:
791 g_socket_set_listen_backlog (socket, g_value_get_int (value));
795 g_socket_set_keepalive (socket, g_value_get_boolean (value));
799 g_socket_set_timeout (socket, g_value_get_uint (value));
803 g_socket_set_ttl (socket, g_value_get_uint (value));
807 g_socket_set_broadcast (socket, g_value_get_boolean (value));
810 case PROP_MULTICAST_LOOPBACK:
811 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
814 case PROP_MULTICAST_TTL:
815 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
819 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
824 g_socket_finalize (GObject *object)
826 GSocket *socket = G_SOCKET (object);
829 g_clear_error (&socket->priv->construct_error);
831 if (socket->priv->fd != -1 &&
832 !socket->priv->closed)
833 g_socket_close (socket, NULL);
835 if (socket->priv->remote_address)
836 g_object_unref (socket->priv->remote_address);
839 if (socket->priv->event != WSA_INVALID_EVENT)
841 WSACloseEvent (socket->priv->event);
842 socket->priv->event = WSA_INVALID_EVENT;
845 g_assert (socket->priv->requested_conditions == NULL);
846 g_mutex_clear (&socket->priv->win32_source_lock);
847 g_cond_clear (&socket->priv->win32_source_cond);
850 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
852 if (socket->priv->recv_addr_cache[i].addr)
854 g_object_unref (socket->priv->recv_addr_cache[i].addr);
855 g_free (socket->priv->recv_addr_cache[i].native);
859 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
860 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
864 g_socket_class_init (GSocketClass *klass)
866 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
869 /* There is no portable, thread-safe way to avoid having the process
870 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
871 * forced to simply ignore the signal process-wide.
873 * Even if we ignore it though, gdb will still stop if the app
874 * receives a SIGPIPE, which can be confusing and annoying. So when
875 * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
876 * prevent the signal from occurring at all.
878 signal (SIGPIPE, SIG_IGN);
881 gobject_class->finalize = g_socket_finalize;
882 gobject_class->constructed = g_socket_constructed;
883 gobject_class->set_property = g_socket_set_property;
884 gobject_class->get_property = g_socket_get_property;
886 g_object_class_install_property (gobject_class, PROP_FAMILY,
887 g_param_spec_enum ("family",
889 P_("The sockets address family"),
890 G_TYPE_SOCKET_FAMILY,
891 G_SOCKET_FAMILY_INVALID,
892 G_PARAM_CONSTRUCT_ONLY |
894 G_PARAM_STATIC_STRINGS));
896 g_object_class_install_property (gobject_class, PROP_TYPE,
897 g_param_spec_enum ("type",
899 P_("The sockets type"),
901 G_SOCKET_TYPE_STREAM,
902 G_PARAM_CONSTRUCT_ONLY |
904 G_PARAM_STATIC_STRINGS));
906 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
907 g_param_spec_enum ("protocol",
908 P_("Socket protocol"),
909 P_("The id of the protocol to use, or -1 for unknown"),
910 G_TYPE_SOCKET_PROTOCOL,
911 G_SOCKET_PROTOCOL_UNKNOWN,
912 G_PARAM_CONSTRUCT_ONLY |
914 G_PARAM_STATIC_STRINGS));
916 g_object_class_install_property (gobject_class, PROP_FD,
917 g_param_spec_int ("fd",
918 P_("File descriptor"),
919 P_("The sockets file descriptor"),
923 G_PARAM_CONSTRUCT_ONLY |
925 G_PARAM_STATIC_STRINGS));
927 g_object_class_install_property (gobject_class, PROP_BLOCKING,
928 g_param_spec_boolean ("blocking",
930 P_("Whether or not I/O on this socket is blocking"),
933 G_PARAM_STATIC_STRINGS));
935 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
936 g_param_spec_int ("listen-backlog",
937 P_("Listen backlog"),
938 P_("Outstanding connections in the listen queue"),
943 G_PARAM_STATIC_STRINGS));
945 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
946 g_param_spec_boolean ("keepalive",
947 P_("Keep connection alive"),
948 P_("Keep connection alive by sending periodic pings"),
951 G_PARAM_STATIC_STRINGS));
953 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
954 g_param_spec_object ("local-address",
956 P_("The local address the socket is bound to"),
957 G_TYPE_SOCKET_ADDRESS,
959 G_PARAM_STATIC_STRINGS));
961 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
962 g_param_spec_object ("remote-address",
963 P_("Remote address"),
964 P_("The remote address the socket is connected to"),
965 G_TYPE_SOCKET_ADDRESS,
967 G_PARAM_STATIC_STRINGS));
972 * The timeout in seconds on socket I/O
976 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
977 g_param_spec_uint ("timeout",
979 P_("The timeout in seconds on socket I/O"),
984 G_PARAM_STATIC_STRINGS));
989 * Whether the socket should allow sending to broadcast addresses.
993 g_object_class_install_property (gobject_class, PROP_BROADCAST,
994 g_param_spec_boolean ("broadcast",
996 P_("Whether to allow sending to broadcast addresses"),
999 G_PARAM_STATIC_STRINGS));
1004 * Time-to-live for outgoing unicast packets
1008 g_object_class_install_property (gobject_class, PROP_TTL,
1009 g_param_spec_uint ("ttl",
1011 P_("Time-to-live of outgoing unicast packets"),
1014 G_PARAM_STATIC_STRINGS));
1017 * GSocket:multicast-loopback:
1019 * Whether outgoing multicast packets loop back to the local host.
1023 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
1024 g_param_spec_boolean ("multicast-loopback",
1025 P_("Multicast loopback"),
1026 P_("Whether outgoing multicast packets loop back to the local host"),
1029 G_PARAM_STATIC_STRINGS));
1032 * GSocket:multicast-ttl:
1034 * Time-to-live out outgoing multicast packets
1038 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
1039 g_param_spec_uint ("multicast-ttl",
1040 P_("Multicast TTL"),
1041 P_("Time-to-live of outgoing multicast packets"),
1044 G_PARAM_STATIC_STRINGS));
1048 g_socket_initable_iface_init (GInitableIface *iface)
1050 iface->init = g_socket_initable_init;
1054 g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface)
1056 iface->receive_messages = g_socket_datagram_based_receive_messages;
1057 iface->send_messages = g_socket_datagram_based_send_messages;
1058 iface->create_source = g_socket_datagram_based_create_source;
1059 iface->condition_check = g_socket_datagram_based_condition_check;
1060 iface->condition_wait = g_socket_datagram_based_condition_wait;
1064 g_socket_init (GSocket *socket)
1066 socket->priv = g_socket_get_instance_private (socket);
1068 socket->priv->fd = -1;
1069 socket->priv->blocking = TRUE;
1070 socket->priv->listen_backlog = 10;
1071 socket->priv->construct_error = NULL;
1073 socket->priv->event = WSA_INVALID_EVENT;
1074 g_mutex_init (&socket->priv->win32_source_lock);
1075 g_cond_init (&socket->priv->win32_source_cond);
1080 g_socket_initable_init (GInitable *initable,
1081 GCancellable *cancellable,
1086 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
1088 socket = G_SOCKET (initable);
1090 if (cancellable != NULL)
1092 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1093 _("Cancellable initialization not supported"));
1097 socket->priv->inited = TRUE;
1099 if (socket->priv->construct_error)
1102 *error = g_error_copy (socket->priv->construct_error);
1111 check_datagram_based (GDatagramBased *self,
1114 switch (g_socket_get_socket_type (G_SOCKET (self)))
1116 case G_SOCKET_TYPE_INVALID:
1117 case G_SOCKET_TYPE_STREAM:
1118 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1119 _("Cannot use datagram operations on a non-datagram "
1122 case G_SOCKET_TYPE_DATAGRAM:
1123 case G_SOCKET_TYPE_SEQPACKET:
1128 /* Due to us sharing #GSocketSource with the #GSocket implementation, it is
1129 * pretty tricky to split out #GSocket:timeout so that it does not affect
1130 * #GDatagramBased operations (but still affects #GSocket operations). It is
1131 * not worth that effort — just disallow it and require the user to specify
1132 * timeouts on a per-operation basis. */
1133 if (g_socket_get_timeout (G_SOCKET (self)) != 0)
1135 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1136 _("Cannot use datagram operations on a socket with a "
1145 g_socket_datagram_based_receive_messages (GDatagramBased *self,
1146 GInputMessage *messages,
1150 GCancellable *cancellable,
1153 if (!check_datagram_based (self, error))
1156 return g_socket_receive_messages_with_timeout (G_SOCKET (self), messages,
1157 num_messages, flags, timeout_us,
1158 cancellable, error);
1162 g_socket_datagram_based_send_messages (GDatagramBased *self,
1163 GOutputMessage *messages,
1167 GCancellable *cancellable,
1170 if (!check_datagram_based (self, error))
1173 return g_socket_send_messages_with_timeout (G_SOCKET (self), messages,
1174 num_messages, flags, timeout_us,
1175 cancellable, error);
1179 g_socket_datagram_based_create_source (GDatagramBased *self,
1180 GIOCondition condition,
1181 GCancellable *cancellable)
1183 if (!check_datagram_based (self, NULL))
1186 return g_socket_create_source (G_SOCKET (self), condition, cancellable);
1190 g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
1191 GIOCondition condition)
1193 if (!check_datagram_based (datagram_based, NULL))
1196 return g_socket_condition_check (G_SOCKET (datagram_based), condition);
1200 g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
1201 GIOCondition condition,
1203 GCancellable *cancellable,
1206 if (!check_datagram_based (datagram_based, error))
1209 return g_socket_condition_timed_wait (G_SOCKET (datagram_based), condition,
1210 timeout_us, cancellable, error);
1215 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1216 * @type: the socket type to use.
1217 * @protocol: the id of the protocol to use, or 0 for default.
1218 * @error: #GError for error reporting, or %NULL to ignore.
1220 * Creates a new #GSocket with the defined family, type and protocol.
1221 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1222 * for the family and type is used.
1224 * The @protocol is a family and type specific int that specifies what
1225 * kind of protocol to use. #GSocketProtocol lists several common ones.
1226 * Many families only support one protocol, and use 0 for this, others
1227 * support several and using 0 means to use the default protocol for
1228 * the family and type.
1230 * The protocol id is passed directly to the operating
1231 * system, so you can use protocols not listed in #GSocketProtocol if you
1232 * know the protocol number used for it.
1234 * Returns: a #GSocket or %NULL on error.
1235 * Free the returned object with g_object_unref().
1240 g_socket_new (GSocketFamily family,
1242 GSocketProtocol protocol,
1245 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1249 "protocol", protocol,
1254 * g_socket_new_from_fd:
1255 * @fd: a native socket file descriptor.
1256 * @error: #GError for error reporting, or %NULL to ignore.
1258 * Creates a new #GSocket from a native file descriptor
1259 * or winsock SOCKET handle.
1261 * This reads all the settings from the file descriptor so that
1262 * all properties should work. Note that the file descriptor
1263 * will be set to non-blocking mode, independent on the blocking
1264 * mode of the #GSocket.
1266 * On success, the returned #GSocket takes ownership of @fd. On failure, the
1267 * caller must close @fd themselves.
1269 * Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
1270 * descriptor. Instead, a GError will be set with code %G_IO_ERROR_FAILED
1272 * Returns: a #GSocket or %NULL on error.
1273 * Free the returned object with g_object_unref().
1278 g_socket_new_from_fd (gint fd,
1281 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1288 * g_socket_set_blocking:
1289 * @socket: a #GSocket.
1290 * @blocking: Whether to use blocking I/O or not.
1292 * Sets the blocking mode of the socket. In blocking mode
1293 * all operations (which don’t take an explicit blocking parameter) block until
1294 * they succeed or there is an error. In
1295 * non-blocking mode all functions return results immediately or
1296 * with a %G_IO_ERROR_WOULD_BLOCK error.
1298 * All sockets are created in blocking mode. However, note that the
1299 * platform level socket is always non-blocking, and blocking mode
1300 * is a GSocket level feature.
1305 g_socket_set_blocking (GSocket *socket,
1308 g_return_if_fail (G_IS_SOCKET (socket));
1310 blocking = !!blocking;
1312 if (socket->priv->blocking == blocking)
1315 socket->priv->blocking = blocking;
1316 g_object_notify (G_OBJECT (socket), "blocking");
1320 * g_socket_get_blocking:
1321 * @socket: a #GSocket.
1323 * Gets the blocking mode of the socket. For details on blocking I/O,
1324 * see g_socket_set_blocking().
1326 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1331 g_socket_get_blocking (GSocket *socket)
1333 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1335 return socket->priv->blocking;
1339 * g_socket_set_keepalive:
1340 * @socket: a #GSocket.
1341 * @keepalive: Value for the keepalive flag
1343 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1344 * this flag is set on a socket, the system will attempt to verify that the
1345 * remote socket endpoint is still present if a sufficiently long period of
1346 * time passes with no data being exchanged. If the system is unable to
1347 * verify the presence of the remote endpoint, it will automatically close
1350 * This option is only functional on certain kinds of sockets. (Notably,
1351 * %G_SOCKET_PROTOCOL_TCP sockets.)
1353 * The exact time between pings is system- and protocol-dependent, but will
1354 * normally be at least two hours. Most commonly, you would set this flag
1355 * on a server socket if you want to allow clients to remain idle for long
1356 * periods of time, but also want to ensure that connections are eventually
1357 * garbage-collected if clients crash or become unreachable.
1362 g_socket_set_keepalive (GSocket *socket,
1365 GError *error = NULL;
1367 g_return_if_fail (G_IS_SOCKET (socket));
1369 keepalive = !!keepalive;
1370 if (socket->priv->keepalive == keepalive)
1373 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1376 g_warning ("error setting keepalive: %s", error->message);
1377 g_error_free (error);
1381 socket->priv->keepalive = keepalive;
1382 g_object_notify (G_OBJECT (socket), "keepalive");
1386 * g_socket_get_keepalive:
1387 * @socket: a #GSocket.
1389 * Gets the keepalive mode of the socket. For details on this,
1390 * see g_socket_set_keepalive().
1392 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1397 g_socket_get_keepalive (GSocket *socket)
1399 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1401 return socket->priv->keepalive;
1405 * g_socket_get_listen_backlog:
1406 * @socket: a #GSocket.
1408 * Gets the listen backlog setting of the socket. For details on this,
1409 * see g_socket_set_listen_backlog().
1411 * Returns: the maximum number of pending connections.
1416 g_socket_get_listen_backlog (GSocket *socket)
1418 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1420 return socket->priv->listen_backlog;
1424 * g_socket_set_listen_backlog:
1425 * @socket: a #GSocket.
1426 * @backlog: the maximum number of pending connections.
1428 * Sets the maximum number of outstanding connections allowed
1429 * when listening on this socket. If more clients than this are
1430 * connecting to the socket and the application is not handling them
1431 * on time then the new connections will be refused.
1433 * Note that this must be called before g_socket_listen() and has no
1434 * effect if called after that.
1439 g_socket_set_listen_backlog (GSocket *socket,
1442 g_return_if_fail (G_IS_SOCKET (socket));
1443 g_return_if_fail (!socket->priv->listening);
1445 if (backlog != socket->priv->listen_backlog)
1447 socket->priv->listen_backlog = backlog;
1448 g_object_notify (G_OBJECT (socket), "listen-backlog");
1453 * g_socket_get_timeout:
1454 * @socket: a #GSocket.
1456 * Gets the timeout setting of the socket. For details on this, see
1457 * g_socket_set_timeout().
1459 * Returns: the timeout in seconds
1464 g_socket_get_timeout (GSocket *socket)
1466 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1468 return socket->priv->timeout;
1472 * g_socket_set_timeout:
1473 * @socket: a #GSocket.
1474 * @timeout: the timeout for @socket, in seconds, or 0 for none
1476 * Sets the time in seconds after which I/O operations on @socket will
1477 * time out if they have not yet completed.
1479 * On a blocking socket, this means that any blocking #GSocket
1480 * operation will time out after @timeout seconds of inactivity,
1481 * returning %G_IO_ERROR_TIMED_OUT.
1483 * On a non-blocking socket, calls to g_socket_condition_wait() will
1484 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1485 * created with g_socket_create_source() will trigger after
1486 * @timeout seconds of inactivity, with the requested condition
1487 * set, at which point calling g_socket_receive(), g_socket_send(),
1488 * g_socket_check_connect_result(), etc, will fail with
1489 * %G_IO_ERROR_TIMED_OUT.
1491 * If @timeout is 0 (the default), operations will never time out
1494 * Note that if an I/O operation is interrupted by a signal, this may
1495 * cause the timeout to be reset.
1500 g_socket_set_timeout (GSocket *socket,
1503 g_return_if_fail (G_IS_SOCKET (socket));
1505 if (timeout != socket->priv->timeout)
1507 socket->priv->timeout = timeout;
1508 g_object_notify (G_OBJECT (socket), "timeout");
1514 * @socket: a #GSocket.
1516 * Gets the unicast time-to-live setting on @socket; see
1517 * g_socket_set_ttl() for more details.
1519 * Returns: the time-to-live setting on @socket
1524 g_socket_get_ttl (GSocket *socket)
1526 GError *error = NULL;
1529 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1531 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1533 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1536 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1538 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1542 g_return_val_if_reached (0);
1546 g_warning ("error getting unicast ttl: %s", error->message);
1547 g_error_free (error);
1556 * @socket: a #GSocket.
1557 * @ttl: the time-to-live value for all unicast packets on @socket
1559 * Sets the time-to-live for outgoing unicast packets on @socket.
1560 * By default the platform-specific default value is used.
1565 g_socket_set_ttl (GSocket *socket,
1568 GError *error = NULL;
1570 g_return_if_fail (G_IS_SOCKET (socket));
1572 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1574 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1577 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1579 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1581 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1585 g_return_if_reached ();
1589 g_warning ("error setting unicast ttl: %s", error->message);
1590 g_error_free (error);
1594 g_object_notify (G_OBJECT (socket), "ttl");
1598 * g_socket_get_broadcast:
1599 * @socket: a #GSocket.
1601 * Gets the broadcast setting on @socket; if %TRUE,
1602 * it is possible to send packets to broadcast
1605 * Returns: the broadcast setting on @socket
1610 g_socket_get_broadcast (GSocket *socket)
1612 GError *error = NULL;
1615 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1617 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1620 g_warning ("error getting broadcast: %s", error->message);
1621 g_error_free (error);
1629 * g_socket_set_broadcast:
1630 * @socket: a #GSocket.
1631 * @broadcast: whether @socket should allow sending to broadcast
1634 * Sets whether @socket should allow sending to broadcast addresses.
1635 * This is %FALSE by default.
1640 g_socket_set_broadcast (GSocket *socket,
1643 GError *error = NULL;
1645 g_return_if_fail (G_IS_SOCKET (socket));
1647 broadcast = !!broadcast;
1649 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1652 g_warning ("error setting broadcast: %s", error->message);
1653 g_error_free (error);
1657 g_object_notify (G_OBJECT (socket), "broadcast");
1661 * g_socket_get_multicast_loopback:
1662 * @socket: a #GSocket.
1664 * Gets the multicast loopback setting on @socket; if %TRUE (the
1665 * default), outgoing multicast packets will be looped back to
1666 * multicast listeners on the same host.
1668 * Returns: the multicast loopback setting on @socket
1673 g_socket_get_multicast_loopback (GSocket *socket)
1675 GError *error = NULL;
1678 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1680 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1682 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1685 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1687 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1691 g_return_val_if_reached (FALSE);
1695 g_warning ("error getting multicast loopback: %s", error->message);
1696 g_error_free (error);
1704 * g_socket_set_multicast_loopback:
1705 * @socket: a #GSocket.
1706 * @loopback: whether @socket should receive messages sent to its
1707 * multicast groups from the local host
1709 * Sets whether outgoing multicast packets will be received by sockets
1710 * listening on that multicast address on the same host. This is %TRUE
1716 g_socket_set_multicast_loopback (GSocket *socket,
1719 GError *error = NULL;
1721 g_return_if_fail (G_IS_SOCKET (socket));
1723 loopback = !!loopback;
1725 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1727 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1730 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1732 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1734 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1738 g_return_if_reached ();
1742 g_warning ("error setting multicast loopback: %s", error->message);
1743 g_error_free (error);
1747 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1751 * g_socket_get_multicast_ttl:
1752 * @socket: a #GSocket.
1754 * Gets the multicast time-to-live setting on @socket; see
1755 * g_socket_set_multicast_ttl() for more details.
1757 * Returns: the multicast time-to-live setting on @socket
1762 g_socket_get_multicast_ttl (GSocket *socket)
1764 GError *error = NULL;
1767 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1769 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1771 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1774 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1776 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1780 g_return_val_if_reached (FALSE);
1784 g_warning ("error getting multicast ttl: %s", error->message);
1785 g_error_free (error);
1793 * g_socket_set_multicast_ttl:
1794 * @socket: a #GSocket.
1795 * @ttl: the time-to-live value for all multicast datagrams on @socket
1797 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1798 * By default, this is 1, meaning that multicast packets will not leave
1799 * the local network.
1804 g_socket_set_multicast_ttl (GSocket *socket,
1807 GError *error = NULL;
1809 g_return_if_fail (G_IS_SOCKET (socket));
1811 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1813 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1816 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1818 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1820 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1824 g_return_if_reached ();
1828 g_warning ("error setting multicast ttl: %s", error->message);
1829 g_error_free (error);
1833 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1837 * g_socket_get_family:
1838 * @socket: a #GSocket.
1840 * Gets the socket family of the socket.
1842 * Returns: a #GSocketFamily
1847 g_socket_get_family (GSocket *socket)
1849 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1851 return socket->priv->family;
1855 * g_socket_get_socket_type:
1856 * @socket: a #GSocket.
1858 * Gets the socket type of the socket.
1860 * Returns: a #GSocketType
1865 g_socket_get_socket_type (GSocket *socket)
1867 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1869 return socket->priv->type;
1873 * g_socket_get_protocol:
1874 * @socket: a #GSocket.
1876 * Gets the socket protocol id the socket was created with.
1877 * In case the protocol is unknown, -1 is returned.
1879 * Returns: a protocol id, or -1 if unknown
1884 g_socket_get_protocol (GSocket *socket)
1886 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1888 return socket->priv->protocol;
1893 * @socket: a #GSocket.
1895 * Returns the underlying OS socket object. On unix this
1896 * is a socket file descriptor, and on Windows this is
1897 * a Winsock2 SOCKET handle. This may be useful for
1898 * doing platform specific or otherwise unusual operations
1901 * Returns: the file descriptor of the socket.
1906 g_socket_get_fd (GSocket *socket)
1908 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1910 return socket->priv->fd;
1914 * g_socket_get_local_address:
1915 * @socket: a #GSocket.
1916 * @error: #GError for error reporting, or %NULL to ignore.
1918 * Try to get the local address of a bound socket. This is only
1919 * useful if the socket has been bound to a local address,
1920 * either explicitly or implicitly when connecting.
1922 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1923 * Free the returned object with g_object_unref().
1928 g_socket_get_local_address (GSocket *socket,
1932 struct sockaddr_storage storage;
1935 guint len = sizeof (buffer);
1937 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1939 if (getsockname (socket->priv->fd, &buffer.sa, &len) < 0)
1941 int errsv = get_socket_errno ();
1942 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1943 _("could not get local address: %s"), socket_strerror (errsv));
1947 return g_socket_address_new_from_native (&buffer.storage, len);
1951 * g_socket_get_remote_address:
1952 * @socket: a #GSocket.
1953 * @error: #GError for error reporting, or %NULL to ignore.
1955 * Try to get the remote address of a connected socket. This is only
1956 * useful for connection oriented sockets that have been connected.
1958 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1959 * Free the returned object with g_object_unref().
1964 g_socket_get_remote_address (GSocket *socket,
1968 struct sockaddr_storage storage;
1971 guint len = sizeof (buffer);
1973 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1975 if (socket->priv->connect_pending)
1977 if (!g_socket_check_connect_result (socket, error))
1980 socket->priv->connect_pending = FALSE;
1983 if (!socket->priv->remote_address)
1985 if (getpeername (socket->priv->fd, &buffer.sa, &len) < 0)
1987 int errsv = get_socket_errno ();
1988 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1989 _("could not get remote address: %s"), socket_strerror (errsv));
1993 socket->priv->remote_address = g_socket_address_new_from_native (&buffer.storage, len);
1996 return g_object_ref (socket->priv->remote_address);
2000 * g_socket_is_connected:
2001 * @socket: a #GSocket.
2003 * Check whether the socket is connected. This is only useful for
2004 * connection-oriented sockets.
2006 * If using g_socket_shutdown(), this function will return %TRUE until the
2007 * socket has been shut down for reading and writing. If you do a non-blocking
2008 * connect, this function will not return %TRUE until after you call
2009 * g_socket_check_connect_result().
2011 * Returns: %TRUE if socket is connected, %FALSE otherwise.
2016 g_socket_is_connected (GSocket *socket)
2018 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2020 return (socket->priv->connected_read || socket->priv->connected_write);
2025 * @socket: a #GSocket.
2026 * @error: #GError for error reporting, or %NULL to ignore.
2028 * Marks the socket as a server socket, i.e. a socket that is used
2029 * to accept incoming requests using g_socket_accept().
2031 * Before calling this the socket must be bound to a local address using
2034 * To set the maximum amount of outstanding clients, use
2035 * g_socket_set_listen_backlog().
2037 * Returns: %TRUE on success, %FALSE on error.
2042 g_socket_listen (GSocket *socket,
2045 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2047 if (!check_socket (socket, error))
2050 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
2052 int errsv = get_socket_errno ();
2054 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2055 _("could not listen: %s"), socket_strerror (errsv));
2059 socket->priv->listening = TRUE;
2066 * @socket: a #GSocket.
2067 * @address: a #GSocketAddress specifying the local address.
2068 * @allow_reuse: whether to allow reusing this address
2069 * @error: #GError for error reporting, or %NULL to ignore.
2071 * When a socket is created it is attached to an address family, but it
2072 * doesn't have an address in this family. g_socket_bind() assigns the
2073 * address (sometimes called name) of the socket.
2075 * It is generally required to bind to a local address before you can
2076 * receive connections. (See g_socket_listen() and g_socket_accept() ).
2077 * In certain situations, you may also want to bind a socket that will be
2078 * used to initiate connections, though this is not normally required.
2080 * If @socket is a TCP socket, then @allow_reuse controls the setting
2081 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
2082 * server sockets (sockets that you will eventually call
2083 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
2084 * set this flag on a server socket may cause g_socket_bind() to return
2085 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
2086 * immediately restarted.)
2088 * If @socket is a UDP socket, then @allow_reuse determines whether or
2089 * not other UDP sockets can be bound to the same address at the same
2090 * time. In particular, you can have several UDP sockets bound to the
2091 * same address, and they will all receive all of the multicast and
2092 * broadcast packets sent to that address. (The behavior of unicast
2093 * UDP packets to an address with multiple listeners is not defined.)
2095 * Returns: %TRUE on success, %FALSE on error.
2100 g_socket_bind (GSocket *socket,
2101 GSocketAddress *address,
2102 gboolean reuse_address,
2106 struct sockaddr_storage storage;
2109 gboolean so_reuseaddr;
2111 gboolean so_reuseport;
2114 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2116 if (!check_socket (socket, error))
2119 if (!g_socket_address_to_native (address, &addr.storage, sizeof addr, error))
2122 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
2123 * sockets, but has nasty side effects we don't want for TCP
2126 * On other platforms, we set SO_REUSEPORT, if it exists, for
2127 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
2128 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
2129 * the desired semantics on UDP (as it does on Linux, although
2130 * Linux has SO_REUSEPORT too as of 3.9).
2134 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2136 so_reuseaddr = !!reuse_address;
2140 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2143 /* Ignore errors here, the only likely error is "not supported", and
2144 * this is a "best effort" thing mainly.
2146 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
2148 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
2151 if (bind (socket->priv->fd, &addr.sa,
2152 g_socket_address_get_native_size (address)) < 0)
2154 int errsv = get_socket_errno ();
2156 G_IO_ERROR, socket_io_error_from_errno (errsv),
2157 _("Error binding to address: %s"), socket_strerror (errsv));
2165 g_socket_multicast_group_operation (GSocket *socket,
2166 GInetAddress *group,
2167 gboolean source_specific,
2169 gboolean join_group,
2172 const guint8 *native_addr;
2173 gint optname, result;
2175 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2176 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2177 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2179 if (!check_socket (socket, error))
2182 native_addr = g_inet_address_to_bytes (group);
2183 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2185 #ifdef HAVE_IP_MREQN
2186 struct ip_mreqn mc_req;
2188 struct ip_mreq mc_req;
2191 memset (&mc_req, 0, sizeof (mc_req));
2192 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2194 #ifdef HAVE_IP_MREQN
2196 mc_req.imr_ifindex = if_nametoindex (iface);
2198 mc_req.imr_ifindex = 0; /* Pick any. */
2199 #elif defined(G_OS_WIN32)
2201 mc_req.imr_interface.s_addr = g_htonl (if_nametoindex (iface));
2203 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2205 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2208 if (source_specific)
2210 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2211 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2213 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2215 _("Error joining multicast group: %s") :
2216 _("Error leaving multicast group: %s"),
2217 _("No support for source-specific multicast"));
2222 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2223 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2224 &mc_req, sizeof (mc_req));
2226 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2228 struct ipv6_mreq mc_req_ipv6;
2230 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2231 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2232 #ifdef HAVE_IF_NAMETOINDEX
2234 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2237 mc_req_ipv6.ipv6mr_interface = 0;
2239 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2240 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2241 &mc_req_ipv6, sizeof (mc_req_ipv6));
2244 g_return_val_if_reached (FALSE);
2248 int errsv = get_socket_errno ();
2250 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2252 _("Error joining multicast group: %s") :
2253 _("Error leaving multicast group: %s"),
2254 socket_strerror (errsv));
2262 * g_socket_join_multicast_group:
2263 * @socket: a #GSocket.
2264 * @group: a #GInetAddress specifying the group address to join.
2265 * @iface: (nullable): Name of the interface to use, or %NULL
2266 * @source_specific: %TRUE if source-specific multicast should be used
2267 * @error: #GError for error reporting, or %NULL to ignore.
2269 * Registers @socket to receive multicast messages sent to @group.
2270 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2271 * been bound to an appropriate interface and port with
2274 * If @iface is %NULL, the system will automatically pick an interface
2275 * to bind to based on @group.
2277 * If @source_specific is %TRUE, source-specific multicast as defined
2278 * in RFC 4604 is used. Note that on older platforms this may fail
2279 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2281 * To bind to a given source-specific multicast address, use
2282 * g_socket_join_multicast_group_ssm() instead.
2284 * Returns: %TRUE on success, %FALSE on error.
2289 g_socket_join_multicast_group (GSocket *socket,
2290 GInetAddress *group,
2291 gboolean source_specific,
2295 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2299 * g_socket_leave_multicast_group:
2300 * @socket: a #GSocket.
2301 * @group: a #GInetAddress specifying the group address to leave.
2302 * @iface: (nullable): Interface used
2303 * @source_specific: %TRUE if source-specific multicast was used
2304 * @error: #GError for error reporting, or %NULL to ignore.
2306 * Removes @socket from the multicast group defined by @group, @iface,
2307 * and @source_specific (which must all have the same values they had
2308 * when you joined the group).
2310 * @socket remains bound to its address and port, and can still receive
2311 * unicast messages after calling this.
2313 * To unbind to a given source-specific multicast address, use
2314 * g_socket_leave_multicast_group_ssm() instead.
2316 * Returns: %TRUE on success, %FALSE on error.
2321 g_socket_leave_multicast_group (GSocket *socket,
2322 GInetAddress *group,
2323 gboolean source_specific,
2327 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2331 g_socket_multicast_group_operation_ssm (GSocket *socket,
2332 GInetAddress *group,
2333 GInetAddress *source_specific,
2335 gboolean join_group,
2340 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2341 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2342 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2343 g_return_val_if_fail (iface == NULL || *iface != '\0', FALSE);
2344 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2346 if (!source_specific)
2348 return g_socket_multicast_group_operation (socket, group, FALSE, iface,
2352 if (!check_socket (socket, error))
2355 switch (g_inet_address_get_family (group))
2357 case G_SOCKET_FAMILY_INVALID:
2358 case G_SOCKET_FAMILY_UNIX:
2360 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2362 _("Error joining multicast group: %s") :
2363 _("Error leaving multicast group: %s"),
2364 _("Unsupported socket family"));
2369 case G_SOCKET_FAMILY_IPV4:
2371 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2373 #ifdef BROKEN_IP_MREQ_SOURCE_STRUCT
2374 #define S_ADDR_FIELD(src) src.imr_interface
2376 #define S_ADDR_FIELD(src) src.imr_interface.s_addr
2380 struct ip_mreq_source mc_req_src;
2382 if (g_inet_address_get_family (source_specific) !=
2383 G_SOCKET_FAMILY_IPV4)
2385 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2387 _("Error joining multicast group: %s") :
2388 _("Error leaving multicast group: %s"),
2389 _("source-specific not an IPv4 address"));
2393 memset (&mc_req_src, 0, sizeof (mc_req_src));
2395 /* By default use the default IPv4 multicast interface. */
2396 S_ADDR_FIELD(mc_req_src) = g_htonl (INADDR_ANY);
2400 #if defined(G_OS_WIN32) && defined (HAVE_IF_NAMETOINDEX)
2401 guint iface_index = if_nametoindex (iface);
2402 if (iface_index == 0)
2406 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2407 _("Interface not found: %s"), g_strerror (errsv));
2410 /* (0.0.0.iface_index) only works on Windows. */
2411 S_ADDR_FIELD(mc_req_src) = g_htonl (iface_index);
2412 #elif defined (HAVE_SIOCGIFADDR)
2415 struct sockaddr_in *iface_addr;
2416 size_t if_name_len = strlen (iface);
2418 memset (&ifr, 0, sizeof (ifr));
2420 if (if_name_len >= sizeof (ifr.ifr_name))
2422 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FILENAME_TOO_LONG,
2423 _("Interface name too long"));
2427 memcpy (ifr.ifr_name, iface, if_name_len);
2429 /* Get the IPv4 address of the given network interface name. */
2430 ret = ioctl (socket->priv->fd, SIOCGIFADDR, &ifr);
2435 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2436 _("Interface not found: %s"), g_strerror (errsv));
2440 iface_addr = (struct sockaddr_in *) &ifr.ifr_addr;
2441 S_ADDR_FIELD(mc_req_src) = iface_addr->sin_addr.s_addr;
2442 #endif /* defined(G_OS_WIN32) && defined (HAVE_IF_NAMETOINDEX) */
2444 memcpy (&mc_req_src.imr_multiaddr, g_inet_address_to_bytes (group),
2445 g_inet_address_get_native_size (group));
2446 memcpy (&mc_req_src.imr_sourceaddr,
2447 g_inet_address_to_bytes (source_specific),
2448 g_inet_address_get_native_size (source_specific));
2451 join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2452 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2453 &mc_req_src, sizeof (mc_req_src));
2458 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2460 _("Error joining multicast group: %s") :
2461 _("Error leaving multicast group: %s"),
2462 _("No support for IPv4 source-specific multicast"));
2464 #endif /* IP_ADD_SOURCE_MEMBERSHIP */
2468 case G_SOCKET_FAMILY_IPV6:
2470 #ifdef MCAST_JOIN_SOURCE_GROUP
2473 struct group_source_req mc_req_src;
2474 GSocketAddress *saddr_group, *saddr_source_specific;
2475 guint iface_index = 0;
2477 #if defined (HAVE_IF_NAMETOINDEX)
2480 iface_index = if_nametoindex (iface);
2481 if (iface_index == 0)
2485 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2486 _("Interface not found: %s"), g_strerror (errsv));
2490 #endif /* defined (HAVE_IF_NAMETOINDEX) */
2491 mc_req_src.gsr_interface = iface_index;
2493 saddr_group = g_inet_socket_address_new (group, 0);
2494 res = g_socket_address_to_native (saddr_group, &mc_req_src.gsr_group,
2495 sizeof (mc_req_src.gsr_group),
2497 g_object_unref (saddr_group);
2501 saddr_source_specific = g_inet_socket_address_new (source_specific, 0);
2502 res = g_socket_address_to_native (saddr_source_specific,
2503 &mc_req_src.gsr_source,
2504 sizeof (mc_req_src.gsr_source),
2506 g_object_unref (saddr_source_specific);
2512 join_group ? MCAST_JOIN_SOURCE_GROUP : MCAST_LEAVE_SOURCE_GROUP;
2513 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2514 &mc_req_src, sizeof (mc_req_src));
2516 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2518 _("Error joining multicast group: %s") :
2519 _("Error leaving multicast group: %s"),
2520 _("No support for IPv6 source-specific multicast"));
2522 #endif /* MCAST_JOIN_SOURCE_GROUP */
2527 g_return_val_if_reached (FALSE);
2532 int errsv = get_socket_errno ();
2534 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2536 _("Error joining multicast group: %s") :
2537 _("Error leaving multicast group: %s"),
2538 socket_strerror (errsv));
2546 * g_socket_join_multicast_group_ssm:
2547 * @socket: a #GSocket.
2548 * @group: a #GInetAddress specifying the group address to join.
2549 * @source_specific: (nullable): a #GInetAddress specifying the
2550 * source-specific multicast address or %NULL to ignore.
2551 * @iface: (nullable): Name of the interface to use, or %NULL
2552 * @error: #GError for error reporting, or %NULL to ignore.
2554 * Registers @socket to receive multicast messages sent to @group.
2555 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2556 * been bound to an appropriate interface and port with
2559 * If @iface is %NULL, the system will automatically pick an interface
2560 * to bind to based on @group.
2562 * If @source_specific is not %NULL, use source-specific multicast as
2563 * defined in RFC 4604. Note that on older platforms this may fail
2564 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2566 * Note that this function can be called multiple times for the same
2567 * @group with different @source_specific in order to receive multicast
2568 * packets from more than one source.
2570 * Returns: %TRUE on success, %FALSE on error.
2575 g_socket_join_multicast_group_ssm (GSocket *socket,
2576 GInetAddress *group,
2577 GInetAddress *source_specific,
2581 return g_socket_multicast_group_operation_ssm (socket, group,
2582 source_specific, iface, TRUE, error);
2586 * g_socket_leave_multicast_group_ssm:
2587 * @socket: a #GSocket.
2588 * @group: a #GInetAddress specifying the group address to leave.
2589 * @source_specific: (nullable): a #GInetAddress specifying the
2590 * source-specific multicast address or %NULL to ignore.
2591 * @iface: (nullable): Name of the interface to use, or %NULL
2592 * @error: #GError for error reporting, or %NULL to ignore.
2594 * Removes @socket from the multicast group defined by @group, @iface,
2595 * and @source_specific (which must all have the same values they had
2596 * when you joined the group).
2598 * @socket remains bound to its address and port, and can still receive
2599 * unicast messages after calling this.
2601 * Returns: %TRUE on success, %FALSE on error.
2606 g_socket_leave_multicast_group_ssm (GSocket *socket,
2607 GInetAddress *group,
2608 GInetAddress *source_specific,
2612 return g_socket_multicast_group_operation_ssm (socket, group,
2613 source_specific, iface, FALSE, error);
2617 * g_socket_speaks_ipv4:
2618 * @socket: a #GSocket
2620 * Checks if a socket is capable of speaking IPv4.
2622 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2623 * and under some combinations of circumstances IPv6 sockets are also
2624 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2627 * No other types of sockets are currently considered as being capable
2630 * Returns: %TRUE if this socket can be used with IPv4.
2635 g_socket_speaks_ipv4 (GSocket *socket)
2637 switch (socket->priv->family)
2639 case G_SOCKET_FAMILY_IPV4:
2642 case G_SOCKET_FAMILY_IPV6:
2643 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2647 if (!g_socket_get_option (socket,
2648 IPPROTO_IPV6, IPV6_V6ONLY,
2665 * @socket: a #GSocket.
2666 * @cancellable: (nullable): a %GCancellable or %NULL
2667 * @error: #GError for error reporting, or %NULL to ignore.
2669 * Accept incoming connections on a connection-based socket. This removes
2670 * the first outstanding connection request from the listening socket and
2671 * creates a #GSocket object for it.
2673 * The @socket must be bound to a local address with g_socket_bind() and
2674 * must be listening for incoming connections (g_socket_listen()).
2676 * If there are no outstanding connections then the operation will block
2677 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2678 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2680 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2681 * Free the returned object with g_object_unref().
2686 g_socket_accept (GSocket *socket,
2687 GCancellable *cancellable,
2690 GSocket *new_socket;
2693 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2695 if (!check_socket (socket, error))
2698 if (!check_timeout (socket, error))
2703 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2705 int errsv = get_socket_errno ();
2710 #ifdef WSAEWOULDBLOCK
2711 if (errsv == WSAEWOULDBLOCK)
2713 if (errsv == EWOULDBLOCK ||
2717 win32_unset_event_mask (socket, FD_ACCEPT);
2719 if (socket->priv->blocking)
2721 if (!g_socket_condition_wait (socket,
2722 G_IO_IN, cancellable, error))
2729 socket_set_error_lazy (error, errsv, _("Error accepting connection: %s"));
2735 win32_unset_event_mask (socket, FD_ACCEPT);
2739 /* The socket inherits the accepting sockets event mask and even object,
2740 we need to remove that */
2741 WSAEventSelect (ret, NULL, 0);
2747 /* We always want to set close-on-exec to protect users. If you
2748 need to so some weird inheritance to exec you can re-enable this
2749 using lower level hacks with g_socket_get_fd(). */
2750 flags = fcntl (ret, F_GETFD, 0);
2752 (flags & FD_CLOEXEC) == 0)
2754 flags |= FD_CLOEXEC;
2755 fcntl (ret, F_SETFD, flags);
2760 new_socket = g_socket_new_from_fd (ret, error);
2761 if (new_socket == NULL)
2770 new_socket->priv->protocol = socket->priv->protocol;
2777 * @socket: a #GSocket.
2778 * @address: a #GSocketAddress specifying the remote address.
2779 * @cancellable: (nullable): a %GCancellable or %NULL
2780 * @error: #GError for error reporting, or %NULL to ignore.
2782 * Connect the socket to the specified remote address.
2784 * For connection oriented socket this generally means we attempt to make
2785 * a connection to the @address. For a connection-less socket it sets
2786 * the default address for g_socket_send() and discards all incoming datagrams
2787 * from other sources.
2789 * Generally connection oriented sockets can only connect once, but
2790 * connection-less sockets can connect multiple times to change the
2793 * If the connect call needs to do network I/O it will block, unless
2794 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2795 * and the user can be notified of the connection finishing by waiting
2796 * for the G_IO_OUT condition. The result of the connection must then be
2797 * checked with g_socket_check_connect_result().
2799 * Returns: %TRUE if connected, %FALSE on error.
2804 g_socket_connect (GSocket *socket,
2805 GSocketAddress *address,
2806 GCancellable *cancellable,
2810 struct sockaddr_storage storage;
2814 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2816 if (!check_socket (socket, error))
2819 if (!g_socket_address_to_native (address, &buffer.storage, sizeof buffer, error))
2822 if (socket->priv->remote_address)
2823 g_object_unref (socket->priv->remote_address);
2824 socket->priv->remote_address = g_object_ref (address);
2828 if (connect (socket->priv->fd, &buffer.sa,
2829 g_socket_address_get_native_size (address)) < 0)
2831 int errsv = get_socket_errno ();
2837 if (errsv == EINPROGRESS)
2839 if (errsv == WSAEWOULDBLOCK)
2842 win32_unset_event_mask (socket, FD_CONNECT);
2844 if (socket->priv->blocking)
2846 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2848 if (g_socket_check_connect_result (socket, error))
2854 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2855 _("Connection in progress"));
2856 socket->priv->connect_pending = TRUE;
2860 g_set_error_literal (error, G_IO_ERROR,
2861 socket_io_error_from_errno (errsv),
2862 socket_strerror (errsv));
2869 win32_unset_event_mask (socket, FD_CONNECT);
2871 socket->priv->connected_read = TRUE;
2872 socket->priv->connected_write = TRUE;
2878 * g_socket_check_connect_result:
2879 * @socket: a #GSocket
2880 * @error: #GError for error reporting, or %NULL to ignore.
2882 * Checks and resets the pending connect error for the socket.
2883 * This is used to check for errors when g_socket_connect() is
2884 * used in non-blocking mode.
2886 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2891 g_socket_check_connect_result (GSocket *socket,
2896 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2898 if (!check_socket (socket, error))
2901 if (!check_timeout (socket, error))
2904 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
2906 g_prefix_error (error, _("Unable to get pending error: "));
2912 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2913 socket_strerror (value));
2914 if (socket->priv->remote_address)
2916 g_object_unref (socket->priv->remote_address);
2917 socket->priv->remote_address = NULL;
2922 socket->priv->connected_read = TRUE;
2923 socket->priv->connected_write = TRUE;
2929 * g_socket_get_available_bytes:
2930 * @socket: a #GSocket
2932 * Get the amount of data pending in the OS input buffer, without blocking.
2934 * If @socket is a UDP or SCTP socket, this will return the size of
2935 * just the next packet, even if additional packets are buffered after
2938 * Note that on Windows, this function is rather inefficient in the
2939 * UDP case, and so if you know any plausible upper bound on the size
2940 * of the incoming packet, it is better to just do a
2941 * g_socket_receive() with a buffer of that size, rather than calling
2942 * g_socket_get_available_bytes() first and then doing a receive of
2943 * exactly the right size.
2945 * Returns: the number of bytes that can be read from the socket
2946 * without blocking or truncating, or -1 on error.
2951 g_socket_get_available_bytes (GSocket *socket)
2954 const gint bufsize = 64 * 1024;
2955 static guchar *buf = NULL;
2963 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2966 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
2969 if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
2971 if (G_UNLIKELY (g_once_init_enter (&buf)))
2972 g_once_init_leave (&buf, g_malloc (bufsize));
2974 /* On datagram sockets, FIONREAD ioctl is not reliable because many
2975 * systems add internal header size to the reported size, making it
2976 * unusable for this function. */
2977 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
2980 int errsv = get_socket_errno ();
2982 if (errsv == WSAEWOULDBLOCK)
2984 if (errsv == EWOULDBLOCK || errsv == EAGAIN)
2992 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
2994 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
3003 /* Block on a timed wait for @condition until (@start_time + @timeout).
3004 * Return %G_IO_ERROR_TIMED_OUT if the timeout is reached; otherwise %TRUE.
3007 block_on_timeout (GSocket *socket,
3008 GIOCondition condition,
3011 GCancellable *cancellable,
3014 gint64 wait_timeout = -1;
3016 g_return_val_if_fail (timeout_us != 0, TRUE);
3018 /* check if we've timed out or how much time to wait at most */
3019 if (timeout_us >= 0)
3021 gint64 elapsed = g_get_monotonic_time () - start_time;
3023 if (elapsed >= timeout_us)
3025 g_set_error_literal (error,
3026 G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3027 _("Socket I/O timed out"));
3031 wait_timeout = timeout_us - elapsed;
3034 return g_socket_condition_timed_wait (socket, condition, wait_timeout,
3035 cancellable, error);
3039 g_socket_receive_with_timeout (GSocket *socket,
3043 GCancellable *cancellable,
3049 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3051 start_time = g_get_monotonic_time ();
3053 if (!check_socket (socket, error))
3056 if (!check_timeout (socket, error))
3059 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3064 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
3066 int errsv = get_socket_errno ();
3071 #ifdef WSAEWOULDBLOCK
3072 if (errsv == WSAEWOULDBLOCK)
3074 if (errsv == EWOULDBLOCK ||
3078 win32_unset_event_mask (socket, FD_READ);
3080 if (timeout_us != 0)
3082 if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
3083 cancellable, error))
3090 win32_unset_event_mask (socket, FD_READ);
3092 socket_set_error_lazy (error, errsv, _("Error receiving data: %s"));
3096 win32_unset_event_mask (socket, FD_READ);
3106 * @socket: a #GSocket
3107 * @buffer: (array length=size) (element-type guint8): a buffer to
3108 * read data into (which should be at least @size bytes long).
3109 * @size: the number of bytes you want to read from the socket
3110 * @cancellable: (nullable): a %GCancellable or %NULL
3111 * @error: #GError for error reporting, or %NULL to ignore.
3113 * Receive data (up to @size bytes) from a socket. This is mainly used by
3114 * connection-oriented sockets; it is identical to g_socket_receive_from()
3115 * with @address set to %NULL.
3117 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
3118 * g_socket_receive() will always read either 0 or 1 complete messages from
3119 * the socket. If the received message is too large to fit in @buffer, then
3120 * the data beyond @size bytes will be discarded, without any explicit
3121 * indication that this has occurred.
3123 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
3124 * number of bytes, up to @size. If more than @size bytes have been
3125 * received, the additional data will be returned in future calls to
3126 * g_socket_receive().
3128 * If the socket is in blocking mode the call will block until there
3129 * is some data to receive, the connection is closed, or there is an
3130 * error. If there is no data available and the socket is in
3131 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3132 * returned. To be notified when data is available, wait for the
3133 * %G_IO_IN condition.
3135 * On error -1 is returned and @error is set accordingly.
3137 * Returns: Number of bytes read, or 0 if the connection was closed by
3138 * the peer, or -1 on error
3143 g_socket_receive (GSocket *socket,
3146 GCancellable *cancellable,
3149 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3150 socket->priv->blocking ? -1 : 0,
3151 cancellable, error);
3155 * g_socket_receive_with_blocking:
3156 * @socket: a #GSocket
3157 * @buffer: (array length=size) (element-type guint8): a buffer to
3158 * read data into (which should be at least @size bytes long).
3159 * @size: the number of bytes you want to read from the socket
3160 * @blocking: whether to do blocking or non-blocking I/O
3161 * @cancellable: (nullable): a %GCancellable or %NULL
3162 * @error: #GError for error reporting, or %NULL to ignore.
3164 * This behaves exactly the same as g_socket_receive(), except that
3165 * the choice of blocking or non-blocking behavior is determined by
3166 * the @blocking argument rather than by @socket's properties.
3168 * Returns: Number of bytes read, or 0 if the connection was closed by
3169 * the peer, or -1 on error
3174 g_socket_receive_with_blocking (GSocket *socket,
3178 GCancellable *cancellable,
3181 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3182 blocking ? -1 : 0, cancellable, error);
3186 * g_socket_receive_from:
3187 * @socket: a #GSocket
3188 * @address: (out) (optional): a pointer to a #GSocketAddress
3190 * @buffer: (array length=size) (element-type guint8): a buffer to
3191 * read data into (which should be at least @size bytes long).
3192 * @size: the number of bytes you want to read from the socket
3193 * @cancellable: (nullable): a %GCancellable or %NULL
3194 * @error: #GError for error reporting, or %NULL to ignore.
3196 * Receive data (up to @size bytes) from a socket.
3198 * If @address is non-%NULL then @address will be set equal to the
3199 * source address of the received packet.
3200 * @address is owned by the caller.
3202 * See g_socket_receive() for additional information.
3204 * Returns: Number of bytes read, or 0 if the connection was closed by
3205 * the peer, or -1 on error
3210 g_socket_receive_from (GSocket *socket,
3211 GSocketAddress **address,
3214 GCancellable *cancellable,
3222 return g_socket_receive_message (socket,
3230 /* See the comment about SIGPIPE above. */
3232 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
3234 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
3238 g_socket_send_with_timeout (GSocket *socket,
3239 const guint8 *buffer,
3242 GCancellable *cancellable,
3248 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3250 start_time = g_get_monotonic_time ();
3252 if (!check_socket (socket, error))
3255 if (!check_timeout (socket, error))
3258 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3263 if ((ret = send (socket->priv->fd, (const char *)buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
3265 int errsv = get_socket_errno ();
3270 #ifdef WSAEWOULDBLOCK
3271 if (errsv == WSAEWOULDBLOCK)
3273 if (errsv == EWOULDBLOCK ||
3277 win32_unset_event_mask (socket, FD_WRITE);
3279 if (timeout_us != 0)
3281 if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
3282 cancellable, error))
3289 socket_set_error_lazy (error, errsv, _("Error sending data: %s"));
3300 * @socket: a #GSocket
3301 * @buffer: (array length=size) (element-type guint8): the buffer
3302 * containing the data to send.
3303 * @size: the number of bytes to send
3304 * @cancellable: (nullable): a %GCancellable or %NULL
3305 * @error: #GError for error reporting, or %NULL to ignore.
3307 * Tries to send @size bytes from @buffer on the socket. This is
3308 * mainly used by connection-oriented sockets; it is identical to
3309 * g_socket_send_to() with @address set to %NULL.
3311 * If the socket is in blocking mode the call will block until there is
3312 * space for the data in the socket queue. If there is no space available
3313 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3314 * will be returned. To be notified when space is available, wait for the
3315 * %G_IO_OUT condition. Note though that you may still receive
3316 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3317 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3318 * very common due to the way the underlying APIs work.)
3320 * On error -1 is returned and @error is set accordingly.
3322 * Returns: Number of bytes written (which may be less than @size), or -1
3328 g_socket_send (GSocket *socket,
3329 const gchar *buffer,
3331 GCancellable *cancellable,
3334 return g_socket_send_with_blocking (socket, buffer, size,
3335 socket->priv->blocking,
3336 cancellable, error);
3340 * g_socket_send_with_blocking:
3341 * @socket: a #GSocket
3342 * @buffer: (array length=size) (element-type guint8): the buffer
3343 * containing the data to send.
3344 * @size: the number of bytes to send
3345 * @blocking: whether to do blocking or non-blocking I/O
3346 * @cancellable: (nullable): a %GCancellable or %NULL
3347 * @error: #GError for error reporting, or %NULL to ignore.
3349 * This behaves exactly the same as g_socket_send(), except that
3350 * the choice of blocking or non-blocking behavior is determined by
3351 * the @blocking argument rather than by @socket's properties.
3353 * Returns: Number of bytes written (which may be less than @size), or -1
3359 g_socket_send_with_blocking (GSocket *socket,
3360 const gchar *buffer,
3363 GCancellable *cancellable,
3366 return g_socket_send_with_timeout (socket, (const guint8 *) buffer, size,
3367 blocking ? -1 : 0, cancellable, error);
3372 * @socket: a #GSocket
3373 * @address: (nullable): a #GSocketAddress, or %NULL
3374 * @buffer: (array length=size) (element-type guint8): the buffer
3375 * containing the data to send.
3376 * @size: the number of bytes to send
3377 * @cancellable: (nullable): a %GCancellable or %NULL
3378 * @error: #GError for error reporting, or %NULL to ignore.
3380 * Tries to send @size bytes from @buffer to @address. If @address is
3381 * %NULL then the message is sent to the default receiver (set by
3382 * g_socket_connect()).
3384 * See g_socket_send() for additional information.
3386 * Returns: Number of bytes written (which may be less than @size), or -1
3392 g_socket_send_to (GSocket *socket,
3393 GSocketAddress *address,
3394 const gchar *buffer,
3396 GCancellable *cancellable,
3404 return g_socket_send_message (socket,
3414 * g_socket_shutdown:
3415 * @socket: a #GSocket
3416 * @shutdown_read: whether to shut down the read side
3417 * @shutdown_write: whether to shut down the write side
3418 * @error: #GError for error reporting, or %NULL to ignore.
3420 * Shut down part or all of a full-duplex connection.
3422 * If @shutdown_read is %TRUE then the receiving side of the connection
3423 * is shut down, and further reading is disallowed.
3425 * If @shutdown_write is %TRUE then the sending side of the connection
3426 * is shut down, and further writing is disallowed.
3428 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
3430 * One example where it is useful to shut down only one side of a connection is
3431 * graceful disconnect for TCP connections where you close the sending side,
3432 * then wait for the other side to close the connection, thus ensuring that the
3433 * other side saw all sent data.
3435 * Returns: %TRUE on success, %FALSE on error
3440 g_socket_shutdown (GSocket *socket,
3441 gboolean shutdown_read,
3442 gboolean shutdown_write,
3447 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3449 if (!check_socket (socket, error))
3453 if (!shutdown_read && !shutdown_write)
3457 if (shutdown_read && shutdown_write)
3459 else if (shutdown_read)
3464 if (shutdown_read && shutdown_write)
3466 else if (shutdown_read)
3472 if (shutdown (socket->priv->fd, how) != 0)
3474 int errsv = get_socket_errno ();
3475 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
3476 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
3481 socket->priv->connected_read = FALSE;
3483 socket->priv->connected_write = FALSE;
3490 * @socket: a #GSocket
3491 * @error: #GError for error reporting, or %NULL to ignore.
3493 * Closes the socket, shutting down any active connection.
3495 * Closing a socket does not wait for all outstanding I/O operations
3496 * to finish, so the caller should not rely on them to be guaranteed
3497 * to complete even if the close returns with no error.
3499 * Once the socket is closed, all other operations will return
3500 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
3503 * Sockets will be automatically closed when the last reference
3504 * is dropped, but you might want to call this function to make sure
3505 * resources are released as early as possible.
3507 * Beware that due to the way that TCP works, it is possible for
3508 * recently-sent data to be lost if either you close a socket while the
3509 * %G_IO_IN condition is set, or else if the remote connection tries to
3510 * send something to you after you close the socket but before it has
3511 * finished reading all of the data you sent. There is no easy generic
3512 * way to avoid this problem; the easiest fix is to design the network
3513 * protocol such that the client will never send data "out of turn".
3514 * Another solution is for the server to half-close the connection by
3515 * calling g_socket_shutdown() with only the @shutdown_write flag set,
3516 * and then wait for the client to notice this and close its side of the
3517 * connection, after which the server can safely call g_socket_close().
3518 * (This is what #GTcpConnection does if you call
3519 * g_tcp_connection_set_graceful_disconnect(). But of course, this
3520 * only works if the client will close its connection after the server
3523 * Returns: %TRUE on success, %FALSE on error
3528 g_socket_close (GSocket *socket,
3533 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3535 if (socket->priv->closed)
3536 return TRUE; /* Multiple close not an error */
3538 if (!check_socket (socket, error))
3544 res = closesocket (socket->priv->fd);
3546 res = close (socket->priv->fd);
3550 int errsv = get_socket_errno ();
3555 g_set_error (error, G_IO_ERROR,
3556 socket_io_error_from_errno (errsv),
3557 _("Error closing socket: %s"),
3558 socket_strerror (errsv));
3564 socket->priv->fd = -1;
3565 socket->priv->connected_read = FALSE;
3566 socket->priv->connected_write = FALSE;
3567 socket->priv->closed = TRUE;
3568 if (socket->priv->remote_address)
3570 g_object_unref (socket->priv->remote_address);
3571 socket->priv->remote_address = NULL;
3578 * g_socket_is_closed:
3579 * @socket: a #GSocket
3581 * Checks whether a socket is closed.
3583 * Returns: %TRUE if socket is closed, %FALSE otherwise
3588 g_socket_is_closed (GSocket *socket)
3590 return socket->priv->closed;
3594 /* Broken source, used on errors */
3596 broken_dispatch (GSource *source,
3597 GSourceFunc callback,
3603 static GSourceFuncs broken_funcs =
3612 network_events_for_condition (GIOCondition condition)
3616 if (condition & G_IO_IN)
3617 event_mask |= (FD_READ | FD_ACCEPT);
3618 if (condition & G_IO_OUT)
3619 event_mask |= (FD_WRITE | FD_CONNECT);
3620 event_mask |= FD_CLOSE;
3626 ensure_event (GSocket *socket)
3628 if (socket->priv->event == WSA_INVALID_EVENT)
3629 socket->priv->event = WSACreateEvent();
3633 update_select_events (GSocket *socket)
3640 ensure_event (socket);
3643 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3646 event_mask |= network_events_for_condition (*ptr);
3649 if (event_mask != socket->priv->selected_events)
3651 /* If no events selected, disable event so we can unset
3654 if (event_mask == 0)
3657 event = socket->priv->event;
3659 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3660 socket->priv->selected_events = event_mask;
3665 add_condition_watch (GSocket *socket,
3666 GIOCondition *condition)
3668 g_mutex_lock (&socket->priv->win32_source_lock);
3669 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3671 socket->priv->requested_conditions =
3672 g_list_prepend (socket->priv->requested_conditions, condition);
3674 update_select_events (socket);
3675 g_mutex_unlock (&socket->priv->win32_source_lock);
3679 remove_condition_watch (GSocket *socket,
3680 GIOCondition *condition)
3682 g_mutex_lock (&socket->priv->win32_source_lock);
3683 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3685 socket->priv->requested_conditions =
3686 g_list_remove (socket->priv->requested_conditions, condition);
3688 update_select_events (socket);
3689 g_mutex_unlock (&socket->priv->win32_source_lock);
3693 update_condition_unlocked (GSocket *socket)
3695 WSANETWORKEVENTS events;
3696 GIOCondition condition;
3698 if (WSAEnumNetworkEvents (socket->priv->fd,
3699 socket->priv->event,
3702 socket->priv->current_events |= events.lNetworkEvents;
3703 if (events.lNetworkEvents & FD_WRITE &&
3704 events.iErrorCode[FD_WRITE_BIT] != 0)
3705 socket->priv->current_errors |= FD_WRITE;
3706 if (events.lNetworkEvents & FD_CONNECT &&
3707 events.iErrorCode[FD_CONNECT_BIT] != 0)
3708 socket->priv->current_errors |= FD_CONNECT;
3712 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3713 condition |= G_IO_IN;
3715 if (socket->priv->current_events & FD_CLOSE)
3717 int r, errsv, buffer;
3719 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3721 errsv = get_socket_errno ();
3724 (r < 0 && errsv == WSAENOTCONN))
3725 condition |= G_IO_IN;
3727 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3728 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3729 condition |= G_IO_HUP;
3731 condition |= G_IO_ERR;
3734 if (socket->priv->closed)
3735 condition |= G_IO_HUP;
3737 /* Never report both G_IO_OUT and HUP, these are
3738 mutually exclusive (can't write to a closed socket) */
3739 if ((condition & G_IO_HUP) == 0 &&
3740 socket->priv->current_events & FD_WRITE)
3742 if (socket->priv->current_errors & FD_WRITE)
3743 condition |= G_IO_ERR;
3745 condition |= G_IO_OUT;
3749 if (socket->priv->current_events & FD_CONNECT)
3751 if (socket->priv->current_errors & FD_CONNECT)
3752 condition |= (G_IO_HUP | G_IO_ERR);
3754 condition |= G_IO_OUT;
3762 update_condition (GSocket *socket)
3765 g_mutex_lock (&socket->priv->win32_source_lock);
3766 res = update_condition_unlocked (socket);
3767 g_mutex_unlock (&socket->priv->win32_source_lock);
3780 GIOCondition condition;
3784 socket_source_prepare (GSource *source,
3787 GSocketSource *socket_source = (GSocketSource *)source;
3792 if ((socket_source->pollfd.revents & G_IO_NVAL) != 0)
3795 if (g_socket_is_closed (socket_source->socket))
3797 g_source_remove_poll (source, &socket_source->pollfd);
3798 socket_source->pollfd.revents = G_IO_NVAL;
3802 return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3804 return g_socket_is_closed (socket_source->socket) && socket_source->fd_tag != NULL;
3810 socket_source_check_win32 (GSource *source)
3814 return socket_source_prepare (source, &timeout);
3819 socket_source_dispatch (GSource *source,
3820 GSourceFunc callback,
3823 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3824 GSocketSource *socket_source = (GSocketSource *)source;
3825 GSocket *socket = socket_source->socket;
3831 events = update_condition (socket_source->socket);
3833 if (g_socket_is_closed (socket_source->socket))
3835 if (socket_source->fd_tag)
3836 g_source_remove_unix_fd (source, socket_source->fd_tag);
3837 socket_source->fd_tag = NULL;
3842 events = g_source_query_unix_fd (source, socket_source->fd_tag);
3846 timeout = g_source_get_ready_time (source);
3847 if (timeout >= 0 && timeout < g_source_get_time (source) &&
3848 !g_socket_is_closed (socket_source->socket))
3850 socket->priv->timed_out = TRUE;
3851 events |= (G_IO_IN | G_IO_OUT);
3854 ret = (*func) (socket, events & socket_source->condition, user_data);
3856 if (socket->priv->timeout && !g_socket_is_closed (socket_source->socket))
3857 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3859 g_source_set_ready_time (source, -1);
3865 socket_source_finalize (GSource *source)
3867 GSocketSource *socket_source = (GSocketSource *)source;
3870 socket = socket_source->socket;
3873 remove_condition_watch (socket, &socket_source->condition);
3876 g_object_unref (socket);
3880 socket_source_closure_callback (GSocket *socket,
3881 GIOCondition condition,
3884 GClosure *closure = data;
3886 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3887 GValue result_value = G_VALUE_INIT;
3890 g_value_init (&result_value, G_TYPE_BOOLEAN);
3892 g_value_init (¶ms[0], G_TYPE_SOCKET);
3893 g_value_set_object (¶ms[0], socket);
3894 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
3895 g_value_set_flags (¶ms[1], condition);
3897 g_closure_invoke (closure, &result_value, 2, params, NULL);
3899 result = g_value_get_boolean (&result_value);
3900 g_value_unset (&result_value);
3901 g_value_unset (¶ms[0]);
3902 g_value_unset (¶ms[1]);
3907 static GSourceFuncs socket_source_funcs =
3909 socket_source_prepare,
3911 socket_source_check_win32,
3915 socket_source_dispatch,
3916 socket_source_finalize,
3917 (GSourceFunc)socket_source_closure_callback,
3921 socket_source_new (GSocket *socket,
3922 GIOCondition condition,
3923 GCancellable *cancellable)
3926 GSocketSource *socket_source;
3929 ensure_event (socket);
3931 if (socket->priv->event == WSA_INVALID_EVENT)
3933 g_warning ("Failed to create WSAEvent");
3934 return g_source_new (&broken_funcs, sizeof (GSource));
3938 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
3940 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3941 g_source_set_name (source, "GSocket");
3942 socket_source = (GSocketSource *)source;
3944 socket_source->socket = g_object_ref (socket);
3945 socket_source->condition = condition;
3949 GSource *cancellable_source;
3951 cancellable_source = g_cancellable_source_new (cancellable);
3952 g_source_add_child_source (source, cancellable_source);
3953 g_source_set_dummy_callback (cancellable_source);
3954 g_source_unref (cancellable_source);
3958 add_condition_watch (socket, &socket_source->condition);
3959 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3960 socket_source->pollfd.events = condition;
3961 socket_source->pollfd.revents = 0;
3962 g_source_add_poll (source, &socket_source->pollfd);
3964 socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
3967 if (socket->priv->timeout)
3968 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3970 g_source_set_ready_time (source, -1);
3976 * g_socket_create_source: (skip)
3977 * @socket: a #GSocket
3978 * @condition: a #GIOCondition mask to monitor
3979 * @cancellable: (nullable): a %GCancellable or %NULL
3981 * Creates a #GSource that can be attached to a %GMainContext to monitor
3982 * for the availability of the specified @condition on the socket. The #GSource
3983 * keeps a reference to the @socket.
3985 * The callback on the source is of the #GSocketSourceFunc type.
3987 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3988 * these conditions will always be reported output if they are true.
3990 * @cancellable if not %NULL can be used to cancel the source, which will
3991 * cause the source to trigger, reporting the current condition (which
3992 * is likely 0 unless cancellation happened at the same time as a
3993 * condition change). You can check for this in the callback using
3994 * g_cancellable_is_cancelled().
3996 * If @socket has a timeout set, and it is reached before @condition
3997 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3998 * %G_IO_OUT depending on @condition. However, @socket will have been
3999 * marked as having had a timeout, and so the next #GSocket I/O method
4000 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
4002 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
4007 g_socket_create_source (GSocket *socket,
4008 GIOCondition condition,
4009 GCancellable *cancellable)
4011 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
4013 return socket_source_new (socket, condition, cancellable);
4017 * g_socket_condition_check:
4018 * @socket: a #GSocket
4019 * @condition: a #GIOCondition mask to check
4021 * Checks on the readiness of @socket to perform operations.
4022 * The operations specified in @condition are checked for and masked
4023 * against the currently-satisfied conditions on @socket. The result
4026 * Note that on Windows, it is possible for an operation to return
4027 * %G_IO_ERROR_WOULD_BLOCK even immediately after
4028 * g_socket_condition_check() has claimed that the socket is ready for
4029 * writing. Rather than calling g_socket_condition_check() and then
4030 * writing to the socket if it succeeds, it is generally better to
4031 * simply try writing to the socket right away, and try again later if
4032 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
4034 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
4035 * these conditions will always be set in the output if they are true.
4037 * This call never blocks.
4039 * Returns: the @GIOCondition mask of the current state
4044 g_socket_condition_check (GSocket *socket,
4045 GIOCondition condition)
4047 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
4049 if (!check_socket (socket, NULL))
4054 GIOCondition current_condition;
4056 condition |= G_IO_ERR | G_IO_HUP;
4058 add_condition_watch (socket, &condition);
4059 current_condition = update_condition (socket);
4060 remove_condition_watch (socket, &condition);
4061 return condition & current_condition;
4067 poll_fd.fd = socket->priv->fd;
4068 poll_fd.events = condition;
4069 poll_fd.revents = 0;
4072 result = g_poll (&poll_fd, 1, 0);
4073 while (result == -1 && get_socket_errno () == EINTR);
4075 return poll_fd.revents;
4081 * g_socket_condition_wait:
4082 * @socket: a #GSocket
4083 * @condition: a #GIOCondition mask to wait for
4084 * @cancellable: (nullable): a #GCancellable, or %NULL
4085 * @error: a #GError pointer, or %NULL
4087 * Waits for @condition to become true on @socket. When the condition
4088 * is met, %TRUE is returned.
4090 * If @cancellable is cancelled before the condition is met, or if the
4091 * socket has a timeout set and it is reached before the condition is
4092 * met, then %FALSE is returned and @error, if non-%NULL, is set to
4093 * the appropriate value (%G_IO_ERROR_CANCELLED or
4094 * %G_IO_ERROR_TIMED_OUT).
4096 * See also g_socket_condition_timed_wait().
4098 * Returns: %TRUE if the condition was met, %FALSE otherwise
4103 g_socket_condition_wait (GSocket *socket,
4104 GIOCondition condition,
4105 GCancellable *cancellable,
4108 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4110 return g_socket_condition_timed_wait (socket, condition, -1,
4111 cancellable, error);
4115 * g_socket_condition_timed_wait:
4116 * @socket: a #GSocket
4117 * @condition: a #GIOCondition mask to wait for
4118 * @timeout_us: the maximum time (in microseconds) to wait, or -1
4119 * @cancellable: (nullable): a #GCancellable, or %NULL
4120 * @error: a #GError pointer, or %NULL
4122 * Waits for up to @timeout_us microseconds for @condition to become true
4123 * on @socket. If the condition is met, %TRUE is returned.
4125 * If @cancellable is cancelled before the condition is met, or if
4126 * @timeout_us (or the socket's #GSocket:timeout) is reached before the
4127 * condition is met, then %FALSE is returned and @error, if non-%NULL,
4128 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
4129 * %G_IO_ERROR_TIMED_OUT).
4131 * If you don't want a timeout, use g_socket_condition_wait().
4132 * (Alternatively, you can pass -1 for @timeout_us.)
4134 * Note that although @timeout_us is in microseconds for consistency with
4135 * other GLib APIs, this function actually only has millisecond
4136 * resolution, and the behavior is undefined if @timeout_us is not an
4137 * exact number of milliseconds.
4139 * Returns: %TRUE if the condition was met, %FALSE otherwise
4144 g_socket_condition_timed_wait (GSocket *socket,
4145 GIOCondition condition,
4147 GCancellable *cancellable,
4153 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4155 if (!check_socket (socket, error))
4158 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4161 if (socket->priv->timeout &&
4162 (timeout_us < 0 || socket->priv->timeout < timeout_us / G_USEC_PER_SEC))
4163 timeout_ms = (gint64) socket->priv->timeout * 1000;
4164 else if (timeout_us != -1)
4165 timeout_ms = timeout_us / 1000;
4169 start_time = g_get_monotonic_time ();
4173 GIOCondition current_condition;
4179 /* Always check these */
4180 condition |= G_IO_ERR | G_IO_HUP;
4182 add_condition_watch (socket, &condition);
4185 events[num_events++] = socket->priv->event;
4187 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
4188 events[num_events++] = (WSAEVENT)cancel_fd.fd;
4190 if (timeout_ms == -1)
4191 timeout_ms = WSA_INFINITE;
4193 g_mutex_lock (&socket->priv->win32_source_lock);
4194 current_condition = update_condition_unlocked (socket);
4195 while ((condition & current_condition) == 0)
4197 if (!socket->priv->waiting)
4199 socket->priv->waiting = TRUE;
4200 socket->priv->waiting_result = 0;
4201 g_mutex_unlock (&socket->priv->win32_source_lock);
4203 res = WSAWaitForMultipleEvents (num_events, events, FALSE, timeout_ms, FALSE);
4205 g_mutex_lock (&socket->priv->win32_source_lock);
4206 socket->priv->waiting = FALSE;
4207 socket->priv->waiting_result = res;
4208 g_cond_broadcast (&socket->priv->win32_source_cond);
4212 if (timeout_ms != WSA_INFINITE)
4214 if (!g_cond_wait_until (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock, timeout_ms))
4216 res = WSA_WAIT_TIMEOUT;
4221 res = socket->priv->waiting_result;
4226 g_cond_wait (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock);
4227 res = socket->priv->waiting_result;
4231 if (res == WSA_WAIT_FAILED)
4233 int errsv = get_socket_errno ();
4235 g_set_error (error, G_IO_ERROR,
4236 socket_io_error_from_errno (errsv),
4237 _("Waiting for socket condition: %s"),
4238 socket_strerror (errsv));
4241 else if (res == WSA_WAIT_TIMEOUT)
4243 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4244 _("Socket I/O timed out"));
4248 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4251 current_condition = update_condition_unlocked (socket);
4253 if (timeout_ms != WSA_INFINITE)
4255 timeout_ms -= (g_get_monotonic_time () - start_time) * 1000;
4260 g_mutex_unlock (&socket->priv->win32_source_lock);
4261 remove_condition_watch (socket, &condition);
4263 g_cancellable_release_fd (cancellable);
4265 return (condition & current_condition) != 0;
4273 poll_fd[0].fd = socket->priv->fd;
4274 poll_fd[0].events = condition;
4277 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
4283 result = g_poll (poll_fd, num, timeout_ms);
4285 if (result != -1 || errsv != EINTR)
4288 if (timeout_ms != -1)
4290 timeout_ms -= (g_get_monotonic_time () - start_time) / 1000;
4297 g_cancellable_release_fd (cancellable);
4301 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4302 _("Socket I/O timed out"));
4306 return !g_cancellable_set_error_if_cancelled (cancellable, error);
4313 /* Unfortunately these have to be macros rather than inline functions due to
4314 * using alloca(). */
4315 #define output_message_to_msghdr(message, prev_message, msg, prev_msg, error) \
4317 const GOutputMessage *_message = (message); \
4318 const GOutputMessage *_prev_message = (prev_message); \
4319 struct msghdr *_msg = (msg); \
4320 const struct msghdr *_prev_msg = (prev_msg); \
4321 GError **_error = (error); \
4323 _msg->msg_flags = 0; \
4326 if (_prev_message != NULL && _prev_message->address == _message->address) \
4328 _msg->msg_name = _prev_msg->msg_name; \
4329 _msg->msg_namelen = _prev_msg->msg_namelen; \
4331 else if (_message->address != NULL) \
4333 _msg->msg_namelen = g_socket_address_get_native_size (_message->address); \
4334 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4335 if (!g_socket_address_to_native (_message->address, _msg->msg_name, \
4336 _msg->msg_namelen, _error)) \
4341 _msg->msg_name = NULL; \
4342 _msg->msg_namelen = 0; \
4347 /* this entire expression will be evaluated at compile time */ \
4348 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4349 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4350 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4351 G_STRUCT_OFFSET (GOutputVector, buffer) && \
4352 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4353 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4354 G_STRUCT_OFFSET (GOutputVector, size)) \
4355 /* ABI is compatible */ \
4357 _msg->msg_iov = (struct iovec *) _message->vectors; \
4358 _msg->msg_iovlen = _message->num_vectors; \
4361 /* ABI is incompatible */ \
4365 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4366 for (i = 0; i < _message->num_vectors; i++) \
4368 _msg->msg_iov[i].iov_base = (void *) _message->vectors[i].buffer; \
4369 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4371 _msg->msg_iovlen = _message->num_vectors; \
4377 struct cmsghdr *cmsg; \
4380 _msg->msg_controllen = 0; \
4381 for (i = 0; i < _message->num_control_messages; i++) \
4382 _msg->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (_message->control_messages[i])); \
4384 if (_msg->msg_controllen == 0) \
4385 _msg->msg_control = NULL; \
4388 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4389 memset (_msg->msg_control, '\0', _msg->msg_controllen); \
4392 cmsg = CMSG_FIRSTHDR (_msg); \
4393 for (i = 0; i < _message->num_control_messages; i++) \
4395 cmsg->cmsg_level = g_socket_control_message_get_level (_message->control_messages[i]); \
4396 cmsg->cmsg_type = g_socket_control_message_get_msg_type (_message->control_messages[i]); \
4397 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (_message->control_messages[i])); \
4398 g_socket_control_message_serialize (_message->control_messages[i], \
4399 CMSG_DATA (cmsg)); \
4400 cmsg = CMSG_NXTHDR (_msg, cmsg); \
4402 g_assert (cmsg == NULL); \
4406 #define input_message_to_msghdr(message, msg) \
4408 const GInputMessage *_message = (message); \
4409 struct msghdr *_msg = (msg); \
4412 if (_message->address) \
4414 _msg->msg_namelen = sizeof (struct sockaddr_storage); \
4415 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4419 _msg->msg_name = NULL; \
4420 _msg->msg_namelen = 0; \
4424 /* this entire expression will be evaluated at compile time */ \
4425 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4426 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4427 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4428 G_STRUCT_OFFSET (GInputVector, buffer) && \
4429 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4430 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4431 G_STRUCT_OFFSET (GInputVector, size)) \
4432 /* ABI is compatible */ \
4434 _msg->msg_iov = (struct iovec *) _message->vectors; \
4435 _msg->msg_iovlen = _message->num_vectors; \
4438 /* ABI is incompatible */ \
4442 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4443 for (i = 0; i < _message->num_vectors; i++) \
4445 _msg->msg_iov[i].iov_base = _message->vectors[i].buffer; \
4446 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4448 _msg->msg_iovlen = _message->num_vectors; \
4452 if (_message->control_messages == NULL) \
4454 _msg->msg_controllen = 0; \
4455 _msg->msg_control = NULL; \
4459 _msg->msg_controllen = 2048; \
4460 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4464 _msg->msg_flags = _message->flags; \
4468 input_message_from_msghdr (const struct msghdr *msg,
4469 GInputMessage *message,
4472 /* decode address */
4473 if (message->address != NULL)
4475 *message->address = cache_recv_address (socket, msg->msg_name,
4479 /* decode control messages */
4481 GPtrArray *my_messages = NULL;
4482 struct cmsghdr *cmsg;
4484 if (msg->msg_controllen >= sizeof (struct cmsghdr))
4486 g_assert (message->control_messages != NULL);
4487 for (cmsg = CMSG_FIRSTHDR (msg);
4489 cmsg = CMSG_NXTHDR ((struct msghdr *) msg, cmsg))
4491 GSocketControlMessage *control_message;
4493 control_message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4495 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4497 if (control_message == NULL)
4498 /* We've already spewed about the problem in the
4499 deserialization code, so just continue */
4502 if (my_messages == NULL)
4503 my_messages = g_ptr_array_new ();
4504 g_ptr_array_add (my_messages, control_message);
4508 if (message->num_control_messages)
4509 *message->num_control_messages = my_messages != NULL ? my_messages->len : 0;
4511 if (message->control_messages)
4513 if (my_messages == NULL)
4515 *message->control_messages = NULL;
4519 g_ptr_array_add (my_messages, NULL);
4520 *message->control_messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4525 g_assert (my_messages == NULL);
4529 /* capture the flags */
4530 message->flags = msg->msg_flags;
4535 * g_socket_send_message:
4536 * @socket: a #GSocket
4537 * @address: (nullable): a #GSocketAddress, or %NULL
4538 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4539 * @num_vectors: the number of elements in @vectors, or -1
4540 * @messages: (array length=num_messages) (nullable): a pointer to an
4541 * array of #GSocketControlMessages, or %NULL.
4542 * @num_messages: number of elements in @messages, or -1.
4543 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
4544 * contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
4545 * @cancellable: (nullable): a %GCancellable or %NULL
4546 * @error: #GError for error reporting, or %NULL to ignore.
4548 * Send data to @address on @socket. For sending multiple messages see
4549 * g_socket_send_messages(); for easier use, see
4550 * g_socket_send() and g_socket_send_to().
4552 * If @address is %NULL then the message is sent to the default receiver
4553 * (set by g_socket_connect()).
4555 * @vectors must point to an array of #GOutputVector structs and
4556 * @num_vectors must be the length of this array. (If @num_vectors is -1,
4557 * then @vectors is assumed to be terminated by a #GOutputVector with a
4558 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
4559 * that the sent data will be gathered from. Using multiple
4560 * #GOutputVectors is more memory-efficient than manually copying
4561 * data from multiple sources into a single buffer, and more
4562 * network-efficient than making multiple calls to g_socket_send().
4564 * @messages, if non-%NULL, is taken to point to an array of @num_messages
4565 * #GSocketControlMessage instances. These correspond to the control
4566 * messages to be sent on the socket.
4567 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
4570 * @flags modify how the message is sent. The commonly available arguments
4571 * for this are available in the #GSocketMsgFlags enum, but the
4572 * values there are the same as the system values, and the flags
4573 * are passed in as-is, so you can pass in system-specific flags too.
4575 * If the socket is in blocking mode the call will block until there is
4576 * space for the data in the socket queue. If there is no space available
4577 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4578 * will be returned. To be notified when space is available, wait for the
4579 * %G_IO_OUT condition. Note though that you may still receive
4580 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4581 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4582 * very common due to the way the underlying APIs work.)
4584 * On error -1 is returned and @error is set accordingly.
4586 * Returns: Number of bytes written (which may be less than @size), or -1
4592 g_socket_send_message (GSocket *socket,
4593 GSocketAddress *address,
4594 GOutputVector *vectors,
4596 GSocketControlMessage **messages,
4599 GCancellable *cancellable,
4602 GPollableReturn res;
4603 gsize bytes_written = 0;
4605 res = g_socket_send_message_with_timeout (socket, address,
4606 vectors, num_vectors,
4607 messages, num_messages, flags,
4608 socket->priv->blocking ? -1 : 0,
4610 cancellable, error);
4612 if (res == G_POLLABLE_RETURN_WOULD_BLOCK)
4615 socket_set_error_lazy (error, EWOULDBLOCK, _("Error sending message: %s"));
4617 socket_set_error_lazy (error, WSAEWOULDBLOCK, _("Error sending message: %s"));
4621 return res == G_POLLABLE_RETURN_OK ? bytes_written : -1;
4625 * g_socket_send_message_with_timeout:
4626 * @socket: a #GSocket
4627 * @address: (nullable): a #GSocketAddress, or %NULL
4628 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4629 * @num_vectors: the number of elements in @vectors, or -1
4630 * @messages: (array length=num_messages) (nullable): a pointer to an
4631 * array of #GSocketControlMessages, or %NULL.
4632 * @num_messages: number of elements in @messages, or -1.
4633 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
4634 * contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
4635 * @timeout_us: the maximum time (in microseconds) to wait, or -1
4636 * @bytes_written: (out) (optional): location to store the number of bytes that were written to the socket
4637 * @cancellable: (nullable): a %GCancellable or %NULL
4638 * @error: #GError for error reporting, or %NULL to ignore.
4640 * This behaves exactly the same as g_socket_send_message(), except that
4641 * the choice of timeout behavior is determined by the @timeout_us argument
4642 * rather than by @socket's properties.
4644 * On error %G_POLLABLE_RETURN_FAILED is returned and @error is set accordingly, or
4645 * if the socket is currently not writable %G_POLLABLE_RETURN_WOULD_BLOCK is
4646 * returned. @bytes_written will contain 0 in both cases.
4648 * Returns: %G_POLLABLE_RETURN_OK if all data was successfully written,
4649 * %G_POLLABLE_RETURN_WOULD_BLOCK if the socket is currently not writable, or
4650 * %G_POLLABLE_RETURN_FAILED if an error happened and @error is set.
4655 g_socket_send_message_with_timeout (GSocket *socket,
4656 GSocketAddress *address,
4657 const GOutputVector *vectors,
4659 GSocketControlMessage **messages,
4663 gsize *bytes_written,
4664 GCancellable *cancellable,
4667 GOutputVector one_vector;
4674 g_return_val_if_fail (G_IS_SOCKET (socket), G_POLLABLE_RETURN_FAILED);
4675 g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), G_POLLABLE_RETURN_FAILED);
4676 g_return_val_if_fail (num_vectors == 0 || vectors != NULL, G_POLLABLE_RETURN_FAILED);
4677 g_return_val_if_fail (num_messages == 0 || messages != NULL, G_POLLABLE_RETURN_FAILED);
4678 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), G_POLLABLE_RETURN_FAILED);
4679 g_return_val_if_fail (error == NULL || *error == NULL, G_POLLABLE_RETURN_FAILED);
4681 start_time = g_get_monotonic_time ();
4683 if (!check_socket (socket, error))
4684 return G_POLLABLE_RETURN_FAILED;
4686 if (!check_timeout (socket, error))
4687 return G_POLLABLE_RETURN_FAILED;
4689 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4690 return G_POLLABLE_RETURN_FAILED;
4692 if (num_vectors == -1)
4694 for (num_vectors = 0;
4695 vectors[num_vectors].buffer != NULL;
4700 if (num_messages == -1)
4702 for (num_messages = 0;
4703 messages != NULL && messages[num_messages] != NULL;
4708 if (num_vectors == 0)
4712 one_vector.buffer = &zero;
4713 one_vector.size = 1;
4715 vectors = &one_vector;
4720 GOutputMessage output_message;
4723 GError *child_error = NULL;
4725 output_message.address = address;
4726 output_message.vectors = (GOutputVector *) vectors;
4727 output_message.num_vectors = num_vectors;
4728 output_message.bytes_sent = 0;
4729 output_message.control_messages = messages;
4730 output_message.num_control_messages = num_messages;
4732 output_message_to_msghdr (&output_message, NULL, &msg, NULL, &child_error);
4734 if (child_error != NULL)
4736 g_propagate_error (error, child_error);
4737 return G_POLLABLE_RETURN_FAILED;
4742 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4745 int errsv = get_socket_errno ();
4750 if (errsv == EWOULDBLOCK || errsv == EAGAIN)
4752 if (timeout_us != 0)
4754 if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
4755 cancellable, error))
4756 return G_POLLABLE_RETURN_FAILED;
4761 return G_POLLABLE_RETURN_WOULD_BLOCK;
4764 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4765 return G_POLLABLE_RETURN_FAILED;
4771 *bytes_written = result;
4773 return G_POLLABLE_RETURN_OK;
4777 struct sockaddr_storage addr;
4784 /* Win32 doesn't support control messages.
4785 Actually this is possible for raw and datagram sockets
4786 via WSASendMessage on Vista or later, but that doesn't
4788 if (num_messages != 0)
4790 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
4791 _("GSocketControlMessage not supported on Windows"));
4792 return G_POLLABLE_RETURN_FAILED;
4796 bufs = g_newa (WSABUF, num_vectors);
4797 for (i = 0; i < num_vectors; i++)
4799 bufs[i].buf = (char *)vectors[i].buffer;
4800 bufs[i].len = (gulong)vectors[i].size;
4804 addrlen = 0; /* Avoid warning */
4807 addrlen = g_socket_address_get_native_size (address);
4808 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
4809 return G_POLLABLE_RETURN_FAILED;
4815 result = WSASendTo (socket->priv->fd,
4818 (const struct sockaddr *)&addr, addrlen,
4821 result = WSASend (socket->priv->fd,
4828 int errsv = get_socket_errno ();
4830 if (errsv == WSAEINTR)
4833 if (errsv == WSAEWOULDBLOCK)
4835 win32_unset_event_mask (socket, FD_WRITE);
4837 if (timeout_us != 0)
4839 if (!block_on_timeout (socket, G_IO_OUT, timeout_us,
4840 start_time, cancellable, error))
4841 return G_POLLABLE_RETURN_FAILED;
4846 return G_POLLABLE_RETURN_WOULD_BLOCK;
4849 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4850 return G_POLLABLE_RETURN_FAILED;
4856 *bytes_written = bytes_sent;
4857 return G_POLLABLE_RETURN_OK;
4863 * g_socket_send_messages:
4864 * @socket: a #GSocket
4865 * @messages: (array length=num_messages): an array of #GOutputMessage structs
4866 * @num_messages: the number of elements in @messages
4867 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
4868 * contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
4869 * @cancellable: (nullable): a %GCancellable or %NULL
4870 * @error: #GError for error reporting, or %NULL to ignore.
4872 * Send multiple data messages from @socket in one go. This is the most
4873 * complicated and fully-featured version of this call. For easier use, see
4874 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
4876 * @messages must point to an array of #GOutputMessage structs and
4877 * @num_messages must be the length of this array. Each #GOutputMessage
4878 * contains an address to send the data to, and a pointer to an array of
4879 * #GOutputVector structs to describe the buffers that the data to be sent
4880 * for each message will be gathered from. Using multiple #GOutputVectors is
4881 * more memory-efficient than manually copying data from multiple sources
4882 * into a single buffer, and more network-efficient than making multiple
4883 * calls to g_socket_send(). Sending multiple messages in one go avoids the
4884 * overhead of making a lot of syscalls in scenarios where a lot of data
4885 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
4886 * or where the same data needs to be sent to multiple recipients.
4888 * @flags modify how the message is sent. The commonly available arguments
4889 * for this are available in the #GSocketMsgFlags enum, but the
4890 * values there are the same as the system values, and the flags
4891 * are passed in as-is, so you can pass in system-specific flags too.
4893 * If the socket is in blocking mode the call will block until there is
4894 * space for all the data in the socket queue. If there is no space available
4895 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4896 * will be returned if no data was written at all, otherwise the number of
4897 * messages sent will be returned. To be notified when space is available,
4898 * wait for the %G_IO_OUT condition. Note though that you may still receive
4899 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4900 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4901 * very common due to the way the underlying APIs work.)
4903 * On error -1 is returned and @error is set accordingly. An error will only
4904 * be returned if zero messages could be sent; otherwise the number of messages
4905 * successfully sent before the error will be returned.
4907 * Returns: number of messages sent, or -1 on error. Note that the number of
4908 * messages sent may be smaller than @num_messages if the socket is
4909 * non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
4910 * in which case the caller may re-try to send the remaining messages.
4915 g_socket_send_messages (GSocket *socket,
4916 GOutputMessage *messages,
4919 GCancellable *cancellable,
4922 return g_socket_send_messages_with_timeout (socket, messages, num_messages,
4924 socket->priv->blocking ? -1 : 0,
4925 cancellable, error);
4929 g_socket_send_messages_with_timeout (GSocket *socket,
4930 GOutputMessage *messages,
4934 GCancellable *cancellable,
4939 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4940 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
4941 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
4942 g_return_val_if_fail (error == NULL || *error == NULL, -1);
4944 start_time = g_get_monotonic_time ();
4946 if (!check_socket (socket, error))
4949 if (!check_timeout (socket, error))
4952 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4955 if (num_messages == 0)
4958 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
4960 struct mmsghdr *msgvec;
4964 #define MAX_NUM_MESSAGES UIO_MAXIOV
4966 #define MAX_NUM_MESSAGES 1024
4969 if (num_messages > MAX_NUM_MESSAGES)
4970 num_messages = MAX_NUM_MESSAGES;
4972 msgvec = g_newa (struct mmsghdr, num_messages);
4974 for (i = 0; i < num_messages; ++i)
4976 GOutputMessage *msg = &messages[i];
4977 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
4978 GError *child_error = NULL;
4980 msgvec[i].msg_len = 0;
4982 output_message_to_msghdr (msg, (i > 0) ? &messages[i - 1] : NULL,
4983 msg_hdr, (i > 0) ? &msgvec[i - 1].msg_hdr : NULL,
4986 if (child_error != NULL)
4988 g_propagate_error (error, child_error);
4993 for (num_sent = 0; num_sent < num_messages;)
4997 ret = sendmmsg (socket->priv->fd, msgvec + num_sent, num_messages - num_sent,
4998 flags | G_SOCKET_DEFAULT_SEND_FLAGS);
5002 int errsv = get_socket_errno ();
5007 if (timeout_us != 0 &&
5008 (errsv == EWOULDBLOCK ||
5011 if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
5012 cancellable, error))
5016 g_clear_error (error);
5026 /* If any messages were successfully sent, do not error. */
5030 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5038 for (i = 0; i < num_sent; ++i)
5039 messages[i].bytes_sent = msgvec[i].msg_len;
5047 gint64 wait_timeout;
5049 wait_timeout = timeout_us;
5051 for (i = 0; i < num_messages; ++i)
5053 GOutputMessage *msg = &messages[i];
5054 GError *msg_error = NULL;
5055 GPollableReturn pollable_result;
5056 gsize bytes_written = 0;
5058 pollable_result = g_socket_send_message_with_timeout (socket, msg->address,
5061 msg->control_messages,
5062 msg->num_control_messages,
5063 flags, wait_timeout,
5065 cancellable, &msg_error);
5067 if (pollable_result == G_POLLABLE_RETURN_WOULD_BLOCK)
5070 socket_set_error_lazy (&msg_error, EWOULDBLOCK, _("Error sending message: %s"));
5072 socket_set_error_lazy (&msg_error, WSAEWOULDBLOCK, _("Error sending message: %s"));
5076 result = pollable_result == G_POLLABLE_RETURN_OK ? bytes_written : -1;
5078 /* check if we've timed out or how much time to wait at most */
5081 gint64 elapsed = g_get_monotonic_time () - start_time;
5082 wait_timeout = MAX (timeout_us - elapsed, 1);
5087 /* if we couldn't send all messages, just return how many we did
5088 * manage to send, provided we managed to send at least one */
5091 g_error_free (msg_error);
5096 g_propagate_error (error, msg_error);
5101 msg->bytes_sent = result;
5109 static GSocketAddress *
5110 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
5112 GSocketAddress *saddr;
5114 guint64 oldest_time = G_MAXUINT64;
5115 gint oldest_index = 0;
5117 if (native_len <= 0)
5121 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
5123 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
5124 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
5125 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
5130 if (tmp_native_len != native_len)
5133 if (memcmp (tmp_native, native, native_len) == 0)
5135 saddr = g_object_ref (tmp);
5136 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
5140 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
5142 oldest_time = socket->priv->recv_addr_cache[i].last_used;
5147 saddr = g_socket_address_new_from_native (native, native_len);
5149 if (socket->priv->recv_addr_cache[oldest_index].addr)
5151 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
5152 g_free (socket->priv->recv_addr_cache[oldest_index].native);
5155 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
5156 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
5157 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
5158 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
5164 g_socket_receive_message_with_timeout (GSocket *socket,
5165 GSocketAddress **address,
5166 GInputVector *vectors,
5168 GSocketControlMessage ***messages,
5172 GCancellable *cancellable,
5175 GInputVector one_vector;
5179 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5181 start_time = g_get_monotonic_time ();
5183 if (!check_socket (socket, error))
5186 if (!check_timeout (socket, error))
5189 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5192 if (num_vectors == -1)
5194 for (num_vectors = 0;
5195 vectors[num_vectors].buffer != NULL;
5200 if (num_vectors == 0)
5202 one_vector.buffer = &one_byte;
5203 one_vector.size = 1;
5205 vectors = &one_vector;
5210 GInputMessage input_message;
5214 input_message.address = address;
5215 input_message.vectors = vectors;
5216 input_message.num_vectors = num_vectors;
5217 input_message.bytes_received = 0;
5218 input_message.flags = (flags != NULL) ? *flags : 0;
5219 input_message.control_messages = messages;
5220 input_message.num_control_messages = (guint *) num_messages;
5222 /* We always set the close-on-exec flag so we don't leak file
5223 * descriptors into child processes. Note that gunixfdmessage.c
5224 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5226 #ifdef MSG_CMSG_CLOEXEC
5227 input_message.flags |= MSG_CMSG_CLOEXEC;
5230 input_message_to_msghdr (&input_message, &msg);
5235 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5236 #ifdef MSG_CMSG_CLOEXEC
5237 if (result < 0 && get_socket_errno () == EINVAL)
5239 /* We must be running on an old kernel. Call without the flag. */
5240 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
5241 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5247 int errsv = get_socket_errno ();
5252 if (timeout_us != 0 &&
5253 (errsv == EWOULDBLOCK ||
5256 if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
5257 cancellable, error))
5263 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5269 input_message_from_msghdr (&msg, &input_message, socket);
5272 *flags = input_message.flags;
5278 struct sockaddr_storage addr;
5280 DWORD bytes_received;
5287 bufs = g_newa (WSABUF, num_vectors);
5288 for (i = 0; i < num_vectors; i++)
5290 bufs[i].buf = (char *)vectors[i].buffer;
5291 bufs[i].len = (gulong)vectors[i].size;
5303 addrlen = sizeof addr;
5305 result = WSARecvFrom (socket->priv->fd,
5307 &bytes_received, &win_flags,
5308 (struct sockaddr *)&addr, &addrlen,
5311 result = WSARecv (socket->priv->fd,
5313 &bytes_received, &win_flags,
5317 int errsv = get_socket_errno ();
5319 if (errsv == WSAEINTR)
5322 if (errsv == WSAEWOULDBLOCK)
5324 win32_unset_event_mask (socket, FD_READ);
5326 if (timeout_us != 0)
5328 if (!block_on_timeout (socket, G_IO_IN, timeout_us,
5329 start_time, cancellable, error))
5336 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5339 win32_unset_event_mask (socket, FD_READ);
5343 /* decode address */
5344 if (address != NULL)
5346 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
5349 /* capture the flags */
5353 if (messages != NULL)
5355 if (num_messages != NULL)
5358 return bytes_received;
5364 * g_socket_receive_messages:
5365 * @socket: a #GSocket
5366 * @messages: (array length=num_messages): an array of #GInputMessage structs
5367 * @num_messages: the number of elements in @messages
5368 * @flags: an int containing #GSocketMsgFlags flags for the overall operation,
5369 * which may additionally contain
5370 * [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5371 * @cancellable: (nullable): a %GCancellable or %NULL
5372 * @error: #GError for error reporting, or %NULL to ignore
5374 * Receive multiple data messages from @socket in one go. This is the most
5375 * complicated and fully-featured version of this call. For easier use, see
5376 * g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
5378 * @messages must point to an array of #GInputMessage structs and
5379 * @num_messages must be the length of this array. Each #GInputMessage
5380 * contains a pointer to an array of #GInputVector structs describing the
5381 * buffers that the data received in each message will be written to. Using
5382 * multiple #GInputVectors is more memory-efficient than manually copying data
5383 * out of a single buffer to multiple sources, and more system-call-efficient
5384 * than making multiple calls to g_socket_receive(), such as in scenarios where
5385 * a lot of data packets need to be received (e.g. high-bandwidth video
5386 * streaming over RTP/UDP).
5388 * @flags modify how all messages are received. The commonly available
5389 * arguments for this are available in the #GSocketMsgFlags enum, but the
5390 * values there are the same as the system values, and the flags
5391 * are passed in as-is, so you can pass in system-specific flags too. These
5392 * flags affect the overall receive operation. Flags affecting individual
5393 * messages are returned in #GInputMessage.flags.
5395 * The other members of #GInputMessage are treated as described in its
5398 * If #GSocket:blocking is %TRUE the call will block until @num_messages have
5399 * been received, or the end of the stream is reached.
5401 * If #GSocket:blocking is %FALSE the call will return up to @num_messages
5402 * without blocking, or %G_IO_ERROR_WOULD_BLOCK if no messages are queued in the
5403 * operating system to be received.
5405 * In blocking mode, if #GSocket:timeout is positive and is reached before any
5406 * messages are received, %G_IO_ERROR_TIMED_OUT is returned, otherwise up to
5407 * @num_messages are returned. (Note: This is effectively the
5408 * behaviour of `MSG_WAITFORONE` with recvmmsg().)
5410 * To be notified when messages are available, wait for the
5411 * %G_IO_IN condition. Note though that you may still receive
5412 * %G_IO_ERROR_WOULD_BLOCK from g_socket_receive_messages() even if you were
5413 * previously notified of a %G_IO_IN condition.
5415 * If the remote peer closes the connection, any messages queued in the
5416 * operating system will be returned, and subsequent calls to
5417 * g_socket_receive_messages() will return 0 (with no error set).
5419 * On error -1 is returned and @error is set accordingly. An error will only
5420 * be returned if zero messages could be received; otherwise the number of
5421 * messages successfully received before the error will be returned.
5423 * Returns: number of messages received, or -1 on error. Note that the number
5424 * of messages received may be smaller than @num_messages if in non-blocking
5425 * mode, if the peer closed the connection, or if @num_messages
5426 * was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
5427 * to receive the remaining messages.
5432 g_socket_receive_messages (GSocket *socket,
5433 GInputMessage *messages,
5436 GCancellable *cancellable,
5439 if (!check_socket (socket, error) ||
5440 !check_timeout (socket, error))
5443 return g_socket_receive_messages_with_timeout (socket, messages, num_messages,
5445 socket->priv->blocking ? -1 : 0,
5446 cancellable, error);
5450 g_socket_receive_messages_with_timeout (GSocket *socket,
5451 GInputMessage *messages,
5455 GCancellable *cancellable,
5460 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5461 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5462 g_return_val_if_fail (cancellable == NULL ||
5463 G_IS_CANCELLABLE (cancellable), -1);
5464 g_return_val_if_fail (error == NULL || *error == NULL, -1);
5466 start_time = g_get_monotonic_time ();
5468 if (!check_socket (socket, error))
5471 if (!check_timeout (socket, error))
5474 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5477 if (num_messages == 0)
5480 #if !defined (G_OS_WIN32) && defined (HAVE_RECVMMSG)
5482 struct mmsghdr *msgvec;
5483 guint i, num_received;
5486 #define MAX_NUM_MESSAGES UIO_MAXIOV
5488 #define MAX_NUM_MESSAGES 1024
5491 if (num_messages > MAX_NUM_MESSAGES)
5492 num_messages = MAX_NUM_MESSAGES;
5494 msgvec = g_newa (struct mmsghdr, num_messages);
5496 for (i = 0; i < num_messages; ++i)
5498 GInputMessage *msg = &messages[i];
5499 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5501 input_message_to_msghdr (msg, msg_hdr);
5502 msgvec[i].msg_len = 0;
5505 /* We always set the close-on-exec flag so we don't leak file
5506 * descriptors into child processes. Note that gunixfdmessage.c
5507 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5509 #ifdef MSG_CMSG_CLOEXEC
5510 flags |= MSG_CMSG_CLOEXEC;
5513 for (num_received = 0; num_received < num_messages;)
5517 /* We operate in non-blocking mode and handle the timeout ourselves. */
5518 ret = recvmmsg (socket->priv->fd,
5519 msgvec + num_received,
5520 num_messages - num_received,
5521 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5522 #ifdef MSG_CMSG_CLOEXEC
5523 if (ret < 0 && get_socket_errno () == EINVAL)
5525 /* We must be running on an old kernel. Call without the flag. */
5526 flags &= ~(MSG_CMSG_CLOEXEC);
5527 ret = recvmmsg (socket->priv->fd,
5528 msgvec + num_received,
5529 num_messages - num_received,
5530 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5536 int errsv = get_socket_errno ();
5541 if (timeout_us != 0 &&
5542 (errsv == EWOULDBLOCK ||
5545 if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
5546 cancellable, error))
5548 if (num_received > 0)
5550 g_clear_error (error);
5560 /* If any messages were successfully received, do not error. */
5561 if (num_received > 0)
5564 socket_set_error_lazy (error, errsv,
5565 _("Error receiving message: %s"));
5575 num_received += ret;
5578 for (i = 0; i < num_received; ++i)
5580 input_message_from_msghdr (&msgvec[i].msg_hdr, &messages[i], socket);
5581 messages[i].bytes_received = msgvec[i].msg_len;
5584 return num_received;
5589 gint64 wait_timeout;
5591 wait_timeout = timeout_us;
5593 for (i = 0; i < num_messages; i++)
5595 GInputMessage *msg = &messages[i];
5597 GError *msg_error = NULL;
5599 msg->flags = flags; /* in-out parameter */
5601 len = g_socket_receive_message_with_timeout (socket,
5605 msg->control_messages,
5606 (gint *) msg->num_control_messages,
5612 /* check if we've timed out or how much time to wait at most */
5615 gint64 elapsed = g_get_monotonic_time () - start_time;
5616 wait_timeout = MAX (timeout_us - elapsed, 1);
5620 msg->bytes_received = len;
5623 (g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK) ||
5624 g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)))
5626 g_clear_error (&msg_error);
5630 if (msg_error != NULL)
5632 g_propagate_error (error, msg_error);
5646 * g_socket_receive_message:
5647 * @socket: a #GSocket
5648 * @address: (out) (optional): a pointer to a #GSocketAddress
5650 * @vectors: (array length=num_vectors): an array of #GInputVector structs
5651 * @num_vectors: the number of elements in @vectors, or -1
5652 * @messages: (array length=num_messages) (out) (optional) (nullable): a pointer
5653 * which may be filled with an array of #GSocketControlMessages, or %NULL
5654 * @num_messages: (out): a pointer which will be filled with the number of
5655 * elements in @messages, or %NULL
5656 * @flags: (inout): a pointer to an int containing #GSocketMsgFlags flags,
5657 * which may additionally contain
5658 * [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5659 * @cancellable: a %GCancellable or %NULL
5660 * @error: a #GError pointer, or %NULL
5662 * Receive data from a socket. For receiving multiple messages, see
5663 * g_socket_receive_messages(); for easier use, see
5664 * g_socket_receive() and g_socket_receive_from().
5666 * If @address is non-%NULL then @address will be set equal to the
5667 * source address of the received packet.
5668 * @address is owned by the caller.
5670 * @vector must point to an array of #GInputVector structs and
5671 * @num_vectors must be the length of this array. These structs
5672 * describe the buffers that received data will be scattered into.
5673 * If @num_vectors is -1, then @vectors is assumed to be terminated
5674 * by a #GInputVector with a %NULL buffer pointer.
5676 * As a special case, if @num_vectors is 0 (in which case, @vectors
5677 * may of course be %NULL), then a single byte is received and
5678 * discarded. This is to facilitate the common practice of sending a
5679 * single '\0' byte for the purposes of transferring ancillary data.
5681 * @messages, if non-%NULL, will be set to point to a newly-allocated
5682 * array of #GSocketControlMessage instances or %NULL if no such
5683 * messages was received. These correspond to the control messages
5684 * received from the kernel, one #GSocketControlMessage per message
5685 * from the kernel. This array is %NULL-terminated and must be freed
5686 * by the caller using g_free() after calling g_object_unref() on each
5687 * element. If @messages is %NULL, any control messages received will
5690 * @num_messages, if non-%NULL, will be set to the number of control
5691 * messages received.
5693 * If both @messages and @num_messages are non-%NULL, then
5694 * @num_messages gives the number of #GSocketControlMessage instances
5695 * in @messages (ie: not including the %NULL terminator).
5697 * @flags is an in/out parameter. The commonly available arguments
5698 * for this are available in the #GSocketMsgFlags enum, but the
5699 * values there are the same as the system values, and the flags
5700 * are passed in as-is, so you can pass in system-specific flags too
5701 * (and g_socket_receive_message() may pass system-specific flags out).
5702 * Flags passed in to the parameter affect the receive operation; flags returned
5703 * out of it are relevant to the specific returned message.
5705 * As with g_socket_receive(), data may be discarded if @socket is
5706 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
5707 * provide enough buffer space to read a complete message. You can pass
5708 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
5709 * removing it from the receive queue, but there is no portable way to find
5710 * out the length of the message other than by reading it into a
5711 * sufficiently-large buffer.
5713 * If the socket is in blocking mode the call will block until there
5714 * is some data to receive, the connection is closed, or there is an
5715 * error. If there is no data available and the socket is in
5716 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
5717 * returned. To be notified when data is available, wait for the
5718 * %G_IO_IN condition.
5720 * On error -1 is returned and @error is set accordingly.
5722 * Returns: Number of bytes read, or 0 if the connection was closed by
5723 * the peer, or -1 on error
5728 g_socket_receive_message (GSocket *socket,
5729 GSocketAddress **address,
5730 GInputVector *vectors,
5732 GSocketControlMessage ***messages,
5735 GCancellable *cancellable,
5738 return g_socket_receive_message_with_timeout (socket, address, vectors,
5739 num_vectors, messages,
5740 num_messages, flags,
5741 socket->priv->blocking ? -1 : 0,
5742 cancellable, error);
5746 * g_socket_get_credentials:
5747 * @socket: a #GSocket.
5748 * @error: #GError for error reporting, or %NULL to ignore.
5750 * Returns the credentials of the foreign process connected to this
5751 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
5754 * If this operation isn't supported on the OS, the method fails with
5755 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
5756 * by reading the %SO_PEERCRED option on the underlying socket.
5758 * Other ways to obtain credentials from a foreign peer includes the
5759 * #GUnixCredentialsMessage type and
5760 * g_unix_connection_send_credentials() /
5761 * g_unix_connection_receive_credentials() functions.
5763 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
5764 * that must be freed with g_object_unref().
5769 g_socket_get_credentials (GSocket *socket,
5774 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
5775 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5779 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
5783 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
5784 socklen_t optlen = sizeof (native_creds_buf);
5786 if (getsockopt (socket->priv->fd,
5792 ret = g_credentials_new ();
5793 g_credentials_set_native (ret,
5794 G_CREDENTIALS_NATIVE_TYPE,
5798 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
5800 struct unpcbid cred;
5801 socklen_t optlen = sizeof (cred);
5803 if (getsockopt (socket->priv->fd,
5809 ret = g_credentials_new ();
5810 g_credentials_set_native (ret,
5811 G_CREDENTIALS_NATIVE_TYPE,
5815 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
5817 ucred_t *ucred = NULL;
5819 if (getpeerucred (socket->priv->fd, &ucred) == 0)
5821 ret = g_credentials_new ();
5822 g_credentials_set_native (ret,
5823 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
5829 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
5834 int errsv = get_socket_errno ();
5838 socket_io_error_from_errno (errsv),
5839 _("Unable to read socket credentials: %s"),
5840 socket_strerror (errsv));
5845 g_set_error_literal (error,
5847 G_IO_ERROR_NOT_SUPPORTED,
5848 _("g_socket_get_credentials not implemented for this OS"));
5855 * g_socket_get_option:
5856 * @socket: a #GSocket
5857 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5858 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5859 * @value: (out): return location for the option value
5860 * @error: #GError for error reporting, or %NULL to ignore.
5862 * Gets the value of an integer-valued option on @socket, as with
5863 * getsockopt(). (If you need to fetch a non-integer-valued option,
5864 * you will need to call getsockopt() directly.)
5866 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5867 * header pulls in system headers that will define most of the
5868 * standard/portable socket options. For unusual socket protocols or
5869 * platform-dependent options, you may need to include additional
5872 * Note that even for socket options that are a single byte in size,
5873 * @value is still a pointer to a #gint variable, not a #guchar;
5874 * g_socket_get_option() will handle the conversion internally.
5876 * Returns: success or failure. On failure, @error will be set, and
5877 * the system error value (`errno` or WSAGetLastError()) will still
5878 * be set to the result of the getsockopt() call.
5883 g_socket_get_option (GSocket *socket,
5891 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
5894 size = sizeof (gint);
5895 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
5897 int errsv = get_socket_errno ();
5899 g_set_error_literal (error,
5901 socket_io_error_from_errno (errsv),
5902 socket_strerror (errsv));
5904 /* Reset errno in case the caller wants to look at it */
5910 #if G_BYTE_ORDER == G_BIG_ENDIAN
5911 /* If the returned value is smaller than an int then we need to
5912 * slide it over into the low-order bytes of *value.
5914 if (size != sizeof (gint))
5915 *value = *value >> (8 * (sizeof (gint) - size));
5922 * g_socket_set_option:
5923 * @socket: a #GSocket
5924 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5925 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5926 * @value: the value to set the option to
5927 * @error: #GError for error reporting, or %NULL to ignore.
5929 * Sets the value of an integer-valued option on @socket, as with
5930 * setsockopt(). (If you need to set a non-integer-valued option,
5931 * you will need to call setsockopt() directly.)
5933 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5934 * header pulls in system headers that will define most of the
5935 * standard/portable socket options. For unusual socket protocols or
5936 * platform-dependent options, you may need to include additional
5939 * Returns: success or failure. On failure, @error will be set, and
5940 * the system error value (`errno` or WSAGetLastError()) will still
5941 * be set to the result of the setsockopt() call.
5946 g_socket_set_option (GSocket *socket,
5954 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
5956 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
5959 #if !defined (__linux__) && !defined (G_OS_WIN32)
5960 /* Linux and Windows let you set a single-byte value from an int,
5961 * but most other platforms don't.
5963 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
5965 #if G_BYTE_ORDER == G_BIG_ENDIAN
5966 value = value << (8 * (sizeof (gint) - 1));
5968 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
5973 errsv = get_socket_errno ();
5975 g_set_error_literal (error,
5977 socket_io_error_from_errno (errsv),
5978 socket_strerror (errsv));