1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2008 Christian Kellner, Samuel Cormier-Iijima
4 * Copyright © 2009 Codethink Limited
5 * Copyright © 2009 Red Hat, Inc
6 * Copyright © 2015 Collabora, Ltd.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General
19 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 * Authors: Christian Kellner <gicmo@gnome.org>
22 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
23 * Ryan Lortie <desrt@desrt.ca>
24 * Alexander Larsson <alexl@redhat.com>
25 * Philip Withnall <philip.withnall@collabora.co.uk>
33 #include "glib-unix.h"
44 # include <sys/ioctl.h>
47 #ifdef HAVE_SIOCGIFADDR
51 #ifdef HAVE_SYS_FILIO_H
52 # include <sys/filio.h>
59 #define GOBJECT_COMPILATION
60 #include "gobject/gtype-private.h" /* For _PRELUDE type define */
61 #undef GOBJECT_COMPILATION
62 #include "gcancellable.h"
63 #include "gdatagrambased.h"
64 #include "gioenumtypes.h"
65 #include "ginetaddress.h"
66 #include "ginetsocketaddress.h"
67 #include "ginitable.h"
71 #include "gnetworkingprivate.h"
72 #include "gsocketaddress.h"
73 #include "gsocketcontrolmessage.h"
74 #include "gcredentials.h"
75 #include "gcredentialsprivate.h"
77 #include "gioprivate.h"
80 /* For Windows XP runtime compatibility, but use the system's if_nametoindex() if available */
81 #include "gwin32networking.h"
86 * @short_description: Low-level socket object
88 * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
90 * A #GSocket is a low-level networking primitive. It is a more or less
91 * direct mapping of the BSD socket API in a portable GObject based API.
92 * It supports both the UNIX socket implementations and winsock2 on Windows.
94 * #GSocket is the platform independent base upon which the higher level
95 * network primitives are based. Applications are not typically meant to
96 * use it directly, but rather through classes like #GSocketClient,
97 * #GSocketService and #GSocketConnection. However there may be cases where
98 * direct use of #GSocket is useful.
100 * #GSocket implements the #GInitable interface, so if it is manually constructed
101 * by e.g. g_object_new() you must call g_initable_init() and check the
102 * results before using the object. This is done automatically in
103 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
106 * Sockets operate in two general modes, blocking or non-blocking. When
107 * in blocking mode all operations (which don’t take an explicit blocking
108 * parameter) block until the requested operation
109 * is finished or there is an error. In non-blocking mode all calls that
110 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
111 * To know when a call would successfully run you can call g_socket_condition_check(),
112 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
113 * attach it to a #GMainContext to get callbacks when I/O is possible.
114 * Note that all sockets are always set to non blocking mode in the system, and
115 * blocking mode is emulated in GSocket.
117 * When working in non-blocking mode applications should always be able to
118 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
119 * function said that I/O was possible. This can easily happen in case
120 * of a race condition in the application, but it can also happen for other
121 * reasons. For instance, on Windows a socket is always seen as writable
122 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
124 * #GSockets can be either connection oriented or datagram based.
125 * For connection oriented types you must first establish a connection by
126 * either connecting to an address or accepting a connection from another
127 * address. For connectionless socket types the target/source address is
128 * specified or received in each I/O operation.
130 * All socket file descriptors are set to be close-on-exec.
132 * Note that creating a #GSocket causes the signal %SIGPIPE to be
133 * ignored for the remainder of the program. If you are writing a
134 * command-line utility that uses #GSocket, you may need to take into
135 * account the fact that your program will not automatically be killed
136 * if it tries to write to %stdout after it has been closed.
138 * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
139 * a #GSocket concurrently from multiple threads, you must implement your own
145 static void g_socket_initable_iface_init (GInitableIface *iface);
146 static gboolean g_socket_initable_init (GInitable *initable,
147 GCancellable *cancellable,
150 static void g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface);
151 static gint g_socket_datagram_based_receive_messages (GDatagramBased *self,
152 GInputMessage *messages,
156 GCancellable *cancellable,
158 static gint g_socket_datagram_based_send_messages (GDatagramBased *self,
159 GOutputMessage *messages,
163 GCancellable *cancellable,
165 static GSource *g_socket_datagram_based_create_source (GDatagramBased *self,
166 GIOCondition condition,
167 GCancellable *cancellable);
168 static GIOCondition g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
169 GIOCondition condition);
170 static gboolean g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
171 GIOCondition condition,
173 GCancellable *cancellable,
176 static GSocketAddress *
177 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len);
180 g_socket_receive_message_with_timeout (GSocket *socket,
181 GSocketAddress **address,
182 GInputVector *vectors,
184 GSocketControlMessage ***messages,
188 GCancellable *cancellable,
191 g_socket_receive_messages_with_timeout (GSocket *socket,
192 GInputMessage *messages,
196 GCancellable *cancellable,
199 g_socket_send_messages_with_timeout (GSocket *socket,
200 GOutputMessage *messages,
204 GCancellable *cancellable,
222 PROP_MULTICAST_LOOPBACK,
226 /* Size of the receiver cache for g_socket_receive_from() */
227 #define RECV_ADDR_CACHE_SIZE 8
229 struct _GSocketPrivate
231 GSocketFamily family;
233 GSocketProtocol protocol;
237 GError *construct_error;
238 GSocketAddress *remote_address;
243 guint connected_read : 1;
244 guint connected_write : 1;
247 guint connect_pending : 1;
251 DWORD waiting_result;
255 GList *requested_conditions; /* list of requested GIOCondition * */
256 GMutex win32_source_lock;
257 GCond win32_source_cond;
261 GSocketAddress *addr;
262 struct sockaddr *native;
265 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
268 _G_DEFINE_TYPE_EXTENDED_WITH_PRELUDE (GSocket, g_socket, G_TYPE_OBJECT, 0,
269 /* Need a prelude for https://bugzilla.gnome.org/show_bug.cgi?id=674885 */
270 g_type_ensure (G_TYPE_SOCKET_FAMILY);
271 g_type_ensure (G_TYPE_SOCKET_TYPE);
272 g_type_ensure (G_TYPE_SOCKET_PROTOCOL);
273 g_type_ensure (G_TYPE_SOCKET_ADDRESS);
274 /* And networking init is appropriate for the prelude */
275 g_networking_init ();
276 , /* And now the regular type init code */
277 G_ADD_PRIVATE (GSocket)
278 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
279 g_socket_initable_iface_init);
280 G_IMPLEMENT_INTERFACE (G_TYPE_DATAGRAM_BASED,
281 g_socket_datagram_based_iface_init));
284 get_socket_errno (void)
289 return WSAGetLastError ();
294 socket_io_error_from_errno (int err)
297 return g_io_error_from_win32_error (err);
299 return g_io_error_from_errno (err);
304 socket_strerror (int err)
307 return g_strerror (err);
312 msg = g_win32_error_message (err);
314 msg_ret = g_intern_string (msg);
321 /* Wrapper around g_set_error() to avoid doing excess work */
322 #define socket_set_error_lazy(err, errsv, fmt) \
324 GError **__err = (err); \
325 int __errsv = (errsv); \
329 int __code = socket_io_error_from_errno (__errsv); \
330 const char *__strerr = socket_strerror (__errsv); \
332 if (__code == G_IO_ERROR_WOULD_BLOCK) \
333 g_set_error_literal (__err, G_IO_ERROR, __code, __strerr); \
335 g_set_error (__err, G_IO_ERROR, __code, fmt, __strerr); \
340 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
342 _win32_unset_event_mask (GSocket *socket, int mask)
344 g_mutex_lock (&socket->priv->win32_source_lock);
345 socket->priv->current_events &= ~mask;
346 socket->priv->current_errors &= ~mask;
347 g_mutex_unlock (&socket->priv->win32_source_lock);
350 #define win32_unset_event_mask(_socket, _mask)
353 /* Windows has broken prototypes... */
355 #define getsockopt(sockfd, level, optname, optval, optlen) \
356 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
357 #define setsockopt(sockfd, level, optname, optval, optlen) \
358 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
359 #define getsockname(sockfd, addr, addrlen) \
360 getsockname (sockfd, addr, (int *)addrlen)
361 #define getpeername(sockfd, addr, addrlen) \
362 getpeername (sockfd, addr, (int *)addrlen)
363 #define recv(sockfd, buf, len, flags) \
364 recv (sockfd, (gpointer)buf, len, flags)
368 address_to_string (GSocketAddress *address)
370 GString *ret = g_string_new ("");
372 if (G_IS_INET_SOCKET_ADDRESS (address))
374 GInetSocketAddress *isa = G_INET_SOCKET_ADDRESS (address);
375 GInetAddress *ia = g_inet_socket_address_get_address (isa);
376 GSocketFamily family = g_inet_address_get_family (ia);
379 /* Represent IPv6 addresses in URL style:
380 * ::1 port 12345 -> [::1]:12345 */
381 if (family == G_SOCKET_FAMILY_IPV6)
382 g_string_append_c (ret, '[');
384 tmp = g_inet_address_to_string (ia);
385 g_string_append (ret, tmp);
388 if (family == G_SOCKET_FAMILY_IPV6)
390 guint32 scope = g_inet_socket_address_get_scope_id (isa);
393 g_string_append_printf (ret, "%%%u", scope);
395 g_string_append_c (ret, ']');
398 g_string_append_c (ret, ':');
400 g_string_append_printf (ret, "%u", g_inet_socket_address_get_port (isa));
404 /* For unknown address types, just show the type */
405 g_string_append_printf (ret, "(%s)", G_OBJECT_TYPE_NAME (address));
408 return g_string_free (ret, FALSE);
412 check_socket (GSocket *socket,
415 if (!socket->priv->inited)
417 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
418 _("Invalid socket, not initialized"));
422 if (socket->priv->construct_error)
424 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
425 _("Invalid socket, initialization failed due to: %s"),
426 socket->priv->construct_error->message);
430 if (socket->priv->closed)
432 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
433 _("Socket is already closed"));
441 check_timeout (GSocket *socket,
444 if (socket->priv->timed_out)
446 socket->priv->timed_out = FALSE;
447 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
448 _("Socket I/O timed out"));
456 g_socket_details_from_fd (GSocket *socket)
459 struct sockaddr_storage storage;
467 fd = socket->priv->fd;
468 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
470 errsv = get_socket_errno ();
477 socket->priv->type = G_SOCKET_TYPE_STREAM;
481 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
485 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
489 socket->priv->type = G_SOCKET_TYPE_INVALID;
493 addrlen = sizeof address;
494 if (getsockname (fd, &address.sa, &addrlen) != 0)
496 errsv = get_socket_errno ();
502 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
503 sizeof address.storage.ss_family <= addrlen);
504 family = address.storage.ss_family;
508 /* On Solaris, this happens if the socket is not yet connected.
509 * But we can use SO_DOMAIN as a workaround there.
512 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
514 errsv = get_socket_errno ();
518 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
526 case G_SOCKET_FAMILY_IPV4:
527 case G_SOCKET_FAMILY_IPV6:
528 socket->priv->family = address.storage.ss_family;
529 switch (socket->priv->type)
531 case G_SOCKET_TYPE_STREAM:
532 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
535 case G_SOCKET_TYPE_DATAGRAM:
536 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
539 case G_SOCKET_TYPE_SEQPACKET:
540 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
548 case G_SOCKET_FAMILY_UNIX:
549 socket->priv->family = G_SOCKET_FAMILY_UNIX;
550 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
554 socket->priv->family = G_SOCKET_FAMILY_INVALID;
558 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
560 addrlen = sizeof address;
561 if (getpeername (fd, &address.sa, &addrlen) >= 0)
563 socket->priv->connected_read = TRUE;
564 socket->priv->connected_write = TRUE;
568 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
570 socket->priv->keepalive = !!value;
574 /* Can't read, maybe not supported, assume FALSE */
575 socket->priv->keepalive = FALSE;
581 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
582 socket_io_error_from_errno (errsv),
583 _("creating GSocket from fd: %s"),
584 socket_strerror (errsv));
587 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
589 g_socket (gint domain,
597 fd = socket (domain, type | SOCK_CLOEXEC, protocol);
602 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
603 if (fd < 0 && (errsv == EINVAL || errsv == EPROTOTYPE))
605 fd = socket (domain, type, protocol);
609 errsv = get_socket_errno ();
611 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
612 _("Unable to create socket: %s"), socket_strerror (errsv));
621 /* We always want to set close-on-exec to protect users. If you
622 need to so some weird inheritance to exec you can re-enable this
623 using lower level hacks with g_socket_get_fd(). */
624 flags = fcntl (fd, F_GETFD, 0);
626 (flags & FD_CLOEXEC) == 0)
629 fcntl (fd, F_SETFD, flags);
638 g_socket_create_socket (GSocketFamily family,
647 case G_SOCKET_TYPE_STREAM:
648 native_type = SOCK_STREAM;
651 case G_SOCKET_TYPE_DATAGRAM:
652 native_type = SOCK_DGRAM;
655 case G_SOCKET_TYPE_SEQPACKET:
656 native_type = SOCK_SEQPACKET;
660 g_assert_not_reached ();
665 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
666 _("Unable to create socket: %s"), _("Unknown family was specified"));
672 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
673 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
677 return g_socket (family, native_type, protocol, error);
681 g_socket_constructed (GObject *object)
683 GSocket *socket = G_SOCKET (object);
685 if (socket->priv->fd >= 0)
686 /* create socket->priv info from the fd */
687 g_socket_details_from_fd (socket);
690 /* create the fd from socket->priv info */
691 socket->priv->fd = g_socket_create_socket (socket->priv->family,
693 socket->priv->protocol,
694 &socket->priv->construct_error);
696 if (socket->priv->fd != -1)
699 GError *error = NULL;
704 /* Always use native nonblocking sockets, as Windows sets sockets to
705 * nonblocking automatically in certain operations. This way we make
706 * things work the same on all platforms.
709 if (!g_unix_set_fd_nonblocking (socket->priv->fd, TRUE, &error))
711 g_warning ("Error setting socket nonblocking: %s", error->message);
712 g_clear_error (&error);
717 if (ioctlsocket (socket->priv->fd, FIONBIO, &arg) == SOCKET_ERROR)
719 int errsv = get_socket_errno ();
720 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
725 /* See note about SIGPIPE below. */
726 g_socket_set_option (socket, SOL_SOCKET, SO_NOSIGPIPE, TRUE, NULL);
732 g_socket_get_property (GObject *object,
737 GSocket *socket = G_SOCKET (object);
738 GSocketAddress *address;
743 g_value_set_enum (value, socket->priv->family);
747 g_value_set_enum (value, socket->priv->type);
751 g_value_set_enum (value, socket->priv->protocol);
755 g_value_set_int (value, socket->priv->fd);
759 g_value_set_boolean (value, socket->priv->blocking);
762 case PROP_LISTEN_BACKLOG:
763 g_value_set_int (value, socket->priv->listen_backlog);
767 g_value_set_boolean (value, socket->priv->keepalive);
770 case PROP_LOCAL_ADDRESS:
771 address = g_socket_get_local_address (socket, NULL);
772 g_value_take_object (value, address);
775 case PROP_REMOTE_ADDRESS:
776 address = g_socket_get_remote_address (socket, NULL);
777 g_value_take_object (value, address);
781 g_value_set_uint (value, socket->priv->timeout);
785 g_value_set_uint (value, g_socket_get_ttl (socket));
789 g_value_set_boolean (value, g_socket_get_broadcast (socket));
792 case PROP_MULTICAST_LOOPBACK:
793 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
796 case PROP_MULTICAST_TTL:
797 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
801 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
806 g_socket_set_property (GObject *object,
811 GSocket *socket = G_SOCKET (object);
816 socket->priv->family = g_value_get_enum (value);
820 socket->priv->type = g_value_get_enum (value);
824 socket->priv->protocol = g_value_get_enum (value);
828 socket->priv->fd = g_value_get_int (value);
832 g_socket_set_blocking (socket, g_value_get_boolean (value));
835 case PROP_LISTEN_BACKLOG:
836 g_socket_set_listen_backlog (socket, g_value_get_int (value));
840 g_socket_set_keepalive (socket, g_value_get_boolean (value));
844 g_socket_set_timeout (socket, g_value_get_uint (value));
848 g_socket_set_ttl (socket, g_value_get_uint (value));
852 g_socket_set_broadcast (socket, g_value_get_boolean (value));
855 case PROP_MULTICAST_LOOPBACK:
856 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
859 case PROP_MULTICAST_TTL:
860 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
864 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
869 g_socket_finalize (GObject *object)
871 GSocket *socket = G_SOCKET (object);
874 g_clear_error (&socket->priv->construct_error);
876 if (socket->priv->fd != -1 &&
877 !socket->priv->closed)
878 g_socket_close (socket, NULL);
880 if (socket->priv->remote_address)
881 g_object_unref (socket->priv->remote_address);
884 if (socket->priv->event != WSA_INVALID_EVENT)
886 WSACloseEvent (socket->priv->event);
887 socket->priv->event = WSA_INVALID_EVENT;
890 g_assert (socket->priv->requested_conditions == NULL);
891 g_mutex_clear (&socket->priv->win32_source_lock);
892 g_cond_clear (&socket->priv->win32_source_cond);
895 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
897 if (socket->priv->recv_addr_cache[i].addr)
899 g_object_unref (socket->priv->recv_addr_cache[i].addr);
900 g_free (socket->priv->recv_addr_cache[i].native);
904 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
905 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
909 g_socket_class_init (GSocketClass *klass)
911 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
914 /* There is no portable, thread-safe way to avoid having the process
915 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
916 * forced to simply ignore the signal process-wide.
918 * Even if we ignore it though, gdb will still stop if the app
919 * receives a SIGPIPE, which can be confusing and annoying. So when
920 * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
921 * prevent the signal from occurring at all.
923 signal (SIGPIPE, SIG_IGN);
926 gobject_class->finalize = g_socket_finalize;
927 gobject_class->constructed = g_socket_constructed;
928 gobject_class->set_property = g_socket_set_property;
929 gobject_class->get_property = g_socket_get_property;
931 g_object_class_install_property (gobject_class, PROP_FAMILY,
932 g_param_spec_enum ("family",
934 P_("The sockets address family"),
935 G_TYPE_SOCKET_FAMILY,
936 G_SOCKET_FAMILY_INVALID,
937 G_PARAM_CONSTRUCT_ONLY |
939 G_PARAM_STATIC_STRINGS));
941 g_object_class_install_property (gobject_class, PROP_TYPE,
942 g_param_spec_enum ("type",
944 P_("The sockets type"),
946 G_SOCKET_TYPE_STREAM,
947 G_PARAM_CONSTRUCT_ONLY |
949 G_PARAM_STATIC_STRINGS));
951 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
952 g_param_spec_enum ("protocol",
953 P_("Socket protocol"),
954 P_("The id of the protocol to use, or -1 for unknown"),
955 G_TYPE_SOCKET_PROTOCOL,
956 G_SOCKET_PROTOCOL_UNKNOWN,
957 G_PARAM_CONSTRUCT_ONLY |
959 G_PARAM_STATIC_STRINGS));
961 g_object_class_install_property (gobject_class, PROP_FD,
962 g_param_spec_int ("fd",
963 P_("File descriptor"),
964 P_("The sockets file descriptor"),
968 G_PARAM_CONSTRUCT_ONLY |
970 G_PARAM_STATIC_STRINGS));
972 g_object_class_install_property (gobject_class, PROP_BLOCKING,
973 g_param_spec_boolean ("blocking",
975 P_("Whether or not I/O on this socket is blocking"),
978 G_PARAM_STATIC_STRINGS));
980 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
981 g_param_spec_int ("listen-backlog",
982 P_("Listen backlog"),
983 P_("Outstanding connections in the listen queue"),
988 G_PARAM_STATIC_STRINGS));
990 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
991 g_param_spec_boolean ("keepalive",
992 P_("Keep connection alive"),
993 P_("Keep connection alive by sending periodic pings"),
996 G_PARAM_STATIC_STRINGS));
998 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
999 g_param_spec_object ("local-address",
1000 P_("Local address"),
1001 P_("The local address the socket is bound to"),
1002 G_TYPE_SOCKET_ADDRESS,
1004 G_PARAM_STATIC_STRINGS));
1006 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
1007 g_param_spec_object ("remote-address",
1008 P_("Remote address"),
1009 P_("The remote address the socket is connected to"),
1010 G_TYPE_SOCKET_ADDRESS,
1012 G_PARAM_STATIC_STRINGS));
1017 * The timeout in seconds on socket I/O
1021 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
1022 g_param_spec_uint ("timeout",
1024 P_("The timeout in seconds on socket I/O"),
1029 G_PARAM_STATIC_STRINGS));
1032 * GSocket:broadcast:
1034 * Whether the socket should allow sending to broadcast addresses.
1038 g_object_class_install_property (gobject_class, PROP_BROADCAST,
1039 g_param_spec_boolean ("broadcast",
1041 P_("Whether to allow sending to broadcast addresses"),
1044 G_PARAM_STATIC_STRINGS));
1049 * Time-to-live for outgoing unicast packets
1053 g_object_class_install_property (gobject_class, PROP_TTL,
1054 g_param_spec_uint ("ttl",
1056 P_("Time-to-live of outgoing unicast packets"),
1059 G_PARAM_STATIC_STRINGS));
1062 * GSocket:multicast-loopback:
1064 * Whether outgoing multicast packets loop back to the local host.
1068 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
1069 g_param_spec_boolean ("multicast-loopback",
1070 P_("Multicast loopback"),
1071 P_("Whether outgoing multicast packets loop back to the local host"),
1074 G_PARAM_STATIC_STRINGS));
1077 * GSocket:multicast-ttl:
1079 * Time-to-live out outgoing multicast packets
1083 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
1084 g_param_spec_uint ("multicast-ttl",
1085 P_("Multicast TTL"),
1086 P_("Time-to-live of outgoing multicast packets"),
1089 G_PARAM_STATIC_STRINGS));
1093 g_socket_initable_iface_init (GInitableIface *iface)
1095 iface->init = g_socket_initable_init;
1099 g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface)
1101 iface->receive_messages = g_socket_datagram_based_receive_messages;
1102 iface->send_messages = g_socket_datagram_based_send_messages;
1103 iface->create_source = g_socket_datagram_based_create_source;
1104 iface->condition_check = g_socket_datagram_based_condition_check;
1105 iface->condition_wait = g_socket_datagram_based_condition_wait;
1109 g_socket_init (GSocket *socket)
1111 socket->priv = g_socket_get_instance_private (socket);
1113 socket->priv->fd = -1;
1114 socket->priv->blocking = TRUE;
1115 socket->priv->listen_backlog = 10;
1116 socket->priv->construct_error = NULL;
1118 socket->priv->event = WSA_INVALID_EVENT;
1119 g_mutex_init (&socket->priv->win32_source_lock);
1120 g_cond_init (&socket->priv->win32_source_cond);
1125 g_socket_initable_init (GInitable *initable,
1126 GCancellable *cancellable,
1131 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
1133 socket = G_SOCKET (initable);
1135 if (cancellable != NULL)
1137 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1138 _("Cancellable initialization not supported"));
1142 socket->priv->inited = TRUE;
1144 if (socket->priv->construct_error)
1147 *error = g_error_copy (socket->priv->construct_error);
1156 check_datagram_based (GDatagramBased *self,
1159 switch (g_socket_get_socket_type (G_SOCKET (self)))
1161 case G_SOCKET_TYPE_INVALID:
1162 case G_SOCKET_TYPE_STREAM:
1163 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1164 _("Cannot use datagram operations on a non-datagram "
1167 case G_SOCKET_TYPE_DATAGRAM:
1168 case G_SOCKET_TYPE_SEQPACKET:
1173 /* Due to us sharing #GSocketSource with the #GSocket implementation, it is
1174 * pretty tricky to split out #GSocket:timeout so that it does not affect
1175 * #GDatagramBased operations (but still affects #GSocket operations). It is
1176 * not worth that effort — just disallow it and require the user to specify
1177 * timeouts on a per-operation basis. */
1178 if (g_socket_get_timeout (G_SOCKET (self)) != 0)
1180 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1181 _("Cannot use datagram operations on a socket with a "
1190 g_socket_datagram_based_receive_messages (GDatagramBased *self,
1191 GInputMessage *messages,
1195 GCancellable *cancellable,
1198 if (!check_datagram_based (self, error))
1201 return g_socket_receive_messages_with_timeout (G_SOCKET (self), messages,
1202 num_messages, flags, timeout_us,
1203 cancellable, error);
1207 g_socket_datagram_based_send_messages (GDatagramBased *self,
1208 GOutputMessage *messages,
1212 GCancellable *cancellable,
1215 if (!check_datagram_based (self, error))
1218 return g_socket_send_messages_with_timeout (G_SOCKET (self), messages,
1219 num_messages, flags, timeout_us,
1220 cancellable, error);
1224 g_socket_datagram_based_create_source (GDatagramBased *self,
1225 GIOCondition condition,
1226 GCancellable *cancellable)
1228 if (!check_datagram_based (self, NULL))
1231 return g_socket_create_source (G_SOCKET (self), condition, cancellable);
1235 g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
1236 GIOCondition condition)
1238 if (!check_datagram_based (datagram_based, NULL))
1241 return g_socket_condition_check (G_SOCKET (datagram_based), condition);
1245 g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
1246 GIOCondition condition,
1248 GCancellable *cancellable,
1251 if (!check_datagram_based (datagram_based, error))
1254 return g_socket_condition_timed_wait (G_SOCKET (datagram_based), condition,
1255 timeout_us, cancellable, error);
1260 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1261 * @type: the socket type to use.
1262 * @protocol: the id of the protocol to use, or 0 for default.
1263 * @error: #GError for error reporting, or %NULL to ignore.
1265 * Creates a new #GSocket with the defined family, type and protocol.
1266 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1267 * for the family and type is used.
1269 * The @protocol is a family and type specific int that specifies what
1270 * kind of protocol to use. #GSocketProtocol lists several common ones.
1271 * Many families only support one protocol, and use 0 for this, others
1272 * support several and using 0 means to use the default protocol for
1273 * the family and type.
1275 * The protocol id is passed directly to the operating
1276 * system, so you can use protocols not listed in #GSocketProtocol if you
1277 * know the protocol number used for it.
1279 * Returns: a #GSocket or %NULL on error.
1280 * Free the returned object with g_object_unref().
1285 g_socket_new (GSocketFamily family,
1287 GSocketProtocol protocol,
1290 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1294 "protocol", protocol,
1299 * g_socket_new_from_fd:
1300 * @fd: a native socket file descriptor.
1301 * @error: #GError for error reporting, or %NULL to ignore.
1303 * Creates a new #GSocket from a native file descriptor
1304 * or winsock SOCKET handle.
1306 * This reads all the settings from the file descriptor so that
1307 * all properties should work. Note that the file descriptor
1308 * will be set to non-blocking mode, independent on the blocking
1309 * mode of the #GSocket.
1311 * On success, the returned #GSocket takes ownership of @fd. On failure, the
1312 * caller must close @fd themselves.
1314 * Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
1315 * descriptor. Instead, a GError will be set with code %G_IO_ERROR_FAILED
1317 * Returns: a #GSocket or %NULL on error.
1318 * Free the returned object with g_object_unref().
1323 g_socket_new_from_fd (gint fd,
1326 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1333 * g_socket_set_blocking:
1334 * @socket: a #GSocket.
1335 * @blocking: Whether to use blocking I/O or not.
1337 * Sets the blocking mode of the socket. In blocking mode
1338 * all operations (which don’t take an explicit blocking parameter) block until
1339 * they succeed or there is an error. In
1340 * non-blocking mode all functions return results immediately or
1341 * with a %G_IO_ERROR_WOULD_BLOCK error.
1343 * All sockets are created in blocking mode. However, note that the
1344 * platform level socket is always non-blocking, and blocking mode
1345 * is a GSocket level feature.
1350 g_socket_set_blocking (GSocket *socket,
1353 g_return_if_fail (G_IS_SOCKET (socket));
1355 blocking = !!blocking;
1357 if (socket->priv->blocking == blocking)
1360 socket->priv->blocking = blocking;
1361 g_object_notify (G_OBJECT (socket), "blocking");
1365 * g_socket_get_blocking:
1366 * @socket: a #GSocket.
1368 * Gets the blocking mode of the socket. For details on blocking I/O,
1369 * see g_socket_set_blocking().
1371 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1376 g_socket_get_blocking (GSocket *socket)
1378 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1380 return socket->priv->blocking;
1384 * g_socket_set_keepalive:
1385 * @socket: a #GSocket.
1386 * @keepalive: Value for the keepalive flag
1388 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1389 * this flag is set on a socket, the system will attempt to verify that the
1390 * remote socket endpoint is still present if a sufficiently long period of
1391 * time passes with no data being exchanged. If the system is unable to
1392 * verify the presence of the remote endpoint, it will automatically close
1395 * This option is only functional on certain kinds of sockets. (Notably,
1396 * %G_SOCKET_PROTOCOL_TCP sockets.)
1398 * The exact time between pings is system- and protocol-dependent, but will
1399 * normally be at least two hours. Most commonly, you would set this flag
1400 * on a server socket if you want to allow clients to remain idle for long
1401 * periods of time, but also want to ensure that connections are eventually
1402 * garbage-collected if clients crash or become unreachable.
1407 g_socket_set_keepalive (GSocket *socket,
1410 GError *error = NULL;
1412 g_return_if_fail (G_IS_SOCKET (socket));
1414 keepalive = !!keepalive;
1415 if (socket->priv->keepalive == keepalive)
1418 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1421 g_warning ("error setting keepalive: %s", error->message);
1422 g_error_free (error);
1426 socket->priv->keepalive = keepalive;
1427 g_object_notify (G_OBJECT (socket), "keepalive");
1431 * g_socket_get_keepalive:
1432 * @socket: a #GSocket.
1434 * Gets the keepalive mode of the socket. For details on this,
1435 * see g_socket_set_keepalive().
1437 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1442 g_socket_get_keepalive (GSocket *socket)
1444 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1446 return socket->priv->keepalive;
1450 * g_socket_get_listen_backlog:
1451 * @socket: a #GSocket.
1453 * Gets the listen backlog setting of the socket. For details on this,
1454 * see g_socket_set_listen_backlog().
1456 * Returns: the maximum number of pending connections.
1461 g_socket_get_listen_backlog (GSocket *socket)
1463 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1465 return socket->priv->listen_backlog;
1469 * g_socket_set_listen_backlog:
1470 * @socket: a #GSocket.
1471 * @backlog: the maximum number of pending connections.
1473 * Sets the maximum number of outstanding connections allowed
1474 * when listening on this socket. If more clients than this are
1475 * connecting to the socket and the application is not handling them
1476 * on time then the new connections will be refused.
1478 * Note that this must be called before g_socket_listen() and has no
1479 * effect if called after that.
1484 g_socket_set_listen_backlog (GSocket *socket,
1487 g_return_if_fail (G_IS_SOCKET (socket));
1488 g_return_if_fail (!socket->priv->listening);
1490 if (backlog != socket->priv->listen_backlog)
1492 socket->priv->listen_backlog = backlog;
1493 g_object_notify (G_OBJECT (socket), "listen-backlog");
1498 * g_socket_get_timeout:
1499 * @socket: a #GSocket.
1501 * Gets the timeout setting of the socket. For details on this, see
1502 * g_socket_set_timeout().
1504 * Returns: the timeout in seconds
1509 g_socket_get_timeout (GSocket *socket)
1511 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1513 return socket->priv->timeout;
1517 * g_socket_set_timeout:
1518 * @socket: a #GSocket.
1519 * @timeout: the timeout for @socket, in seconds, or 0 for none
1521 * Sets the time in seconds after which I/O operations on @socket will
1522 * time out if they have not yet completed.
1524 * On a blocking socket, this means that any blocking #GSocket
1525 * operation will time out after @timeout seconds of inactivity,
1526 * returning %G_IO_ERROR_TIMED_OUT.
1528 * On a non-blocking socket, calls to g_socket_condition_wait() will
1529 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1530 * created with g_socket_create_source() will trigger after
1531 * @timeout seconds of inactivity, with the requested condition
1532 * set, at which point calling g_socket_receive(), g_socket_send(),
1533 * g_socket_check_connect_result(), etc, will fail with
1534 * %G_IO_ERROR_TIMED_OUT.
1536 * If @timeout is 0 (the default), operations will never time out
1539 * Note that if an I/O operation is interrupted by a signal, this may
1540 * cause the timeout to be reset.
1545 g_socket_set_timeout (GSocket *socket,
1548 g_return_if_fail (G_IS_SOCKET (socket));
1550 if (timeout != socket->priv->timeout)
1552 socket->priv->timeout = timeout;
1553 g_object_notify (G_OBJECT (socket), "timeout");
1559 * @socket: a #GSocket.
1561 * Gets the unicast time-to-live setting on @socket; see
1562 * g_socket_set_ttl() for more details.
1564 * Returns: the time-to-live setting on @socket
1569 g_socket_get_ttl (GSocket *socket)
1571 GError *error = NULL;
1574 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1576 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1578 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1581 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1583 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1587 g_return_val_if_reached (0);
1591 g_warning ("error getting unicast ttl: %s", error->message);
1592 g_error_free (error);
1601 * @socket: a #GSocket.
1602 * @ttl: the time-to-live value for all unicast packets on @socket
1604 * Sets the time-to-live for outgoing unicast packets on @socket.
1605 * By default the platform-specific default value is used.
1610 g_socket_set_ttl (GSocket *socket,
1613 GError *error = NULL;
1615 g_return_if_fail (G_IS_SOCKET (socket));
1617 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1619 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1622 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1624 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1626 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1630 g_return_if_reached ();
1634 g_warning ("error setting unicast ttl: %s", error->message);
1635 g_error_free (error);
1639 g_object_notify (G_OBJECT (socket), "ttl");
1643 * g_socket_get_broadcast:
1644 * @socket: a #GSocket.
1646 * Gets the broadcast setting on @socket; if %TRUE,
1647 * it is possible to send packets to broadcast
1650 * Returns: the broadcast setting on @socket
1655 g_socket_get_broadcast (GSocket *socket)
1657 GError *error = NULL;
1660 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1662 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1665 g_warning ("error getting broadcast: %s", error->message);
1666 g_error_free (error);
1674 * g_socket_set_broadcast:
1675 * @socket: a #GSocket.
1676 * @broadcast: whether @socket should allow sending to broadcast
1679 * Sets whether @socket should allow sending to broadcast addresses.
1680 * This is %FALSE by default.
1685 g_socket_set_broadcast (GSocket *socket,
1688 GError *error = NULL;
1690 g_return_if_fail (G_IS_SOCKET (socket));
1692 broadcast = !!broadcast;
1694 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1697 g_warning ("error setting broadcast: %s", error->message);
1698 g_error_free (error);
1702 g_object_notify (G_OBJECT (socket), "broadcast");
1706 * g_socket_get_multicast_loopback:
1707 * @socket: a #GSocket.
1709 * Gets the multicast loopback setting on @socket; if %TRUE (the
1710 * default), outgoing multicast packets will be looped back to
1711 * multicast listeners on the same host.
1713 * Returns: the multicast loopback setting on @socket
1718 g_socket_get_multicast_loopback (GSocket *socket)
1720 GError *error = NULL;
1723 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1725 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1727 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1730 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1732 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1736 g_return_val_if_reached (FALSE);
1740 g_warning ("error getting multicast loopback: %s", error->message);
1741 g_error_free (error);
1749 * g_socket_set_multicast_loopback:
1750 * @socket: a #GSocket.
1751 * @loopback: whether @socket should receive messages sent to its
1752 * multicast groups from the local host
1754 * Sets whether outgoing multicast packets will be received by sockets
1755 * listening on that multicast address on the same host. This is %TRUE
1761 g_socket_set_multicast_loopback (GSocket *socket,
1764 GError *error = NULL;
1766 g_return_if_fail (G_IS_SOCKET (socket));
1768 loopback = !!loopback;
1770 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1772 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1775 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1777 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1779 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1783 g_return_if_reached ();
1787 g_warning ("error setting multicast loopback: %s", error->message);
1788 g_error_free (error);
1792 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1796 * g_socket_get_multicast_ttl:
1797 * @socket: a #GSocket.
1799 * Gets the multicast time-to-live setting on @socket; see
1800 * g_socket_set_multicast_ttl() for more details.
1802 * Returns: the multicast time-to-live setting on @socket
1807 g_socket_get_multicast_ttl (GSocket *socket)
1809 GError *error = NULL;
1812 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1814 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1816 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1819 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1821 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1825 g_return_val_if_reached (FALSE);
1829 g_warning ("error getting multicast ttl: %s", error->message);
1830 g_error_free (error);
1838 * g_socket_set_multicast_ttl:
1839 * @socket: a #GSocket.
1840 * @ttl: the time-to-live value for all multicast datagrams on @socket
1842 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1843 * By default, this is 1, meaning that multicast packets will not leave
1844 * the local network.
1849 g_socket_set_multicast_ttl (GSocket *socket,
1852 GError *error = NULL;
1854 g_return_if_fail (G_IS_SOCKET (socket));
1856 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1858 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1861 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1863 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1865 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1869 g_return_if_reached ();
1873 g_warning ("error setting multicast ttl: %s", error->message);
1874 g_error_free (error);
1878 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1882 * g_socket_get_family:
1883 * @socket: a #GSocket.
1885 * Gets the socket family of the socket.
1887 * Returns: a #GSocketFamily
1892 g_socket_get_family (GSocket *socket)
1894 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1896 return socket->priv->family;
1900 * g_socket_get_socket_type:
1901 * @socket: a #GSocket.
1903 * Gets the socket type of the socket.
1905 * Returns: a #GSocketType
1910 g_socket_get_socket_type (GSocket *socket)
1912 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1914 return socket->priv->type;
1918 * g_socket_get_protocol:
1919 * @socket: a #GSocket.
1921 * Gets the socket protocol id the socket was created with.
1922 * In case the protocol is unknown, -1 is returned.
1924 * Returns: a protocol id, or -1 if unknown
1929 g_socket_get_protocol (GSocket *socket)
1931 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1933 return socket->priv->protocol;
1938 * @socket: a #GSocket.
1940 * Returns the underlying OS socket object. On unix this
1941 * is a socket file descriptor, and on Windows this is
1942 * a Winsock2 SOCKET handle. This may be useful for
1943 * doing platform specific or otherwise unusual operations
1946 * Returns: the file descriptor of the socket.
1951 g_socket_get_fd (GSocket *socket)
1953 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1955 return socket->priv->fd;
1959 * g_socket_get_local_address:
1960 * @socket: a #GSocket.
1961 * @error: #GError for error reporting, or %NULL to ignore.
1963 * Try to get the local address of a bound socket. This is only
1964 * useful if the socket has been bound to a local address,
1965 * either explicitly or implicitly when connecting.
1967 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1968 * Free the returned object with g_object_unref().
1973 g_socket_get_local_address (GSocket *socket,
1977 struct sockaddr_storage storage;
1980 guint len = sizeof (buffer);
1982 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1984 if (getsockname (socket->priv->fd, &buffer.sa, &len) < 0)
1986 int errsv = get_socket_errno ();
1987 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1988 _("could not get local address: %s"), socket_strerror (errsv));
1992 return g_socket_address_new_from_native (&buffer.storage, len);
1996 * g_socket_get_remote_address:
1997 * @socket: a #GSocket.
1998 * @error: #GError for error reporting, or %NULL to ignore.
2000 * Try to get the remote address of a connected socket. This is only
2001 * useful for connection oriented sockets that have been connected.
2003 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
2004 * Free the returned object with g_object_unref().
2009 g_socket_get_remote_address (GSocket *socket,
2013 struct sockaddr_storage storage;
2016 guint len = sizeof (buffer);
2018 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2020 if (socket->priv->connect_pending)
2022 if (!g_socket_check_connect_result (socket, error))
2025 socket->priv->connect_pending = FALSE;
2028 if (!socket->priv->remote_address)
2030 if (getpeername (socket->priv->fd, &buffer.sa, &len) < 0)
2032 int errsv = get_socket_errno ();
2033 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2034 _("could not get remote address: %s"), socket_strerror (errsv));
2038 socket->priv->remote_address = g_socket_address_new_from_native (&buffer.storage, len);
2041 return g_object_ref (socket->priv->remote_address);
2045 * g_socket_is_connected:
2046 * @socket: a #GSocket.
2048 * Check whether the socket is connected. This is only useful for
2049 * connection-oriented sockets.
2051 * If using g_socket_shutdown(), this function will return %TRUE until the
2052 * socket has been shut down for reading and writing. If you do a non-blocking
2053 * connect, this function will not return %TRUE until after you call
2054 * g_socket_check_connect_result().
2056 * Returns: %TRUE if socket is connected, %FALSE otherwise.
2061 g_socket_is_connected (GSocket *socket)
2063 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2065 return (socket->priv->connected_read || socket->priv->connected_write);
2070 * @socket: a #GSocket.
2071 * @error: #GError for error reporting, or %NULL to ignore.
2073 * Marks the socket as a server socket, i.e. a socket that is used
2074 * to accept incoming requests using g_socket_accept().
2076 * Before calling this the socket must be bound to a local address using
2079 * To set the maximum amount of outstanding clients, use
2080 * g_socket_set_listen_backlog().
2082 * Returns: %TRUE on success, %FALSE on error.
2087 g_socket_listen (GSocket *socket,
2090 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2092 if (!check_socket (socket, error))
2095 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
2097 int errsv = get_socket_errno ();
2099 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2100 _("could not listen: %s"), socket_strerror (errsv));
2104 socket->priv->listening = TRUE;
2111 * @socket: a #GSocket.
2112 * @address: a #GSocketAddress specifying the local address.
2113 * @allow_reuse: whether to allow reusing this address
2114 * @error: #GError for error reporting, or %NULL to ignore.
2116 * When a socket is created it is attached to an address family, but it
2117 * doesn't have an address in this family. g_socket_bind() assigns the
2118 * address (sometimes called name) of the socket.
2120 * It is generally required to bind to a local address before you can
2121 * receive connections. (See g_socket_listen() and g_socket_accept() ).
2122 * In certain situations, you may also want to bind a socket that will be
2123 * used to initiate connections, though this is not normally required.
2125 * If @socket is a TCP socket, then @allow_reuse controls the setting
2126 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
2127 * server sockets (sockets that you will eventually call
2128 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
2129 * set this flag on a server socket may cause g_socket_bind() to return
2130 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
2131 * immediately restarted.)
2133 * If @socket is a UDP socket, then @allow_reuse determines whether or
2134 * not other UDP sockets can be bound to the same address at the same
2135 * time. In particular, you can have several UDP sockets bound to the
2136 * same address, and they will all receive all of the multicast and
2137 * broadcast packets sent to that address. (The behavior of unicast
2138 * UDP packets to an address with multiple listeners is not defined.)
2140 * Returns: %TRUE on success, %FALSE on error.
2145 g_socket_bind (GSocket *socket,
2146 GSocketAddress *address,
2147 gboolean reuse_address,
2151 struct sockaddr_storage storage;
2154 gboolean so_reuseaddr;
2156 gboolean so_reuseport;
2159 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2161 if (!check_socket (socket, error))
2164 if (!g_socket_address_to_native (address, &addr.storage, sizeof addr, error))
2167 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
2168 * sockets, but has nasty side effects we don't want for TCP
2171 * On other platforms, we set SO_REUSEPORT, if it exists, for
2172 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
2173 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
2174 * the desired semantics on UDP (as it does on Linux, although
2175 * Linux has SO_REUSEPORT too as of 3.9).
2179 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2181 so_reuseaddr = !!reuse_address;
2185 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2188 /* Ignore errors here, the only likely error is "not supported", and
2189 * this is a "best effort" thing mainly.
2191 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
2193 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
2196 if (bind (socket->priv->fd, &addr.sa,
2197 g_socket_address_get_native_size (address)) < 0)
2199 int errsv = get_socket_errno ();
2200 gchar *address_string = address_to_string (address);
2203 G_IO_ERROR, socket_io_error_from_errno (errsv),
2204 _("Error binding to address %s: %s"),
2205 address_string, socket_strerror (errsv));
2206 g_free (address_string);
2215 g_socket_w32_get_adapter_ipv4_addr (const gchar *name_or_ip)
2217 ULONG bufsize = 15000; /* MS-recommended initial bufsize */
2218 DWORD ret = ERROR_BUFFER_OVERFLOW;
2219 unsigned int malloc_iterations = 0;
2220 PIP_ADAPTER_ADDRESSES addr_buf = NULL, eth_adapter;
2221 wchar_t *wchar_name_or_ip = NULL;
2223 NET_IFINDEX if_index;
2226 * For Windows OS only - return adapter IPv4 address in network byte order.
2228 * Input string can be either friendly name of adapter, IP address of adapter,
2229 * indextoname, or fullname of adapter.
2231 * 192.168.1.109 ===> IP address given directly,
2232 * convert directly with inet_addr() function
2233 * Wi-Fi ===> Adapter friendly name "Wi-Fi",
2234 * scan with GetAdapterAddresses and adapter->FriendlyName
2235 * ethernet_32774 ===> Adapter name as returned by if_indextoname
2236 * {33E8F5CD-BAEA-4214-BE13-B79AB8080CAB} ===> Adaptername,
2237 * as returned in GetAdapterAddresses and adapter->AdapterName
2240 /* Step 1: Check if string is an IP address: */
2241 ip_result = inet_addr (name_or_ip);
2242 if (ip_result != INADDR_NONE)
2243 return ip_result; /* Success, IP address string was given directly */
2246 * Step 2: Check if name represents a valid Interface index (e.g. ethernet_75521)
2247 * function if_nametoindex will return >=1 if a valid index, or 0=no match
2248 * valid index will be used later in GetAdaptersAddress loop for lookup of adapter IP address
2250 if_index = if_nametoindex (name_or_ip);
2252 /* Step 3: Prepare wchar string for friendly name comparision */
2255 size_t if_name_len = strlen (name_or_ip);
2256 if (if_name_len >= MAX_ADAPTER_NAME_LENGTH + 4)
2258 /* Name-check only needed if index=0... */
2259 wchar_name_or_ip = (wchar_t *) g_try_malloc ((if_name_len + 1) * sizeof(wchar_t));
2260 if (wchar_name_or_ip)
2261 mbstowcs (wchar_name_or_ip, name_or_ip, if_name_len + 1);
2262 /* NOTE: Even if malloc fails here, some comparisions can still be done later... so no exit here! */
2266 * Step 4: Allocate memory and get adapter addresses.
2267 * Buffer allocation loop recommended by MS, since size can be dynamic
2268 * https://docs.microsoft.com/en-us/windows/desktop/api/iphlpapi/nf-iphlpapi-getadaptersaddresses
2270 #define MAX_ALLOC_ITERATIONS 3
2273 malloc_iterations++;
2274 addr_buf = (PIP_ADAPTER_ADDRESSES) g_try_realloc (addr_buf, bufsize);
2276 ret = GetAdaptersAddresses (AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, addr_buf, &bufsize);
2279 ret == ERROR_BUFFER_OVERFLOW &&
2280 malloc_iterations < MAX_ALLOC_ITERATIONS);
2281 #undef MAX_ALLOC_ITERATIONS
2283 if (addr_buf == 0 || ret != NO_ERROR)
2286 g_free (wchar_name_or_ip);
2290 /* Step 5: Loop through adapters and check match for index or name */
2291 for (eth_adapter = addr_buf; eth_adapter != NULL; eth_adapter = eth_adapter->Next)
2293 /* Check if match for interface index/name: */
2294 gboolean any_match = (if_index > 0) && (eth_adapter->IfIndex == if_index);
2296 /* Check if match for friendly name - but only if NO if_index! */
2297 if (!any_match && if_index == 0 && eth_adapter->FriendlyName &&
2298 eth_adapter->FriendlyName[0] != 0 && wchar_name_or_ip != NULL)
2299 any_match = (_wcsicmp (eth_adapter->FriendlyName, wchar_name_or_ip) == 0);
2301 /* Check if match for adapter low level name - but only if NO if_index: */
2302 if (!any_match && if_index == 0 && eth_adapter->AdapterName &&
2303 eth_adapter->AdapterName[0] != 0)
2304 any_match = (stricmp (eth_adapter->AdapterName, name_or_ip) == 0);
2308 /* We have match for this adapter, lets get its local unicast IP address! */
2309 PIP_ADAPTER_UNICAST_ADDRESS uni_addr;
2310 for (uni_addr = eth_adapter->FirstUnicastAddress;
2311 uni_addr != NULL; uni_addr = uni_addr->Next)
2313 if (uni_addr->Address.lpSockaddr->sa_family == AF_INET)
2315 ip_result = ((PSOCKADDR_IN) uni_addr->Address.lpSockaddr)->sin_addr.S_un.S_addr;
2316 break; /* finished, exit unicast addr loop */
2323 g_free (wchar_name_or_ip);
2330 g_socket_multicast_group_operation (GSocket *socket,
2331 GInetAddress *group,
2332 gboolean source_specific,
2334 gboolean join_group,
2337 const guint8 *native_addr;
2338 gint optname, result;
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);
2344 if (!check_socket (socket, error))
2347 native_addr = g_inet_address_to_bytes (group);
2348 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2350 #ifdef HAVE_IP_MREQN
2351 struct ip_mreqn mc_req;
2353 struct ip_mreq mc_req;
2356 memset (&mc_req, 0, sizeof (mc_req));
2357 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2359 #ifdef HAVE_IP_MREQN
2361 mc_req.imr_ifindex = if_nametoindex (iface);
2363 mc_req.imr_ifindex = 0; /* Pick any. */
2364 #elif defined(G_OS_WIN32)
2366 mc_req.imr_interface.s_addr = g_socket_w32_get_adapter_ipv4_addr (iface);
2368 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2370 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2373 if (source_specific)
2375 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2376 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2378 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2380 _("Error joining multicast group: %s") :
2381 _("Error leaving multicast group: %s"),
2382 _("No support for source-specific multicast"));
2387 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2388 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2389 &mc_req, sizeof (mc_req));
2391 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2393 struct ipv6_mreq mc_req_ipv6;
2395 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2396 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2397 #ifdef HAVE_IF_NAMETOINDEX
2399 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2402 mc_req_ipv6.ipv6mr_interface = 0;
2404 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2405 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2406 &mc_req_ipv6, sizeof (mc_req_ipv6));
2409 g_return_val_if_reached (FALSE);
2413 int errsv = get_socket_errno ();
2415 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2417 _("Error joining multicast group: %s") :
2418 _("Error leaving multicast group: %s"),
2419 socket_strerror (errsv));
2427 * g_socket_join_multicast_group:
2428 * @socket: a #GSocket.
2429 * @group: a #GInetAddress specifying the group address to join.
2430 * @iface: (nullable): Name of the interface to use, or %NULL
2431 * @source_specific: %TRUE if source-specific multicast should be used
2432 * @error: #GError for error reporting, or %NULL to ignore.
2434 * Registers @socket to receive multicast messages sent to @group.
2435 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2436 * been bound to an appropriate interface and port with
2439 * If @iface is %NULL, the system will automatically pick an interface
2440 * to bind to based on @group.
2442 * If @source_specific is %TRUE, source-specific multicast as defined
2443 * in RFC 4604 is used. Note that on older platforms this may fail
2444 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2446 * To bind to a given source-specific multicast address, use
2447 * g_socket_join_multicast_group_ssm() instead.
2449 * Returns: %TRUE on success, %FALSE on error.
2454 g_socket_join_multicast_group (GSocket *socket,
2455 GInetAddress *group,
2456 gboolean source_specific,
2460 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2464 * g_socket_leave_multicast_group:
2465 * @socket: a #GSocket.
2466 * @group: a #GInetAddress specifying the group address to leave.
2467 * @iface: (nullable): Interface used
2468 * @source_specific: %TRUE if source-specific multicast was used
2469 * @error: #GError for error reporting, or %NULL to ignore.
2471 * Removes @socket from the multicast group defined by @group, @iface,
2472 * and @source_specific (which must all have the same values they had
2473 * when you joined the group).
2475 * @socket remains bound to its address and port, and can still receive
2476 * unicast messages after calling this.
2478 * To unbind to a given source-specific multicast address, use
2479 * g_socket_leave_multicast_group_ssm() instead.
2481 * Returns: %TRUE on success, %FALSE on error.
2486 g_socket_leave_multicast_group (GSocket *socket,
2487 GInetAddress *group,
2488 gboolean source_specific,
2492 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2496 g_socket_multicast_group_operation_ssm (GSocket *socket,
2497 GInetAddress *group,
2498 GInetAddress *source_specific,
2500 gboolean join_group,
2505 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2506 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2507 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2508 g_return_val_if_fail (iface == NULL || *iface != '\0', FALSE);
2509 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2511 if (!source_specific)
2513 return g_socket_multicast_group_operation (socket, group, FALSE, iface,
2517 if (!check_socket (socket, error))
2520 switch (g_inet_address_get_family (group))
2522 case G_SOCKET_FAMILY_INVALID:
2523 case G_SOCKET_FAMILY_UNIX:
2525 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2527 _("Error joining multicast group: %s") :
2528 _("Error leaving multicast group: %s"),
2529 _("Unsupported socket family"));
2534 case G_SOCKET_FAMILY_IPV4:
2536 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2538 #ifdef BROKEN_IP_MREQ_SOURCE_STRUCT
2539 #define S_ADDR_FIELD(src) src.imr_interface
2541 #define S_ADDR_FIELD(src) src.imr_interface.s_addr
2545 struct ip_mreq_source mc_req_src;
2547 if (g_inet_address_get_family (source_specific) !=
2548 G_SOCKET_FAMILY_IPV4)
2550 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2552 _("Error joining multicast group: %s") :
2553 _("Error leaving multicast group: %s"),
2554 _("source-specific not an IPv4 address"));
2558 memset (&mc_req_src, 0, sizeof (mc_req_src));
2560 /* By default use the default IPv4 multicast interface. */
2561 S_ADDR_FIELD(mc_req_src) = g_htonl (INADDR_ANY);
2565 #if defined(G_OS_WIN32)
2566 S_ADDR_FIELD(mc_req_src) = g_socket_w32_get_adapter_ipv4_addr (iface);
2567 #elif defined (HAVE_SIOCGIFADDR)
2570 struct sockaddr_in *iface_addr;
2571 size_t if_name_len = strlen (iface);
2573 memset (&ifr, 0, sizeof (ifr));
2575 if (if_name_len >= sizeof (ifr.ifr_name))
2577 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FILENAME_TOO_LONG,
2578 _("Interface name too long"));
2582 memcpy (ifr.ifr_name, iface, if_name_len);
2584 /* Get the IPv4 address of the given network interface name. */
2585 ret = ioctl (socket->priv->fd, SIOCGIFADDR, &ifr);
2590 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2591 _("Interface not found: %s"), g_strerror (errsv));
2595 iface_addr = (struct sockaddr_in *) &ifr.ifr_addr;
2596 S_ADDR_FIELD(mc_req_src) = iface_addr->sin_addr.s_addr;
2597 #endif /* defined(G_OS_WIN32) && defined (HAVE_IF_NAMETOINDEX) */
2599 memcpy (&mc_req_src.imr_multiaddr, g_inet_address_to_bytes (group),
2600 g_inet_address_get_native_size (group));
2601 memcpy (&mc_req_src.imr_sourceaddr,
2602 g_inet_address_to_bytes (source_specific),
2603 g_inet_address_get_native_size (source_specific));
2606 join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2607 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2608 &mc_req_src, sizeof (mc_req_src));
2613 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2615 _("Error joining multicast group: %s") :
2616 _("Error leaving multicast group: %s"),
2617 _("No support for IPv4 source-specific multicast"));
2619 #endif /* IP_ADD_SOURCE_MEMBERSHIP */
2623 case G_SOCKET_FAMILY_IPV6:
2625 #ifdef MCAST_JOIN_SOURCE_GROUP
2628 struct group_source_req mc_req_src;
2629 GSocketAddress *saddr_group, *saddr_source_specific;
2630 guint iface_index = 0;
2632 #if defined (HAVE_IF_NAMETOINDEX)
2635 iface_index = if_nametoindex (iface);
2636 if (iface_index == 0)
2640 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2641 _("Interface not found: %s"), g_strerror (errsv));
2645 #endif /* defined (HAVE_IF_NAMETOINDEX) */
2646 mc_req_src.gsr_interface = iface_index;
2648 saddr_group = g_inet_socket_address_new (group, 0);
2649 res = g_socket_address_to_native (saddr_group, &mc_req_src.gsr_group,
2650 sizeof (mc_req_src.gsr_group),
2652 g_object_unref (saddr_group);
2656 saddr_source_specific = g_inet_socket_address_new (source_specific, 0);
2657 res = g_socket_address_to_native (saddr_source_specific,
2658 &mc_req_src.gsr_source,
2659 sizeof (mc_req_src.gsr_source),
2661 g_object_unref (saddr_source_specific);
2667 join_group ? MCAST_JOIN_SOURCE_GROUP : MCAST_LEAVE_SOURCE_GROUP;
2668 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2669 &mc_req_src, sizeof (mc_req_src));
2671 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2673 _("Error joining multicast group: %s") :
2674 _("Error leaving multicast group: %s"),
2675 _("No support for IPv6 source-specific multicast"));
2677 #endif /* MCAST_JOIN_SOURCE_GROUP */
2682 g_return_val_if_reached (FALSE);
2687 int errsv = get_socket_errno ();
2689 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2691 _("Error joining multicast group: %s") :
2692 _("Error leaving multicast group: %s"),
2693 socket_strerror (errsv));
2701 * g_socket_join_multicast_group_ssm:
2702 * @socket: a #GSocket.
2703 * @group: a #GInetAddress specifying the group address to join.
2704 * @source_specific: (nullable): a #GInetAddress specifying the
2705 * source-specific multicast address or %NULL to ignore.
2706 * @iface: (nullable): Name of the interface to use, or %NULL
2707 * @error: #GError for error reporting, or %NULL to ignore.
2709 * Registers @socket to receive multicast messages sent to @group.
2710 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2711 * been bound to an appropriate interface and port with
2714 * If @iface is %NULL, the system will automatically pick an interface
2715 * to bind to based on @group.
2717 * If @source_specific is not %NULL, use source-specific multicast as
2718 * defined in RFC 4604. Note that on older platforms this may fail
2719 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2721 * Note that this function can be called multiple times for the same
2722 * @group with different @source_specific in order to receive multicast
2723 * packets from more than one source.
2725 * Returns: %TRUE on success, %FALSE on error.
2730 g_socket_join_multicast_group_ssm (GSocket *socket,
2731 GInetAddress *group,
2732 GInetAddress *source_specific,
2736 return g_socket_multicast_group_operation_ssm (socket, group,
2737 source_specific, iface, TRUE, error);
2741 * g_socket_leave_multicast_group_ssm:
2742 * @socket: a #GSocket.
2743 * @group: a #GInetAddress specifying the group address to leave.
2744 * @source_specific: (nullable): a #GInetAddress specifying the
2745 * source-specific multicast address or %NULL to ignore.
2746 * @iface: (nullable): Name of the interface to use, or %NULL
2747 * @error: #GError for error reporting, or %NULL to ignore.
2749 * Removes @socket from the multicast group defined by @group, @iface,
2750 * and @source_specific (which must all have the same values they had
2751 * when you joined the group).
2753 * @socket remains bound to its address and port, and can still receive
2754 * unicast messages after calling this.
2756 * Returns: %TRUE on success, %FALSE on error.
2761 g_socket_leave_multicast_group_ssm (GSocket *socket,
2762 GInetAddress *group,
2763 GInetAddress *source_specific,
2767 return g_socket_multicast_group_operation_ssm (socket, group,
2768 source_specific, iface, FALSE, error);
2772 * g_socket_speaks_ipv4:
2773 * @socket: a #GSocket
2775 * Checks if a socket is capable of speaking IPv4.
2777 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2778 * and under some combinations of circumstances IPv6 sockets are also
2779 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2782 * No other types of sockets are currently considered as being capable
2785 * Returns: %TRUE if this socket can be used with IPv4.
2790 g_socket_speaks_ipv4 (GSocket *socket)
2792 switch (socket->priv->family)
2794 case G_SOCKET_FAMILY_IPV4:
2797 case G_SOCKET_FAMILY_IPV6:
2798 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2802 if (!g_socket_get_option (socket,
2803 IPPROTO_IPV6, IPV6_V6ONLY,
2820 * @socket: a #GSocket.
2821 * @cancellable: (nullable): a %GCancellable or %NULL
2822 * @error: #GError for error reporting, or %NULL to ignore.
2824 * Accept incoming connections on a connection-based socket. This removes
2825 * the first outstanding connection request from the listening socket and
2826 * creates a #GSocket object for it.
2828 * The @socket must be bound to a local address with g_socket_bind() and
2829 * must be listening for incoming connections (g_socket_listen()).
2831 * If there are no outstanding connections then the operation will block
2832 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2833 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2835 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2836 * Free the returned object with g_object_unref().
2841 g_socket_accept (GSocket *socket,
2842 GCancellable *cancellable,
2845 GSocket *new_socket;
2848 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2850 if (!check_socket (socket, error))
2853 if (!check_timeout (socket, error))
2858 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2860 int errsv = get_socket_errno ();
2865 #ifdef WSAEWOULDBLOCK
2866 if (errsv == WSAEWOULDBLOCK)
2868 if (errsv == EWOULDBLOCK ||
2872 win32_unset_event_mask (socket, FD_ACCEPT);
2874 if (socket->priv->blocking)
2876 if (!g_socket_condition_wait (socket,
2877 G_IO_IN, cancellable, error))
2884 socket_set_error_lazy (error, errsv, _("Error accepting connection: %s"));
2890 win32_unset_event_mask (socket, FD_ACCEPT);
2894 /* The socket inherits the accepting sockets event mask and even object,
2895 we need to remove that */
2896 WSAEventSelect (ret, NULL, 0);
2902 /* We always want to set close-on-exec to protect users. If you
2903 need to so some weird inheritance to exec you can re-enable this
2904 using lower level hacks with g_socket_get_fd(). */
2905 flags = fcntl (ret, F_GETFD, 0);
2907 (flags & FD_CLOEXEC) == 0)
2909 flags |= FD_CLOEXEC;
2910 fcntl (ret, F_SETFD, flags);
2915 new_socket = g_socket_new_from_fd (ret, error);
2916 if (new_socket == NULL)
2925 new_socket->priv->protocol = socket->priv->protocol;
2932 * @socket: a #GSocket.
2933 * @address: a #GSocketAddress specifying the remote address.
2934 * @cancellable: (nullable): a %GCancellable or %NULL
2935 * @error: #GError for error reporting, or %NULL to ignore.
2937 * Connect the socket to the specified remote address.
2939 * For connection oriented socket this generally means we attempt to make
2940 * a connection to the @address. For a connection-less socket it sets
2941 * the default address for g_socket_send() and discards all incoming datagrams
2942 * from other sources.
2944 * Generally connection oriented sockets can only connect once, but
2945 * connection-less sockets can connect multiple times to change the
2948 * If the connect call needs to do network I/O it will block, unless
2949 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2950 * and the user can be notified of the connection finishing by waiting
2951 * for the G_IO_OUT condition. The result of the connection must then be
2952 * checked with g_socket_check_connect_result().
2954 * Returns: %TRUE if connected, %FALSE on error.
2959 g_socket_connect (GSocket *socket,
2960 GSocketAddress *address,
2961 GCancellable *cancellable,
2965 struct sockaddr_storage storage;
2969 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2971 if (!check_socket (socket, error))
2974 if (!g_socket_address_to_native (address, &buffer.storage, sizeof buffer, error))
2977 if (socket->priv->remote_address)
2978 g_object_unref (socket->priv->remote_address);
2979 socket->priv->remote_address = g_object_ref (address);
2983 if (connect (socket->priv->fd, &buffer.sa,
2984 g_socket_address_get_native_size (address)) < 0)
2986 int errsv = get_socket_errno ();
2992 if (errsv == EINPROGRESS)
2994 if (errsv == WSAEWOULDBLOCK)
2997 win32_unset_event_mask (socket, FD_CONNECT);
2999 if (socket->priv->blocking)
3001 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
3003 if (g_socket_check_connect_result (socket, error))
3009 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
3010 _("Connection in progress"));
3011 socket->priv->connect_pending = TRUE;
3015 g_set_error_literal (error, G_IO_ERROR,
3016 socket_io_error_from_errno (errsv),
3017 socket_strerror (errsv));
3024 win32_unset_event_mask (socket, FD_CONNECT);
3026 socket->priv->connected_read = TRUE;
3027 socket->priv->connected_write = TRUE;
3033 * g_socket_check_connect_result:
3034 * @socket: a #GSocket
3035 * @error: #GError for error reporting, or %NULL to ignore.
3037 * Checks and resets the pending connect error for the socket.
3038 * This is used to check for errors when g_socket_connect() is
3039 * used in non-blocking mode.
3041 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
3046 g_socket_check_connect_result (GSocket *socket,
3051 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3053 if (!check_socket (socket, error))
3056 if (!check_timeout (socket, error))
3059 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
3061 g_prefix_error (error, _("Unable to get pending error: "));
3067 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
3068 socket_strerror (value));
3069 if (socket->priv->remote_address)
3071 g_object_unref (socket->priv->remote_address);
3072 socket->priv->remote_address = NULL;
3077 socket->priv->connected_read = TRUE;
3078 socket->priv->connected_write = TRUE;
3084 * g_socket_get_available_bytes:
3085 * @socket: a #GSocket
3087 * Get the amount of data pending in the OS input buffer, without blocking.
3089 * If @socket is a UDP or SCTP socket, this will return the size of
3090 * just the next packet, even if additional packets are buffered after
3093 * Note that on Windows, this function is rather inefficient in the
3094 * UDP case, and so if you know any plausible upper bound on the size
3095 * of the incoming packet, it is better to just do a
3096 * g_socket_receive() with a buffer of that size, rather than calling
3097 * g_socket_get_available_bytes() first and then doing a receive of
3098 * exactly the right size.
3100 * Returns: the number of bytes that can be read from the socket
3101 * without blocking or truncating, or -1 on error.
3106 g_socket_get_available_bytes (GSocket *socket)
3109 const gint bufsize = 64 * 1024;
3110 static guchar *buf = NULL;
3118 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3121 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
3124 if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
3126 if (G_UNLIKELY (g_once_init_enter (&buf)))
3127 g_once_init_leave (&buf, g_malloc (bufsize));
3129 /* On datagram sockets, FIONREAD ioctl is not reliable because many
3130 * systems add internal header size to the reported size, making it
3131 * unusable for this function. */
3132 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
3135 int errsv = get_socket_errno ();
3137 if (errsv == WSAEWOULDBLOCK)
3139 if (errsv == EWOULDBLOCK || errsv == EAGAIN)
3147 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
3149 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
3158 /* Block on a timed wait for @condition until (@start_time + @timeout).
3159 * Return %G_IO_ERROR_TIMED_OUT if the timeout is reached; otherwise %TRUE.
3162 block_on_timeout (GSocket *socket,
3163 GIOCondition condition,
3166 GCancellable *cancellable,
3169 gint64 wait_timeout = -1;
3171 g_return_val_if_fail (timeout_us != 0, TRUE);
3173 /* check if we've timed out or how much time to wait at most */
3174 if (timeout_us >= 0)
3176 gint64 elapsed = g_get_monotonic_time () - start_time;
3178 if (elapsed >= timeout_us)
3180 g_set_error_literal (error,
3181 G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3182 _("Socket I/O timed out"));
3186 wait_timeout = timeout_us - elapsed;
3189 return g_socket_condition_timed_wait (socket, condition, wait_timeout,
3190 cancellable, error);
3194 g_socket_receive_with_timeout (GSocket *socket,
3198 GCancellable *cancellable,
3204 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3206 start_time = g_get_monotonic_time ();
3208 if (!check_socket (socket, error))
3211 if (!check_timeout (socket, error))
3214 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3219 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
3221 int errsv = get_socket_errno ();
3226 #ifdef WSAEWOULDBLOCK
3227 if (errsv == WSAEWOULDBLOCK)
3229 if (errsv == EWOULDBLOCK ||
3233 win32_unset_event_mask (socket, FD_READ);
3235 if (timeout_us != 0)
3237 if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
3238 cancellable, error))
3245 win32_unset_event_mask (socket, FD_READ);
3247 socket_set_error_lazy (error, errsv, _("Error receiving data: %s"));
3251 win32_unset_event_mask (socket, FD_READ);
3261 * @socket: a #GSocket
3262 * @buffer: (array length=size) (element-type guint8): a buffer to
3263 * read data into (which should be at least @size bytes long).
3264 * @size: the number of bytes you want to read from the socket
3265 * @cancellable: (nullable): a %GCancellable or %NULL
3266 * @error: #GError for error reporting, or %NULL to ignore.
3268 * Receive data (up to @size bytes) from a socket. This is mainly used by
3269 * connection-oriented sockets; it is identical to g_socket_receive_from()
3270 * with @address set to %NULL.
3272 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
3273 * g_socket_receive() will always read either 0 or 1 complete messages from
3274 * the socket. If the received message is too large to fit in @buffer, then
3275 * the data beyond @size bytes will be discarded, without any explicit
3276 * indication that this has occurred.
3278 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
3279 * number of bytes, up to @size. If more than @size bytes have been
3280 * received, the additional data will be returned in future calls to
3281 * g_socket_receive().
3283 * If the socket is in blocking mode the call will block until there
3284 * is some data to receive, the connection is closed, or there is an
3285 * error. If there is no data available and the socket is in
3286 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3287 * returned. To be notified when data is available, wait for the
3288 * %G_IO_IN condition.
3290 * On error -1 is returned and @error is set accordingly.
3292 * Returns: Number of bytes read, or 0 if the connection was closed by
3293 * the peer, or -1 on error
3298 g_socket_receive (GSocket *socket,
3301 GCancellable *cancellable,
3304 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3305 socket->priv->blocking ? -1 : 0,
3306 cancellable, error);
3310 * g_socket_receive_with_blocking:
3311 * @socket: a #GSocket
3312 * @buffer: (array length=size) (element-type guint8): a buffer to
3313 * read data into (which should be at least @size bytes long).
3314 * @size: the number of bytes you want to read from the socket
3315 * @blocking: whether to do blocking or non-blocking I/O
3316 * @cancellable: (nullable): a %GCancellable or %NULL
3317 * @error: #GError for error reporting, or %NULL to ignore.
3319 * This behaves exactly the same as g_socket_receive(), except that
3320 * the choice of blocking or non-blocking behavior is determined by
3321 * the @blocking argument rather than by @socket's properties.
3323 * Returns: Number of bytes read, or 0 if the connection was closed by
3324 * the peer, or -1 on error
3329 g_socket_receive_with_blocking (GSocket *socket,
3333 GCancellable *cancellable,
3336 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3337 blocking ? -1 : 0, cancellable, error);
3341 * g_socket_receive_from:
3342 * @socket: a #GSocket
3343 * @address: (out) (optional): a pointer to a #GSocketAddress
3345 * @buffer: (array length=size) (element-type guint8): a buffer to
3346 * read data into (which should be at least @size bytes long).
3347 * @size: the number of bytes you want to read from the socket
3348 * @cancellable: (nullable): a %GCancellable or %NULL
3349 * @error: #GError for error reporting, or %NULL to ignore.
3351 * Receive data (up to @size bytes) from a socket.
3353 * If @address is non-%NULL then @address will be set equal to the
3354 * source address of the received packet.
3355 * @address is owned by the caller.
3357 * See g_socket_receive() for additional information.
3359 * Returns: Number of bytes read, or 0 if the connection was closed by
3360 * the peer, or -1 on error
3365 g_socket_receive_from (GSocket *socket,
3366 GSocketAddress **address,
3369 GCancellable *cancellable,
3377 return g_socket_receive_message (socket,
3385 /* See the comment about SIGPIPE above. */
3387 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
3389 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
3393 g_socket_send_with_timeout (GSocket *socket,
3394 const guint8 *buffer,
3397 GCancellable *cancellable,
3403 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3405 start_time = g_get_monotonic_time ();
3407 if (!check_socket (socket, error))
3410 if (!check_timeout (socket, error))
3413 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3418 if ((ret = send (socket->priv->fd, (const char *)buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
3420 int errsv = get_socket_errno ();
3425 #ifdef WSAEWOULDBLOCK
3426 if (errsv == WSAEWOULDBLOCK)
3428 if (errsv == EWOULDBLOCK ||
3432 win32_unset_event_mask (socket, FD_WRITE);
3434 if (timeout_us != 0)
3436 if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
3437 cancellable, error))
3444 socket_set_error_lazy (error, errsv, _("Error sending data: %s"));
3455 * @socket: a #GSocket
3456 * @buffer: (array length=size) (element-type guint8): the buffer
3457 * containing the data to send.
3458 * @size: the number of bytes to send
3459 * @cancellable: (nullable): a %GCancellable or %NULL
3460 * @error: #GError for error reporting, or %NULL to ignore.
3462 * Tries to send @size bytes from @buffer on the socket. This is
3463 * mainly used by connection-oriented sockets; it is identical to
3464 * g_socket_send_to() with @address set to %NULL.
3466 * If the socket is in blocking mode the call will block until there is
3467 * space for the data in the socket queue. If there is no space available
3468 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3469 * will be returned. To be notified when space is available, wait for the
3470 * %G_IO_OUT condition. Note though that you may still receive
3471 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3472 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3473 * very common due to the way the underlying APIs work.)
3475 * On error -1 is returned and @error is set accordingly.
3477 * Returns: Number of bytes written (which may be less than @size), or -1
3483 g_socket_send (GSocket *socket,
3484 const gchar *buffer,
3486 GCancellable *cancellable,
3489 return g_socket_send_with_blocking (socket, buffer, size,
3490 socket->priv->blocking,
3491 cancellable, error);
3495 * g_socket_send_with_blocking:
3496 * @socket: a #GSocket
3497 * @buffer: (array length=size) (element-type guint8): the buffer
3498 * containing the data to send.
3499 * @size: the number of bytes to send
3500 * @blocking: whether to do blocking or non-blocking I/O
3501 * @cancellable: (nullable): a %GCancellable or %NULL
3502 * @error: #GError for error reporting, or %NULL to ignore.
3504 * This behaves exactly the same as g_socket_send(), except that
3505 * the choice of blocking or non-blocking behavior is determined by
3506 * the @blocking argument rather than by @socket's properties.
3508 * Returns: Number of bytes written (which may be less than @size), or -1
3514 g_socket_send_with_blocking (GSocket *socket,
3515 const gchar *buffer,
3518 GCancellable *cancellable,
3521 return g_socket_send_with_timeout (socket, (const guint8 *) buffer, size,
3522 blocking ? -1 : 0, cancellable, error);
3527 * @socket: a #GSocket
3528 * @address: (nullable): a #GSocketAddress, or %NULL
3529 * @buffer: (array length=size) (element-type guint8): the buffer
3530 * containing the data to send.
3531 * @size: the number of bytes to send
3532 * @cancellable: (nullable): a %GCancellable or %NULL
3533 * @error: #GError for error reporting, or %NULL to ignore.
3535 * Tries to send @size bytes from @buffer to @address. If @address is
3536 * %NULL then the message is sent to the default receiver (set by
3537 * g_socket_connect()).
3539 * See g_socket_send() for additional information.
3541 * Returns: Number of bytes written (which may be less than @size), or -1
3547 g_socket_send_to (GSocket *socket,
3548 GSocketAddress *address,
3549 const gchar *buffer,
3551 GCancellable *cancellable,
3559 return g_socket_send_message (socket,
3569 * g_socket_shutdown:
3570 * @socket: a #GSocket
3571 * @shutdown_read: whether to shut down the read side
3572 * @shutdown_write: whether to shut down the write side
3573 * @error: #GError for error reporting, or %NULL to ignore.
3575 * Shut down part or all of a full-duplex connection.
3577 * If @shutdown_read is %TRUE then the receiving side of the connection
3578 * is shut down, and further reading is disallowed.
3580 * If @shutdown_write is %TRUE then the sending side of the connection
3581 * is shut down, and further writing is disallowed.
3583 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
3585 * One example where it is useful to shut down only one side of a connection is
3586 * graceful disconnect for TCP connections where you close the sending side,
3587 * then wait for the other side to close the connection, thus ensuring that the
3588 * other side saw all sent data.
3590 * Returns: %TRUE on success, %FALSE on error
3595 g_socket_shutdown (GSocket *socket,
3596 gboolean shutdown_read,
3597 gboolean shutdown_write,
3602 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3604 if (!check_socket (socket, error))
3608 if (!shutdown_read && !shutdown_write)
3612 if (shutdown_read && shutdown_write)
3614 else if (shutdown_read)
3619 if (shutdown_read && shutdown_write)
3621 else if (shutdown_read)
3627 if (shutdown (socket->priv->fd, how) != 0)
3629 int errsv = get_socket_errno ();
3630 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
3631 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
3636 socket->priv->connected_read = FALSE;
3638 socket->priv->connected_write = FALSE;
3645 * @socket: a #GSocket
3646 * @error: #GError for error reporting, or %NULL to ignore.
3648 * Closes the socket, shutting down any active connection.
3650 * Closing a socket does not wait for all outstanding I/O operations
3651 * to finish, so the caller should not rely on them to be guaranteed
3652 * to complete even if the close returns with no error.
3654 * Once the socket is closed, all other operations will return
3655 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
3658 * Sockets will be automatically closed when the last reference
3659 * is dropped, but you might want to call this function to make sure
3660 * resources are released as early as possible.
3662 * Beware that due to the way that TCP works, it is possible for
3663 * recently-sent data to be lost if either you close a socket while the
3664 * %G_IO_IN condition is set, or else if the remote connection tries to
3665 * send something to you after you close the socket but before it has
3666 * finished reading all of the data you sent. There is no easy generic
3667 * way to avoid this problem; the easiest fix is to design the network
3668 * protocol such that the client will never send data "out of turn".
3669 * Another solution is for the server to half-close the connection by
3670 * calling g_socket_shutdown() with only the @shutdown_write flag set,
3671 * and then wait for the client to notice this and close its side of the
3672 * connection, after which the server can safely call g_socket_close().
3673 * (This is what #GTcpConnection does if you call
3674 * g_tcp_connection_set_graceful_disconnect(). But of course, this
3675 * only works if the client will close its connection after the server
3678 * Returns: %TRUE on success, %FALSE on error
3683 g_socket_close (GSocket *socket,
3688 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3690 if (socket->priv->closed)
3691 return TRUE; /* Multiple close not an error */
3693 if (!check_socket (socket, error))
3699 res = closesocket (socket->priv->fd);
3701 res = close (socket->priv->fd);
3705 int errsv = get_socket_errno ();
3710 g_set_error (error, G_IO_ERROR,
3711 socket_io_error_from_errno (errsv),
3712 _("Error closing socket: %s"),
3713 socket_strerror (errsv));
3719 socket->priv->fd = -1;
3720 socket->priv->connected_read = FALSE;
3721 socket->priv->connected_write = FALSE;
3722 socket->priv->closed = TRUE;
3723 if (socket->priv->remote_address)
3725 g_object_unref (socket->priv->remote_address);
3726 socket->priv->remote_address = NULL;
3733 * g_socket_is_closed:
3734 * @socket: a #GSocket
3736 * Checks whether a socket is closed.
3738 * Returns: %TRUE if socket is closed, %FALSE otherwise
3743 g_socket_is_closed (GSocket *socket)
3745 return socket->priv->closed;
3749 /* Broken source, used on errors */
3751 broken_dispatch (GSource *source,
3752 GSourceFunc callback,
3758 static GSourceFuncs broken_funcs =
3767 network_events_for_condition (GIOCondition condition)
3771 if (condition & G_IO_IN)
3772 event_mask |= (FD_READ | FD_ACCEPT);
3773 if (condition & G_IO_OUT)
3774 event_mask |= (FD_WRITE | FD_CONNECT);
3775 event_mask |= FD_CLOSE;
3781 ensure_event (GSocket *socket)
3783 if (socket->priv->event == WSA_INVALID_EVENT)
3784 socket->priv->event = WSACreateEvent();
3788 update_select_events (GSocket *socket)
3795 ensure_event (socket);
3798 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3801 event_mask |= network_events_for_condition (*ptr);
3804 if (event_mask != socket->priv->selected_events)
3806 /* If no events selected, disable event so we can unset
3809 if (event_mask == 0)
3812 event = socket->priv->event;
3814 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3815 socket->priv->selected_events = event_mask;
3820 add_condition_watch (GSocket *socket,
3821 GIOCondition *condition)
3823 g_mutex_lock (&socket->priv->win32_source_lock);
3824 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3826 socket->priv->requested_conditions =
3827 g_list_prepend (socket->priv->requested_conditions, condition);
3829 update_select_events (socket);
3830 g_mutex_unlock (&socket->priv->win32_source_lock);
3834 remove_condition_watch (GSocket *socket,
3835 GIOCondition *condition)
3837 g_mutex_lock (&socket->priv->win32_source_lock);
3838 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3840 socket->priv->requested_conditions =
3841 g_list_remove (socket->priv->requested_conditions, condition);
3843 update_select_events (socket);
3844 g_mutex_unlock (&socket->priv->win32_source_lock);
3848 update_condition_unlocked (GSocket *socket)
3850 WSANETWORKEVENTS events;
3851 GIOCondition condition;
3853 if (WSAEnumNetworkEvents (socket->priv->fd,
3854 socket->priv->event,
3857 socket->priv->current_events |= events.lNetworkEvents;
3858 if (events.lNetworkEvents & FD_WRITE &&
3859 events.iErrorCode[FD_WRITE_BIT] != 0)
3860 socket->priv->current_errors |= FD_WRITE;
3861 if (events.lNetworkEvents & FD_CONNECT &&
3862 events.iErrorCode[FD_CONNECT_BIT] != 0)
3863 socket->priv->current_errors |= FD_CONNECT;
3867 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3868 condition |= G_IO_IN;
3870 if (socket->priv->current_events & FD_CLOSE)
3872 int r, errsv, buffer;
3874 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3876 errsv = get_socket_errno ();
3879 (r < 0 && errsv == WSAENOTCONN))
3880 condition |= G_IO_IN;
3882 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3883 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3884 condition |= G_IO_HUP;
3886 condition |= G_IO_ERR;
3889 if (socket->priv->closed)
3890 condition |= G_IO_HUP;
3892 /* Never report both G_IO_OUT and HUP, these are
3893 mutually exclusive (can't write to a closed socket) */
3894 if ((condition & G_IO_HUP) == 0 &&
3895 socket->priv->current_events & FD_WRITE)
3897 if (socket->priv->current_errors & FD_WRITE)
3898 condition |= G_IO_ERR;
3900 condition |= G_IO_OUT;
3904 if (socket->priv->current_events & FD_CONNECT)
3906 if (socket->priv->current_errors & FD_CONNECT)
3907 condition |= (G_IO_HUP | G_IO_ERR);
3909 condition |= G_IO_OUT;
3917 update_condition (GSocket *socket)
3920 g_mutex_lock (&socket->priv->win32_source_lock);
3921 res = update_condition_unlocked (socket);
3922 g_mutex_unlock (&socket->priv->win32_source_lock);
3935 GIOCondition condition;
3939 socket_source_prepare (GSource *source,
3942 GSocketSource *socket_source = (GSocketSource *)source;
3947 if ((socket_source->pollfd.revents & G_IO_NVAL) != 0)
3950 if (g_socket_is_closed (socket_source->socket))
3952 g_source_remove_poll (source, &socket_source->pollfd);
3953 socket_source->pollfd.revents = G_IO_NVAL;
3957 return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3959 return g_socket_is_closed (socket_source->socket) && socket_source->fd_tag != NULL;
3965 socket_source_check_win32 (GSource *source)
3969 return socket_source_prepare (source, &timeout);
3974 socket_source_dispatch (GSource *source,
3975 GSourceFunc callback,
3978 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3979 GSocketSource *socket_source = (GSocketSource *)source;
3980 GSocket *socket = socket_source->socket;
3986 events = update_condition (socket_source->socket);
3988 if (g_socket_is_closed (socket_source->socket))
3990 if (socket_source->fd_tag)
3991 g_source_remove_unix_fd (source, socket_source->fd_tag);
3992 socket_source->fd_tag = NULL;
3997 events = g_source_query_unix_fd (source, socket_source->fd_tag);
4001 timeout = g_source_get_ready_time (source);
4002 if (timeout >= 0 && timeout < g_source_get_time (source) &&
4003 !g_socket_is_closed (socket_source->socket))
4005 socket->priv->timed_out = TRUE;
4006 events |= (G_IO_IN | G_IO_OUT);
4009 ret = (*func) (socket, events & socket_source->condition, user_data);
4011 if (socket->priv->timeout && !g_socket_is_closed (socket_source->socket))
4012 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
4014 g_source_set_ready_time (source, -1);
4020 socket_source_finalize (GSource *source)
4022 GSocketSource *socket_source = (GSocketSource *)source;
4025 socket = socket_source->socket;
4028 remove_condition_watch (socket, &socket_source->condition);
4031 g_object_unref (socket);
4035 socket_source_closure_callback (GSocket *socket,
4036 GIOCondition condition,
4039 GClosure *closure = data;
4041 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
4042 GValue result_value = G_VALUE_INIT;
4045 g_value_init (&result_value, G_TYPE_BOOLEAN);
4047 g_value_init (¶ms[0], G_TYPE_SOCKET);
4048 g_value_set_object (¶ms[0], socket);
4049 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
4050 g_value_set_flags (¶ms[1], condition);
4052 g_closure_invoke (closure, &result_value, 2, params, NULL);
4054 result = g_value_get_boolean (&result_value);
4055 g_value_unset (&result_value);
4056 g_value_unset (¶ms[0]);
4057 g_value_unset (¶ms[1]);
4062 static GSourceFuncs socket_source_funcs =
4064 socket_source_prepare,
4066 socket_source_check_win32,
4070 socket_source_dispatch,
4071 socket_source_finalize,
4072 (GSourceFunc)socket_source_closure_callback,
4076 socket_source_new (GSocket *socket,
4077 GIOCondition condition,
4078 GCancellable *cancellable)
4081 GSocketSource *socket_source;
4084 ensure_event (socket);
4086 if (socket->priv->event == WSA_INVALID_EVENT)
4088 g_warning ("Failed to create WSAEvent");
4089 return g_source_new (&broken_funcs, sizeof (GSource));
4093 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
4095 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
4096 g_source_set_name (source, "GSocket");
4097 socket_source = (GSocketSource *)source;
4099 socket_source->socket = g_object_ref (socket);
4100 socket_source->condition = condition;
4104 GSource *cancellable_source;
4106 cancellable_source = g_cancellable_source_new (cancellable);
4107 g_source_add_child_source (source, cancellable_source);
4108 g_source_set_dummy_callback (cancellable_source);
4109 g_source_unref (cancellable_source);
4113 add_condition_watch (socket, &socket_source->condition);
4114 socket_source->pollfd.fd = (gintptr) socket->priv->event;
4115 socket_source->pollfd.events = condition;
4116 socket_source->pollfd.revents = 0;
4117 g_source_add_poll (source, &socket_source->pollfd);
4119 socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
4122 if (socket->priv->timeout)
4123 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
4125 g_source_set_ready_time (source, -1);
4131 * g_socket_create_source: (skip)
4132 * @socket: a #GSocket
4133 * @condition: a #GIOCondition mask to monitor
4134 * @cancellable: (nullable): a %GCancellable or %NULL
4136 * Creates a #GSource that can be attached to a %GMainContext to monitor
4137 * for the availability of the specified @condition on the socket. The #GSource
4138 * keeps a reference to the @socket.
4140 * The callback on the source is of the #GSocketSourceFunc type.
4142 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
4143 * these conditions will always be reported output if they are true.
4145 * @cancellable if not %NULL can be used to cancel the source, which will
4146 * cause the source to trigger, reporting the current condition (which
4147 * is likely 0 unless cancellation happened at the same time as a
4148 * condition change). You can check for this in the callback using
4149 * g_cancellable_is_cancelled().
4151 * If @socket has a timeout set, and it is reached before @condition
4152 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
4153 * %G_IO_OUT depending on @condition. However, @socket will have been
4154 * marked as having had a timeout, and so the next #GSocket I/O method
4155 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
4157 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
4162 g_socket_create_source (GSocket *socket,
4163 GIOCondition condition,
4164 GCancellable *cancellable)
4166 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
4168 return socket_source_new (socket, condition, cancellable);
4172 * g_socket_condition_check:
4173 * @socket: a #GSocket
4174 * @condition: a #GIOCondition mask to check
4176 * Checks on the readiness of @socket to perform operations.
4177 * The operations specified in @condition are checked for and masked
4178 * against the currently-satisfied conditions on @socket. The result
4181 * Note that on Windows, it is possible for an operation to return
4182 * %G_IO_ERROR_WOULD_BLOCK even immediately after
4183 * g_socket_condition_check() has claimed that the socket is ready for
4184 * writing. Rather than calling g_socket_condition_check() and then
4185 * writing to the socket if it succeeds, it is generally better to
4186 * simply try writing to the socket right away, and try again later if
4187 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
4189 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
4190 * these conditions will always be set in the output if they are true.
4192 * This call never blocks.
4194 * Returns: the @GIOCondition mask of the current state
4199 g_socket_condition_check (GSocket *socket,
4200 GIOCondition condition)
4202 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
4204 if (!check_socket (socket, NULL))
4209 GIOCondition current_condition;
4211 condition |= G_IO_ERR | G_IO_HUP;
4213 add_condition_watch (socket, &condition);
4214 current_condition = update_condition (socket);
4215 remove_condition_watch (socket, &condition);
4216 return condition & current_condition;
4222 poll_fd.fd = socket->priv->fd;
4223 poll_fd.events = condition;
4224 poll_fd.revents = 0;
4227 result = g_poll (&poll_fd, 1, 0);
4228 while (result == -1 && get_socket_errno () == EINTR);
4230 return poll_fd.revents;
4236 * g_socket_condition_wait:
4237 * @socket: a #GSocket
4238 * @condition: a #GIOCondition mask to wait for
4239 * @cancellable: (nullable): a #GCancellable, or %NULL
4240 * @error: a #GError pointer, or %NULL
4242 * Waits for @condition to become true on @socket. When the condition
4243 * is met, %TRUE is returned.
4245 * If @cancellable is cancelled before the condition is met, or if the
4246 * socket has a timeout set and it is reached before the condition is
4247 * met, then %FALSE is returned and @error, if non-%NULL, is set to
4248 * the appropriate value (%G_IO_ERROR_CANCELLED or
4249 * %G_IO_ERROR_TIMED_OUT).
4251 * See also g_socket_condition_timed_wait().
4253 * Returns: %TRUE if the condition was met, %FALSE otherwise
4258 g_socket_condition_wait (GSocket *socket,
4259 GIOCondition condition,
4260 GCancellable *cancellable,
4263 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4265 return g_socket_condition_timed_wait (socket, condition, -1,
4266 cancellable, error);
4270 * g_socket_condition_timed_wait:
4271 * @socket: a #GSocket
4272 * @condition: a #GIOCondition mask to wait for
4273 * @timeout_us: the maximum time (in microseconds) to wait, or -1
4274 * @cancellable: (nullable): a #GCancellable, or %NULL
4275 * @error: a #GError pointer, or %NULL
4277 * Waits for up to @timeout_us microseconds for @condition to become true
4278 * on @socket. If the condition is met, %TRUE is returned.
4280 * If @cancellable is cancelled before the condition is met, or if
4281 * @timeout_us (or the socket's #GSocket:timeout) is reached before the
4282 * condition is met, then %FALSE is returned and @error, if non-%NULL,
4283 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
4284 * %G_IO_ERROR_TIMED_OUT).
4286 * If you don't want a timeout, use g_socket_condition_wait().
4287 * (Alternatively, you can pass -1 for @timeout_us.)
4289 * Note that although @timeout_us is in microseconds for consistency with
4290 * other GLib APIs, this function actually only has millisecond
4291 * resolution, and the behavior is undefined if @timeout_us is not an
4292 * exact number of milliseconds.
4294 * Returns: %TRUE if the condition was met, %FALSE otherwise
4299 g_socket_condition_timed_wait (GSocket *socket,
4300 GIOCondition condition,
4302 GCancellable *cancellable,
4308 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4310 if (!check_socket (socket, error))
4313 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4316 if (socket->priv->timeout &&
4317 (timeout_us < 0 || socket->priv->timeout < timeout_us / G_USEC_PER_SEC))
4318 timeout_ms = (gint64) socket->priv->timeout * 1000;
4319 else if (timeout_us != -1)
4320 timeout_ms = timeout_us / 1000;
4324 start_time = g_get_monotonic_time ();
4328 GIOCondition current_condition;
4334 /* Always check these */
4335 condition |= G_IO_ERR | G_IO_HUP;
4337 add_condition_watch (socket, &condition);
4340 events[num_events++] = socket->priv->event;
4342 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
4343 events[num_events++] = (WSAEVENT)cancel_fd.fd;
4345 if (timeout_ms == -1)
4346 timeout_ms = WSA_INFINITE;
4348 g_mutex_lock (&socket->priv->win32_source_lock);
4349 current_condition = update_condition_unlocked (socket);
4350 while ((condition & current_condition) == 0)
4352 if (!socket->priv->waiting)
4354 socket->priv->waiting = TRUE;
4355 socket->priv->waiting_result = 0;
4356 g_mutex_unlock (&socket->priv->win32_source_lock);
4358 res = WSAWaitForMultipleEvents (num_events, events, FALSE, timeout_ms, FALSE);
4360 g_mutex_lock (&socket->priv->win32_source_lock);
4361 socket->priv->waiting = FALSE;
4362 socket->priv->waiting_result = res;
4363 g_cond_broadcast (&socket->priv->win32_source_cond);
4367 if (timeout_ms != WSA_INFINITE)
4369 if (!g_cond_wait_until (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock, timeout_ms))
4371 res = WSA_WAIT_TIMEOUT;
4376 res = socket->priv->waiting_result;
4381 g_cond_wait (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock);
4382 res = socket->priv->waiting_result;
4386 if (res == WSA_WAIT_FAILED)
4388 int errsv = get_socket_errno ();
4390 g_set_error (error, G_IO_ERROR,
4391 socket_io_error_from_errno (errsv),
4392 _("Waiting for socket condition: %s"),
4393 socket_strerror (errsv));
4396 else if (res == WSA_WAIT_TIMEOUT)
4398 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4399 _("Socket I/O timed out"));
4403 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4406 current_condition = update_condition_unlocked (socket);
4408 if (timeout_ms != WSA_INFINITE)
4410 timeout_ms -= (g_get_monotonic_time () - start_time) * 1000;
4415 g_mutex_unlock (&socket->priv->win32_source_lock);
4416 remove_condition_watch (socket, &condition);
4418 g_cancellable_release_fd (cancellable);
4420 return (condition & current_condition) != 0;
4428 poll_fd[0].fd = socket->priv->fd;
4429 poll_fd[0].events = condition;
4432 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
4438 result = g_poll (poll_fd, num, timeout_ms);
4440 if (result != -1 || errsv != EINTR)
4443 if (timeout_ms != -1)
4445 timeout_ms -= (g_get_monotonic_time () - start_time) / 1000;
4452 g_cancellable_release_fd (cancellable);
4456 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4457 _("Socket I/O timed out"));
4461 return !g_cancellable_set_error_if_cancelled (cancellable, error);
4468 /* Unfortunately these have to be macros rather than inline functions due to
4469 * using alloca(). */
4470 #define output_message_to_msghdr(message, prev_message, msg, prev_msg, error) \
4472 const GOutputMessage *_message = (message); \
4473 const GOutputMessage *_prev_message = (prev_message); \
4474 struct msghdr *_msg = (msg); \
4475 const struct msghdr *_prev_msg = (prev_msg); \
4476 GError **_error = (error); \
4478 _msg->msg_flags = 0; \
4481 if (_prev_message != NULL && _prev_message->address == _message->address) \
4483 _msg->msg_name = _prev_msg->msg_name; \
4484 _msg->msg_namelen = _prev_msg->msg_namelen; \
4486 else if (_message->address != NULL) \
4488 _msg->msg_namelen = g_socket_address_get_native_size (_message->address); \
4489 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4490 if (!g_socket_address_to_native (_message->address, _msg->msg_name, \
4491 _msg->msg_namelen, _error)) \
4496 _msg->msg_name = NULL; \
4497 _msg->msg_namelen = 0; \
4502 /* this entire expression will be evaluated at compile time */ \
4503 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4504 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4505 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4506 G_STRUCT_OFFSET (GOutputVector, buffer) && \
4507 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4508 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4509 G_STRUCT_OFFSET (GOutputVector, size)) \
4510 /* ABI is compatible */ \
4512 _msg->msg_iov = (struct iovec *) _message->vectors; \
4513 _msg->msg_iovlen = _message->num_vectors; \
4516 /* ABI is incompatible */ \
4520 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4521 for (i = 0; i < _message->num_vectors; i++) \
4523 _msg->msg_iov[i].iov_base = (void *) _message->vectors[i].buffer; \
4524 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4526 _msg->msg_iovlen = _message->num_vectors; \
4532 struct cmsghdr *cmsg; \
4535 _msg->msg_controllen = 0; \
4536 for (i = 0; i < _message->num_control_messages; i++) \
4537 _msg->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (_message->control_messages[i])); \
4539 if (_msg->msg_controllen == 0) \
4540 _msg->msg_control = NULL; \
4543 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4544 memset (_msg->msg_control, '\0', _msg->msg_controllen); \
4547 cmsg = CMSG_FIRSTHDR (_msg); \
4548 for (i = 0; i < _message->num_control_messages; i++) \
4550 cmsg->cmsg_level = g_socket_control_message_get_level (_message->control_messages[i]); \
4551 cmsg->cmsg_type = g_socket_control_message_get_msg_type (_message->control_messages[i]); \
4552 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (_message->control_messages[i])); \
4553 g_socket_control_message_serialize (_message->control_messages[i], \
4554 CMSG_DATA (cmsg)); \
4555 cmsg = CMSG_NXTHDR (_msg, cmsg); \
4557 g_assert (cmsg == NULL); \
4561 #define input_message_to_msghdr(message, msg) \
4563 const GInputMessage *_message = (message); \
4564 struct msghdr *_msg = (msg); \
4567 if (_message->address) \
4569 _msg->msg_namelen = sizeof (struct sockaddr_storage); \
4570 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4574 _msg->msg_name = NULL; \
4575 _msg->msg_namelen = 0; \
4579 /* this entire expression will be evaluated at compile time */ \
4580 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4581 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4582 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4583 G_STRUCT_OFFSET (GInputVector, buffer) && \
4584 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4585 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4586 G_STRUCT_OFFSET (GInputVector, size)) \
4587 /* ABI is compatible */ \
4589 _msg->msg_iov = (struct iovec *) _message->vectors; \
4590 _msg->msg_iovlen = _message->num_vectors; \
4593 /* ABI is incompatible */ \
4597 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4598 for (i = 0; i < _message->num_vectors; i++) \
4600 _msg->msg_iov[i].iov_base = _message->vectors[i].buffer; \
4601 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4603 _msg->msg_iovlen = _message->num_vectors; \
4607 if (_message->control_messages == NULL) \
4609 _msg->msg_controllen = 0; \
4610 _msg->msg_control = NULL; \
4614 _msg->msg_controllen = 2048; \
4615 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4619 _msg->msg_flags = _message->flags; \
4623 input_message_from_msghdr (const struct msghdr *msg,
4624 GInputMessage *message,
4627 /* decode address */
4628 if (message->address != NULL)
4630 *message->address = cache_recv_address (socket, msg->msg_name,
4634 /* decode control messages */
4636 GPtrArray *my_messages = NULL;
4637 struct cmsghdr *cmsg;
4639 if (msg->msg_controllen >= sizeof (struct cmsghdr))
4641 g_assert (message->control_messages != NULL);
4642 for (cmsg = CMSG_FIRSTHDR (msg);
4644 cmsg = CMSG_NXTHDR ((struct msghdr *) msg, cmsg))
4646 GSocketControlMessage *control_message;
4648 control_message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4650 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4652 if (control_message == NULL)
4653 /* We've already spewed about the problem in the
4654 deserialization code, so just continue */
4657 if (my_messages == NULL)
4658 my_messages = g_ptr_array_new ();
4659 g_ptr_array_add (my_messages, control_message);
4663 if (message->num_control_messages)
4664 *message->num_control_messages = my_messages != NULL ? my_messages->len : 0;
4666 if (message->control_messages)
4668 if (my_messages == NULL)
4670 *message->control_messages = NULL;
4674 g_ptr_array_add (my_messages, NULL);
4675 *message->control_messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4680 g_assert (my_messages == NULL);
4684 /* capture the flags */
4685 message->flags = msg->msg_flags;
4690 * g_socket_send_message:
4691 * @socket: a #GSocket
4692 * @address: (nullable): a #GSocketAddress, or %NULL
4693 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4694 * @num_vectors: the number of elements in @vectors, or -1
4695 * @messages: (array length=num_messages) (nullable): a pointer to an
4696 * array of #GSocketControlMessages, or %NULL.
4697 * @num_messages: number of elements in @messages, or -1.
4698 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
4699 * contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
4700 * @cancellable: (nullable): a %GCancellable or %NULL
4701 * @error: #GError for error reporting, or %NULL to ignore.
4703 * Send data to @address on @socket. For sending multiple messages see
4704 * g_socket_send_messages(); for easier use, see
4705 * g_socket_send() and g_socket_send_to().
4707 * If @address is %NULL then the message is sent to the default receiver
4708 * (set by g_socket_connect()).
4710 * @vectors must point to an array of #GOutputVector structs and
4711 * @num_vectors must be the length of this array. (If @num_vectors is -1,
4712 * then @vectors is assumed to be terminated by a #GOutputVector with a
4713 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
4714 * that the sent data will be gathered from. Using multiple
4715 * #GOutputVectors is more memory-efficient than manually copying
4716 * data from multiple sources into a single buffer, and more
4717 * network-efficient than making multiple calls to g_socket_send().
4719 * @messages, if non-%NULL, is taken to point to an array of @num_messages
4720 * #GSocketControlMessage instances. These correspond to the control
4721 * messages to be sent on the socket.
4722 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
4725 * @flags modify how the message is sent. The commonly available arguments
4726 * for this are available in the #GSocketMsgFlags enum, but the
4727 * values there are the same as the system values, and the flags
4728 * are passed in as-is, so you can pass in system-specific flags too.
4730 * If the socket is in blocking mode the call will block until there is
4731 * space for the data in the socket queue. If there is no space available
4732 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4733 * will be returned. To be notified when space is available, wait for the
4734 * %G_IO_OUT condition. Note though that you may still receive
4735 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4736 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4737 * very common due to the way the underlying APIs work.)
4739 * On error -1 is returned and @error is set accordingly.
4741 * Returns: Number of bytes written (which may be less than @size), or -1
4747 g_socket_send_message (GSocket *socket,
4748 GSocketAddress *address,
4749 GOutputVector *vectors,
4751 GSocketControlMessage **messages,
4754 GCancellable *cancellable,
4757 GPollableReturn res;
4758 gsize bytes_written = 0;
4760 res = g_socket_send_message_with_timeout (socket, address,
4761 vectors, num_vectors,
4762 messages, num_messages, flags,
4763 socket->priv->blocking ? -1 : 0,
4765 cancellable, error);
4767 if (res == G_POLLABLE_RETURN_WOULD_BLOCK)
4770 socket_set_error_lazy (error, EWOULDBLOCK, _("Error sending message: %s"));
4772 socket_set_error_lazy (error, WSAEWOULDBLOCK, _("Error sending message: %s"));
4776 return res == G_POLLABLE_RETURN_OK ? bytes_written : -1;
4780 * g_socket_send_message_with_timeout:
4781 * @socket: a #GSocket
4782 * @address: (nullable): a #GSocketAddress, or %NULL
4783 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4784 * @num_vectors: the number of elements in @vectors, or -1
4785 * @messages: (array length=num_messages) (nullable): a pointer to an
4786 * array of #GSocketControlMessages, or %NULL.
4787 * @num_messages: number of elements in @messages, or -1.
4788 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
4789 * contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
4790 * @timeout_us: the maximum time (in microseconds) to wait, or -1
4791 * @bytes_written: (out) (optional): location to store the number of bytes that were written to the socket
4792 * @cancellable: (nullable): a %GCancellable or %NULL
4793 * @error: #GError for error reporting, or %NULL to ignore.
4795 * This behaves exactly the same as g_socket_send_message(), except that
4796 * the choice of timeout behavior is determined by the @timeout_us argument
4797 * rather than by @socket's properties.
4799 * On error %G_POLLABLE_RETURN_FAILED is returned and @error is set accordingly, or
4800 * if the socket is currently not writable %G_POLLABLE_RETURN_WOULD_BLOCK is
4801 * returned. @bytes_written will contain 0 in both cases.
4803 * Returns: %G_POLLABLE_RETURN_OK if all data was successfully written,
4804 * %G_POLLABLE_RETURN_WOULD_BLOCK if the socket is currently not writable, or
4805 * %G_POLLABLE_RETURN_FAILED if an error happened and @error is set.
4810 g_socket_send_message_with_timeout (GSocket *socket,
4811 GSocketAddress *address,
4812 const GOutputVector *vectors,
4814 GSocketControlMessage **messages,
4818 gsize *bytes_written,
4819 GCancellable *cancellable,
4822 GOutputVector one_vector;
4829 g_return_val_if_fail (G_IS_SOCKET (socket), G_POLLABLE_RETURN_FAILED);
4830 g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), G_POLLABLE_RETURN_FAILED);
4831 g_return_val_if_fail (num_vectors == 0 || vectors != NULL, G_POLLABLE_RETURN_FAILED);
4832 g_return_val_if_fail (num_messages == 0 || messages != NULL, G_POLLABLE_RETURN_FAILED);
4833 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), G_POLLABLE_RETURN_FAILED);
4834 g_return_val_if_fail (error == NULL || *error == NULL, G_POLLABLE_RETURN_FAILED);
4836 start_time = g_get_monotonic_time ();
4838 if (!check_socket (socket, error))
4839 return G_POLLABLE_RETURN_FAILED;
4841 if (!check_timeout (socket, error))
4842 return G_POLLABLE_RETURN_FAILED;
4844 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4845 return G_POLLABLE_RETURN_FAILED;
4847 if (num_vectors == -1)
4849 for (num_vectors = 0;
4850 vectors[num_vectors].buffer != NULL;
4855 if (num_messages == -1)
4857 for (num_messages = 0;
4858 messages != NULL && messages[num_messages] != NULL;
4863 if (num_vectors == 0)
4867 one_vector.buffer = &zero;
4868 one_vector.size = 1;
4870 vectors = &one_vector;
4875 GOutputMessage output_message;
4878 GError *child_error = NULL;
4880 output_message.address = address;
4881 output_message.vectors = (GOutputVector *) vectors;
4882 output_message.num_vectors = num_vectors;
4883 output_message.bytes_sent = 0;
4884 output_message.control_messages = messages;
4885 output_message.num_control_messages = num_messages;
4887 output_message_to_msghdr (&output_message, NULL, &msg, NULL, &child_error);
4889 if (child_error != NULL)
4891 g_propagate_error (error, child_error);
4892 return G_POLLABLE_RETURN_FAILED;
4897 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4900 int errsv = get_socket_errno ();
4905 if (errsv == EWOULDBLOCK || errsv == EAGAIN)
4907 if (timeout_us != 0)
4909 if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
4910 cancellable, error))
4911 return G_POLLABLE_RETURN_FAILED;
4916 return G_POLLABLE_RETURN_WOULD_BLOCK;
4919 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4920 return G_POLLABLE_RETURN_FAILED;
4926 *bytes_written = result;
4928 return G_POLLABLE_RETURN_OK;
4932 struct sockaddr_storage addr;
4939 /* Win32 doesn't support control messages.
4940 Actually this is possible for raw and datagram sockets
4941 via WSASendMessage on Vista or later, but that doesn't
4943 if (num_messages != 0)
4945 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
4946 _("GSocketControlMessage not supported on Windows"));
4947 return G_POLLABLE_RETURN_FAILED;
4951 bufs = g_newa (WSABUF, num_vectors);
4952 for (i = 0; i < num_vectors; i++)
4954 bufs[i].buf = (char *)vectors[i].buffer;
4955 bufs[i].len = (gulong)vectors[i].size;
4959 addrlen = 0; /* Avoid warning */
4962 addrlen = g_socket_address_get_native_size (address);
4963 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
4964 return G_POLLABLE_RETURN_FAILED;
4970 result = WSASendTo (socket->priv->fd,
4973 (const struct sockaddr *)&addr, addrlen,
4976 result = WSASend (socket->priv->fd,
4983 int errsv = get_socket_errno ();
4985 if (errsv == WSAEINTR)
4988 if (errsv == WSAEWOULDBLOCK)
4990 win32_unset_event_mask (socket, FD_WRITE);
4992 if (timeout_us != 0)
4994 if (!block_on_timeout (socket, G_IO_OUT, timeout_us,
4995 start_time, cancellable, error))
4996 return G_POLLABLE_RETURN_FAILED;
5001 return G_POLLABLE_RETURN_WOULD_BLOCK;
5004 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5005 return G_POLLABLE_RETURN_FAILED;
5011 *bytes_written = bytes_sent;
5012 return G_POLLABLE_RETURN_OK;
5018 * g_socket_send_messages:
5019 * @socket: a #GSocket
5020 * @messages: (array length=num_messages): an array of #GOutputMessage structs
5021 * @num_messages: the number of elements in @messages
5022 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
5023 * contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5024 * @cancellable: (nullable): a %GCancellable or %NULL
5025 * @error: #GError for error reporting, or %NULL to ignore.
5027 * Send multiple data messages from @socket in one go. This is the most
5028 * complicated and fully-featured version of this call. For easier use, see
5029 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
5031 * @messages must point to an array of #GOutputMessage structs and
5032 * @num_messages must be the length of this array. Each #GOutputMessage
5033 * contains an address to send the data to, and a pointer to an array of
5034 * #GOutputVector structs to describe the buffers that the data to be sent
5035 * for each message will be gathered from. Using multiple #GOutputVectors is
5036 * more memory-efficient than manually copying data from multiple sources
5037 * into a single buffer, and more network-efficient than making multiple
5038 * calls to g_socket_send(). Sending multiple messages in one go avoids the
5039 * overhead of making a lot of syscalls in scenarios where a lot of data
5040 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
5041 * or where the same data needs to be sent to multiple recipients.
5043 * @flags modify how the message is sent. The commonly available arguments
5044 * for this are available in the #GSocketMsgFlags enum, but the
5045 * values there are the same as the system values, and the flags
5046 * are passed in as-is, so you can pass in system-specific flags too.
5048 * If the socket is in blocking mode the call will block until there is
5049 * space for all the data in the socket queue. If there is no space available
5050 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
5051 * will be returned if no data was written at all, otherwise the number of
5052 * messages sent will be returned. To be notified when space is available,
5053 * wait for the %G_IO_OUT condition. Note though that you may still receive
5054 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
5055 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
5056 * very common due to the way the underlying APIs work.)
5058 * On error -1 is returned and @error is set accordingly. An error will only
5059 * be returned if zero messages could be sent; otherwise the number of messages
5060 * successfully sent before the error will be returned.
5062 * Returns: number of messages sent, or -1 on error. Note that the number of
5063 * messages sent may be smaller than @num_messages if the socket is
5064 * non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
5065 * in which case the caller may re-try to send the remaining messages.
5070 g_socket_send_messages (GSocket *socket,
5071 GOutputMessage *messages,
5074 GCancellable *cancellable,
5077 return g_socket_send_messages_with_timeout (socket, messages, num_messages,
5079 socket->priv->blocking ? -1 : 0,
5080 cancellable, error);
5084 g_socket_send_messages_with_timeout (GSocket *socket,
5085 GOutputMessage *messages,
5089 GCancellable *cancellable,
5094 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5095 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5096 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
5097 g_return_val_if_fail (error == NULL || *error == NULL, -1);
5099 start_time = g_get_monotonic_time ();
5101 if (!check_socket (socket, error))
5104 if (!check_timeout (socket, error))
5107 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5110 if (num_messages == 0)
5113 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
5115 struct mmsghdr *msgvec;
5118 /* Clamp the number of vectors if more given than we can write in one go.
5119 * The caller has to handle short writes anyway.
5121 if (num_messages > G_IOV_MAX)
5122 num_messages = G_IOV_MAX;
5124 msgvec = g_newa (struct mmsghdr, num_messages);
5126 for (i = 0; i < num_messages; ++i)
5128 GOutputMessage *msg = &messages[i];
5129 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5130 GError *child_error = NULL;
5132 msgvec[i].msg_len = 0;
5134 output_message_to_msghdr (msg, (i > 0) ? &messages[i - 1] : NULL,
5135 msg_hdr, (i > 0) ? &msgvec[i - 1].msg_hdr : NULL,
5138 if (child_error != NULL)
5140 g_propagate_error (error, child_error);
5145 for (num_sent = 0; num_sent < num_messages;)
5149 ret = sendmmsg (socket->priv->fd, msgvec + num_sent, num_messages - num_sent,
5150 flags | G_SOCKET_DEFAULT_SEND_FLAGS);
5154 int errsv = get_socket_errno ();
5159 if (timeout_us != 0 &&
5160 (errsv == EWOULDBLOCK ||
5163 if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
5164 cancellable, error))
5168 g_clear_error (error);
5178 /* If any messages were successfully sent, do not error. */
5182 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5190 for (i = 0; i < num_sent; ++i)
5191 messages[i].bytes_sent = msgvec[i].msg_len;
5199 gint64 wait_timeout;
5201 wait_timeout = timeout_us;
5203 for (i = 0; i < num_messages; ++i)
5205 GOutputMessage *msg = &messages[i];
5206 GError *msg_error = NULL;
5207 GPollableReturn pollable_result;
5208 gsize bytes_written = 0;
5210 pollable_result = g_socket_send_message_with_timeout (socket, msg->address,
5213 msg->control_messages,
5214 msg->num_control_messages,
5215 flags, wait_timeout,
5217 cancellable, &msg_error);
5219 if (pollable_result == G_POLLABLE_RETURN_WOULD_BLOCK)
5222 socket_set_error_lazy (&msg_error, EWOULDBLOCK, _("Error sending message: %s"));
5224 socket_set_error_lazy (&msg_error, WSAEWOULDBLOCK, _("Error sending message: %s"));
5228 result = pollable_result == G_POLLABLE_RETURN_OK ? bytes_written : -1;
5230 /* check if we've timed out or how much time to wait at most */
5233 gint64 elapsed = g_get_monotonic_time () - start_time;
5234 wait_timeout = MAX (timeout_us - elapsed, 1);
5239 /* if we couldn't send all messages, just return how many we did
5240 * manage to send, provided we managed to send at least one */
5243 g_error_free (msg_error);
5248 g_propagate_error (error, msg_error);
5253 msg->bytes_sent = result;
5261 static GSocketAddress *
5262 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
5264 GSocketAddress *saddr;
5266 guint64 oldest_time = G_MAXUINT64;
5267 gint oldest_index = 0;
5269 if (native_len <= 0)
5273 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
5275 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
5276 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
5277 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
5282 if (tmp_native_len != native_len)
5285 if (memcmp (tmp_native, native, native_len) == 0)
5287 saddr = g_object_ref (tmp);
5288 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
5292 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
5294 oldest_time = socket->priv->recv_addr_cache[i].last_used;
5299 saddr = g_socket_address_new_from_native (native, native_len);
5301 if (socket->priv->recv_addr_cache[oldest_index].addr)
5303 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
5304 g_free (socket->priv->recv_addr_cache[oldest_index].native);
5307 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
5308 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
5309 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
5310 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
5316 g_socket_receive_message_with_timeout (GSocket *socket,
5317 GSocketAddress **address,
5318 GInputVector *vectors,
5320 GSocketControlMessage ***messages,
5324 GCancellable *cancellable,
5327 GInputVector one_vector;
5331 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5333 start_time = g_get_monotonic_time ();
5335 if (!check_socket (socket, error))
5338 if (!check_timeout (socket, error))
5341 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5344 if (num_vectors == -1)
5346 for (num_vectors = 0;
5347 vectors[num_vectors].buffer != NULL;
5352 if (num_vectors == 0)
5354 one_vector.buffer = &one_byte;
5355 one_vector.size = 1;
5357 vectors = &one_vector;
5362 GInputMessage input_message;
5366 input_message.address = address;
5367 input_message.vectors = vectors;
5368 input_message.num_vectors = num_vectors;
5369 input_message.bytes_received = 0;
5370 input_message.flags = (flags != NULL) ? *flags : 0;
5371 input_message.control_messages = messages;
5372 input_message.num_control_messages = (guint *) num_messages;
5374 /* We always set the close-on-exec flag so we don't leak file
5375 * descriptors into child processes. Note that gunixfdmessage.c
5376 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5378 #ifdef MSG_CMSG_CLOEXEC
5379 input_message.flags |= MSG_CMSG_CLOEXEC;
5382 input_message_to_msghdr (&input_message, &msg);
5387 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5388 #ifdef MSG_CMSG_CLOEXEC
5389 if (result < 0 && get_socket_errno () == EINVAL)
5391 /* We must be running on an old kernel. Call without the flag. */
5392 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
5393 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5399 int errsv = get_socket_errno ();
5404 if (timeout_us != 0 &&
5405 (errsv == EWOULDBLOCK ||
5408 if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
5409 cancellable, error))
5415 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5421 input_message_from_msghdr (&msg, &input_message, socket);
5424 *flags = input_message.flags;
5430 struct sockaddr_storage addr;
5432 DWORD bytes_received;
5439 bufs = g_newa (WSABUF, num_vectors);
5440 for (i = 0; i < num_vectors; i++)
5442 bufs[i].buf = (char *)vectors[i].buffer;
5443 bufs[i].len = (gulong)vectors[i].size;
5455 addrlen = sizeof addr;
5457 result = WSARecvFrom (socket->priv->fd,
5459 &bytes_received, &win_flags,
5460 (struct sockaddr *)&addr, &addrlen,
5463 result = WSARecv (socket->priv->fd,
5465 &bytes_received, &win_flags,
5469 int errsv = get_socket_errno ();
5471 if (errsv == WSAEINTR)
5474 if (errsv == WSAEWOULDBLOCK)
5476 win32_unset_event_mask (socket, FD_READ);
5478 if (timeout_us != 0)
5480 if (!block_on_timeout (socket, G_IO_IN, timeout_us,
5481 start_time, cancellable, error))
5488 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5491 win32_unset_event_mask (socket, FD_READ);
5495 /* decode address */
5496 if (address != NULL)
5498 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
5501 /* capture the flags */
5505 if (messages != NULL)
5507 if (num_messages != NULL)
5510 return bytes_received;
5516 * g_socket_receive_messages:
5517 * @socket: a #GSocket
5518 * @messages: (array length=num_messages): an array of #GInputMessage structs
5519 * @num_messages: the number of elements in @messages
5520 * @flags: an int containing #GSocketMsgFlags flags for the overall operation,
5521 * which may additionally contain
5522 * [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5523 * @cancellable: (nullable): a %GCancellable or %NULL
5524 * @error: #GError for error reporting, or %NULL to ignore
5526 * Receive multiple data messages from @socket in one go. This is the most
5527 * complicated and fully-featured version of this call. For easier use, see
5528 * g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
5530 * @messages must point to an array of #GInputMessage structs and
5531 * @num_messages must be the length of this array. Each #GInputMessage
5532 * contains a pointer to an array of #GInputVector structs describing the
5533 * buffers that the data received in each message will be written to. Using
5534 * multiple #GInputVectors is more memory-efficient than manually copying data
5535 * out of a single buffer to multiple sources, and more system-call-efficient
5536 * than making multiple calls to g_socket_receive(), such as in scenarios where
5537 * a lot of data packets need to be received (e.g. high-bandwidth video
5538 * streaming over RTP/UDP).
5540 * @flags modify how all messages are received. The commonly available
5541 * arguments for this are available in the #GSocketMsgFlags enum, but the
5542 * values there are the same as the system values, and the flags
5543 * are passed in as-is, so you can pass in system-specific flags too. These
5544 * flags affect the overall receive operation. Flags affecting individual
5545 * messages are returned in #GInputMessage.flags.
5547 * The other members of #GInputMessage are treated as described in its
5550 * If #GSocket:blocking is %TRUE the call will block until @num_messages have
5551 * been received, or the end of the stream is reached.
5553 * If #GSocket:blocking is %FALSE the call will return up to @num_messages
5554 * without blocking, or %G_IO_ERROR_WOULD_BLOCK if no messages are queued in the
5555 * operating system to be received.
5557 * In blocking mode, if #GSocket:timeout is positive and is reached before any
5558 * messages are received, %G_IO_ERROR_TIMED_OUT is returned, otherwise up to
5559 * @num_messages are returned. (Note: This is effectively the
5560 * behaviour of `MSG_WAITFORONE` with recvmmsg().)
5562 * To be notified when messages are available, wait for the
5563 * %G_IO_IN condition. Note though that you may still receive
5564 * %G_IO_ERROR_WOULD_BLOCK from g_socket_receive_messages() even if you were
5565 * previously notified of a %G_IO_IN condition.
5567 * If the remote peer closes the connection, any messages queued in the
5568 * operating system will be returned, and subsequent calls to
5569 * g_socket_receive_messages() will return 0 (with no error set).
5571 * On error -1 is returned and @error is set accordingly. An error will only
5572 * be returned if zero messages could be received; otherwise the number of
5573 * messages successfully received before the error will be returned.
5575 * Returns: number of messages received, or -1 on error. Note that the number
5576 * of messages received may be smaller than @num_messages if in non-blocking
5577 * mode, if the peer closed the connection, or if @num_messages
5578 * was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
5579 * to receive the remaining messages.
5584 g_socket_receive_messages (GSocket *socket,
5585 GInputMessage *messages,
5588 GCancellable *cancellable,
5591 if (!check_socket (socket, error) ||
5592 !check_timeout (socket, error))
5595 return g_socket_receive_messages_with_timeout (socket, messages, num_messages,
5597 socket->priv->blocking ? -1 : 0,
5598 cancellable, error);
5602 g_socket_receive_messages_with_timeout (GSocket *socket,
5603 GInputMessage *messages,
5607 GCancellable *cancellable,
5612 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5613 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5614 g_return_val_if_fail (cancellable == NULL ||
5615 G_IS_CANCELLABLE (cancellable), -1);
5616 g_return_val_if_fail (error == NULL || *error == NULL, -1);
5618 start_time = g_get_monotonic_time ();
5620 if (!check_socket (socket, error))
5623 if (!check_timeout (socket, error))
5626 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5629 if (num_messages == 0)
5632 #if !defined (G_OS_WIN32) && defined (HAVE_RECVMMSG)
5634 struct mmsghdr *msgvec;
5635 guint i, num_received;
5637 /* Clamp the number of vectors if more given than we can write in one go.
5638 * The caller has to handle short writes anyway.
5640 if (num_messages > G_IOV_MAX)
5641 num_messages = G_IOV_MAX;
5643 msgvec = g_newa (struct mmsghdr, num_messages);
5645 for (i = 0; i < num_messages; ++i)
5647 GInputMessage *msg = &messages[i];
5648 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5650 input_message_to_msghdr (msg, msg_hdr);
5651 msgvec[i].msg_len = 0;
5654 /* We always set the close-on-exec flag so we don't leak file
5655 * descriptors into child processes. Note that gunixfdmessage.c
5656 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5658 #ifdef MSG_CMSG_CLOEXEC
5659 flags |= MSG_CMSG_CLOEXEC;
5662 for (num_received = 0; num_received < num_messages;)
5666 /* We operate in non-blocking mode and handle the timeout ourselves. */
5667 ret = recvmmsg (socket->priv->fd,
5668 msgvec + num_received,
5669 num_messages - num_received,
5670 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5671 #ifdef MSG_CMSG_CLOEXEC
5672 if (ret < 0 && get_socket_errno () == EINVAL)
5674 /* We must be running on an old kernel. Call without the flag. */
5675 flags &= ~(MSG_CMSG_CLOEXEC);
5676 ret = recvmmsg (socket->priv->fd,
5677 msgvec + num_received,
5678 num_messages - num_received,
5679 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5685 int errsv = get_socket_errno ();
5690 if (timeout_us != 0 &&
5691 (errsv == EWOULDBLOCK ||
5694 if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
5695 cancellable, error))
5697 if (num_received > 0)
5699 g_clear_error (error);
5709 /* If any messages were successfully received, do not error. */
5710 if (num_received > 0)
5713 socket_set_error_lazy (error, errsv,
5714 _("Error receiving message: %s"));
5724 num_received += ret;
5727 for (i = 0; i < num_received; ++i)
5729 input_message_from_msghdr (&msgvec[i].msg_hdr, &messages[i], socket);
5730 messages[i].bytes_received = msgvec[i].msg_len;
5733 return num_received;
5738 gint64 wait_timeout;
5740 wait_timeout = timeout_us;
5742 for (i = 0; i < num_messages; i++)
5744 GInputMessage *msg = &messages[i];
5746 GError *msg_error = NULL;
5748 msg->flags = flags; /* in-out parameter */
5750 len = g_socket_receive_message_with_timeout (socket,
5754 msg->control_messages,
5755 (gint *) msg->num_control_messages,
5761 /* check if we've timed out or how much time to wait at most */
5764 gint64 elapsed = g_get_monotonic_time () - start_time;
5765 wait_timeout = MAX (timeout_us - elapsed, 1);
5769 msg->bytes_received = len;
5772 (g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK) ||
5773 g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)))
5775 g_clear_error (&msg_error);
5779 if (msg_error != NULL)
5781 g_propagate_error (error, msg_error);
5795 * g_socket_receive_message:
5796 * @socket: a #GSocket
5797 * @address: (out) (optional): a pointer to a #GSocketAddress
5799 * @vectors: (array length=num_vectors): an array of #GInputVector structs
5800 * @num_vectors: the number of elements in @vectors, or -1
5801 * @messages: (array length=num_messages) (out) (optional) (nullable): a pointer
5802 * which may be filled with an array of #GSocketControlMessages, or %NULL
5803 * @num_messages: (out): a pointer which will be filled with the number of
5804 * elements in @messages, or %NULL
5805 * @flags: (inout): a pointer to an int containing #GSocketMsgFlags flags,
5806 * which may additionally contain
5807 * [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5808 * @cancellable: a %GCancellable or %NULL
5809 * @error: a #GError pointer, or %NULL
5811 * Receive data from a socket. For receiving multiple messages, see
5812 * g_socket_receive_messages(); for easier use, see
5813 * g_socket_receive() and g_socket_receive_from().
5815 * If @address is non-%NULL then @address will be set equal to the
5816 * source address of the received packet.
5817 * @address is owned by the caller.
5819 * @vector must point to an array of #GInputVector structs and
5820 * @num_vectors must be the length of this array. These structs
5821 * describe the buffers that received data will be scattered into.
5822 * If @num_vectors is -1, then @vectors is assumed to be terminated
5823 * by a #GInputVector with a %NULL buffer pointer.
5825 * As a special case, if @num_vectors is 0 (in which case, @vectors
5826 * may of course be %NULL), then a single byte is received and
5827 * discarded. This is to facilitate the common practice of sending a
5828 * single '\0' byte for the purposes of transferring ancillary data.
5830 * @messages, if non-%NULL, will be set to point to a newly-allocated
5831 * array of #GSocketControlMessage instances or %NULL if no such
5832 * messages was received. These correspond to the control messages
5833 * received from the kernel, one #GSocketControlMessage per message
5834 * from the kernel. This array is %NULL-terminated and must be freed
5835 * by the caller using g_free() after calling g_object_unref() on each
5836 * element. If @messages is %NULL, any control messages received will
5839 * @num_messages, if non-%NULL, will be set to the number of control
5840 * messages received.
5842 * If both @messages and @num_messages are non-%NULL, then
5843 * @num_messages gives the number of #GSocketControlMessage instances
5844 * in @messages (ie: not including the %NULL terminator).
5846 * @flags is an in/out parameter. The commonly available arguments
5847 * for this are available in the #GSocketMsgFlags enum, but the
5848 * values there are the same as the system values, and the flags
5849 * are passed in as-is, so you can pass in system-specific flags too
5850 * (and g_socket_receive_message() may pass system-specific flags out).
5851 * Flags passed in to the parameter affect the receive operation; flags returned
5852 * out of it are relevant to the specific returned message.
5854 * As with g_socket_receive(), data may be discarded if @socket is
5855 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
5856 * provide enough buffer space to read a complete message. You can pass
5857 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
5858 * removing it from the receive queue, but there is no portable way to find
5859 * out the length of the message other than by reading it into a
5860 * sufficiently-large buffer.
5862 * If the socket is in blocking mode the call will block until there
5863 * is some data to receive, the connection is closed, or there is an
5864 * error. If there is no data available and the socket is in
5865 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
5866 * returned. To be notified when data is available, wait for the
5867 * %G_IO_IN condition.
5869 * On error -1 is returned and @error is set accordingly.
5871 * Returns: Number of bytes read, or 0 if the connection was closed by
5872 * the peer, or -1 on error
5877 g_socket_receive_message (GSocket *socket,
5878 GSocketAddress **address,
5879 GInputVector *vectors,
5881 GSocketControlMessage ***messages,
5884 GCancellable *cancellable,
5887 return g_socket_receive_message_with_timeout (socket, address, vectors,
5888 num_vectors, messages,
5889 num_messages, flags,
5890 socket->priv->blocking ? -1 : 0,
5891 cancellable, error);
5895 * g_socket_get_credentials:
5896 * @socket: a #GSocket.
5897 * @error: #GError for error reporting, or %NULL to ignore.
5899 * Returns the credentials of the foreign process connected to this
5900 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
5903 * If this operation isn't supported on the OS, the method fails with
5904 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
5905 * by reading the %SO_PEERCRED option on the underlying socket.
5907 * This method can be expected to be available on the following platforms:
5909 * - Linux since GLib 2.26
5910 * - OpenBSD since GLib 2.30
5911 * - Solaris, Illumos and OpenSolaris since GLib 2.40
5912 * - NetBSD since GLib 2.42
5914 * Other ways to obtain credentials from a foreign peer includes the
5915 * #GUnixCredentialsMessage type and
5916 * g_unix_connection_send_credentials() /
5917 * g_unix_connection_receive_credentials() functions.
5919 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
5920 * that must be freed with g_object_unref().
5925 g_socket_get_credentials (GSocket *socket,
5930 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
5931 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5935 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
5939 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
5940 socklen_t optlen = sizeof (native_creds_buf);
5942 if (getsockopt (socket->priv->fd,
5948 ret = g_credentials_new ();
5949 g_credentials_set_native (ret,
5950 G_CREDENTIALS_NATIVE_TYPE,
5954 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
5956 struct unpcbid cred;
5957 socklen_t optlen = sizeof (cred);
5959 if (getsockopt (socket->priv->fd,
5965 ret = g_credentials_new ();
5966 g_credentials_set_native (ret,
5967 G_CREDENTIALS_NATIVE_TYPE,
5971 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
5973 ucred_t *ucred = NULL;
5975 if (getpeerucred (socket->priv->fd, &ucred) == 0)
5977 ret = g_credentials_new ();
5978 g_credentials_set_native (ret,
5979 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
5985 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
5990 int errsv = get_socket_errno ();
5994 socket_io_error_from_errno (errsv),
5995 _("Unable to read socket credentials: %s"),
5996 socket_strerror (errsv));
6001 g_set_error_literal (error,
6003 G_IO_ERROR_NOT_SUPPORTED,
6004 _("g_socket_get_credentials not implemented for this OS"));
6011 * g_socket_get_option:
6012 * @socket: a #GSocket
6013 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
6014 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
6015 * @value: (out): return location for the option value
6016 * @error: #GError for error reporting, or %NULL to ignore.
6018 * Gets the value of an integer-valued option on @socket, as with
6019 * getsockopt(). (If you need to fetch a non-integer-valued option,
6020 * you will need to call getsockopt() directly.)
6022 * The [<gio/gnetworking.h>][gio-gnetworking.h]
6023 * header pulls in system headers that will define most of the
6024 * standard/portable socket options. For unusual socket protocols or
6025 * platform-dependent options, you may need to include additional
6028 * Note that even for socket options that are a single byte in size,
6029 * @value is still a pointer to a #gint variable, not a #guchar;
6030 * g_socket_get_option() will handle the conversion internally.
6032 * Returns: success or failure. On failure, @error will be set, and
6033 * the system error value (`errno` or WSAGetLastError()) will still
6034 * be set to the result of the getsockopt() call.
6039 g_socket_get_option (GSocket *socket,
6047 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
6050 size = sizeof (gint);
6051 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
6053 int errsv = get_socket_errno ();
6055 g_set_error_literal (error,
6057 socket_io_error_from_errno (errsv),
6058 socket_strerror (errsv));
6060 /* Reset errno in case the caller wants to look at it */
6066 #if G_BYTE_ORDER == G_BIG_ENDIAN
6067 /* If the returned value is smaller than an int then we need to
6068 * slide it over into the low-order bytes of *value.
6070 if (size != sizeof (gint))
6071 *value = *value >> (8 * (sizeof (gint) - size));
6078 * g_socket_set_option:
6079 * @socket: a #GSocket
6080 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
6081 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
6082 * @value: the value to set the option to
6083 * @error: #GError for error reporting, or %NULL to ignore.
6085 * Sets the value of an integer-valued option on @socket, as with
6086 * setsockopt(). (If you need to set a non-integer-valued option,
6087 * you will need to call setsockopt() directly.)
6089 * The [<gio/gnetworking.h>][gio-gnetworking.h]
6090 * header pulls in system headers that will define most of the
6091 * standard/portable socket options. For unusual socket protocols or
6092 * platform-dependent options, you may need to include additional
6095 * Returns: success or failure. On failure, @error will be set, and
6096 * the system error value (`errno` or WSAGetLastError()) will still
6097 * be set to the result of the setsockopt() call.
6102 g_socket_set_option (GSocket *socket,
6110 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
6112 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
6115 #if !defined (__linux__) && !defined (G_OS_WIN32)
6116 /* Linux and Windows let you set a single-byte value from an int,
6117 * but most other platforms don't.
6119 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
6121 #if G_BYTE_ORDER == G_BIG_ENDIAN
6122 value = value << (8 * (sizeof (gint) - 1));
6124 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
6129 errsv = get_socket_errno ();
6131 g_set_error_literal (error,
6133 socket_io_error_from_errno (errsv),
6134 socket_strerror (errsv));