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"
78 #include "gstrfuncsprivate.h"
82 * @short_description: Low-level socket object
84 * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
86 * A #GSocket is a low-level networking primitive. It is a more or less
87 * direct mapping of the BSD socket API in a portable GObject based API.
88 * It supports both the UNIX socket implementations and winsock2 on Windows.
90 * #GSocket is the platform independent base upon which the higher level
91 * network primitives are based. Applications are not typically meant to
92 * use it directly, but rather through classes like #GSocketClient,
93 * #GSocketService and #GSocketConnection. However there may be cases where
94 * direct use of #GSocket is useful.
96 * #GSocket implements the #GInitable interface, so if it is manually constructed
97 * by e.g. g_object_new() you must call g_initable_init() and check the
98 * results before using the object. This is done automatically in
99 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
102 * Sockets operate in two general modes, blocking or non-blocking. When
103 * in blocking mode all operations (which don’t take an explicit blocking
104 * parameter) block until the requested operation
105 * is finished or there is an error. In non-blocking mode all calls that
106 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
107 * To know when a call would successfully run you can call g_socket_condition_check(),
108 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
109 * attach it to a #GMainContext to get callbacks when I/O is possible.
110 * Note that all sockets are always set to non blocking mode in the system, and
111 * blocking mode is emulated in GSocket.
113 * When working in non-blocking mode applications should always be able to
114 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
115 * function said that I/O was possible. This can easily happen in case
116 * of a race condition in the application, but it can also happen for other
117 * reasons. For instance, on Windows a socket is always seen as writable
118 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
120 * #GSockets can be either connection oriented or datagram based.
121 * For connection oriented types you must first establish a connection by
122 * either connecting to an address or accepting a connection from another
123 * address. For connectionless socket types the target/source address is
124 * specified or received in each I/O operation.
126 * All socket file descriptors are set to be close-on-exec.
128 * Note that creating a #GSocket causes the signal %SIGPIPE to be
129 * ignored for the remainder of the program. If you are writing a
130 * command-line utility that uses #GSocket, you may need to take into
131 * account the fact that your program will not automatically be killed
132 * if it tries to write to %stdout after it has been closed.
134 * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
135 * a #GSocket concurrently from multiple threads, you must implement your own
141 static void g_socket_initable_iface_init (GInitableIface *iface);
142 static gboolean g_socket_initable_init (GInitable *initable,
143 GCancellable *cancellable,
146 static void g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface);
147 static gint g_socket_datagram_based_receive_messages (GDatagramBased *self,
148 GInputMessage *messages,
152 GCancellable *cancellable,
154 static gint g_socket_datagram_based_send_messages (GDatagramBased *self,
155 GOutputMessage *messages,
159 GCancellable *cancellable,
161 static GSource *g_socket_datagram_based_create_source (GDatagramBased *self,
162 GIOCondition condition,
163 GCancellable *cancellable);
164 static GIOCondition g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
165 GIOCondition condition);
166 static gboolean g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
167 GIOCondition condition,
169 GCancellable *cancellable,
172 static GSocketAddress *
173 cache_recv_address (GSocket *socket, struct sockaddr *native, size_t native_len);
176 g_socket_receive_message_with_timeout (GSocket *socket,
177 GSocketAddress **address,
178 GInputVector *vectors,
180 GSocketControlMessage ***messages,
184 GCancellable *cancellable,
187 g_socket_receive_messages_with_timeout (GSocket *socket,
188 GInputMessage *messages,
192 GCancellable *cancellable,
195 g_socket_send_messages_with_timeout (GSocket *socket,
196 GOutputMessage *messages,
200 GCancellable *cancellable,
218 PROP_MULTICAST_LOOPBACK,
222 /* Size of the receiver cache for g_socket_receive_from() */
223 #define RECV_ADDR_CACHE_SIZE 8
225 struct _GSocketPrivate
227 GSocketFamily family;
229 GSocketProtocol protocol;
233 GError *construct_error;
234 GSocketAddress *remote_address;
239 guint connected_read : 1;
240 guint connected_write : 1;
243 guint connect_pending : 1;
247 DWORD waiting_result;
251 GList *requested_conditions; /* list of requested GIOCondition * */
252 GMutex win32_source_lock;
253 GCond win32_source_cond;
257 GSocketAddress *addr;
258 struct sockaddr *native;
261 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
264 _G_DEFINE_TYPE_EXTENDED_WITH_PRELUDE (GSocket, g_socket, G_TYPE_OBJECT, 0,
265 /* Need a prelude for https://bugzilla.gnome.org/show_bug.cgi?id=674885 */
266 g_type_ensure (G_TYPE_SOCKET_FAMILY);
267 g_type_ensure (G_TYPE_SOCKET_TYPE);
268 g_type_ensure (G_TYPE_SOCKET_PROTOCOL);
269 g_type_ensure (G_TYPE_SOCKET_ADDRESS);
270 /* And networking init is appropriate for the prelude */
271 g_networking_init ();
272 , /* And now the regular type init code */
273 G_ADD_PRIVATE (GSocket)
274 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
275 g_socket_initable_iface_init);
276 G_IMPLEMENT_INTERFACE (G_TYPE_DATAGRAM_BASED,
277 g_socket_datagram_based_iface_init));
280 get_socket_errno (void)
285 return WSAGetLastError ();
290 socket_io_error_from_errno (int err)
293 return g_io_error_from_win32_error (err);
295 return g_io_error_from_errno (err);
300 socket_strerror (int err)
303 return g_strerror (err);
308 msg = g_win32_error_message (err);
310 msg_ret = g_intern_string (msg);
317 /* Wrapper around g_set_error() to avoid doing excess work */
318 #define socket_set_error_lazy(err, errsv, fmt) \
320 GError **__err = (err); \
321 int __errsv = (errsv); \
325 int __code = socket_io_error_from_errno (__errsv); \
326 const char *__strerr = socket_strerror (__errsv); \
328 if (__code == G_IO_ERROR_WOULD_BLOCK) \
329 g_set_error_literal (__err, G_IO_ERROR, __code, __strerr); \
331 g_set_error (__err, G_IO_ERROR, __code, fmt, __strerr); \
336 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
338 _win32_unset_event_mask (GSocket *socket, int mask)
340 g_mutex_lock (&socket->priv->win32_source_lock);
341 socket->priv->current_events &= ~mask;
342 socket->priv->current_errors &= ~mask;
343 g_mutex_unlock (&socket->priv->win32_source_lock);
346 #define win32_unset_event_mask(_socket, _mask)
349 /* Windows has broken prototypes... */
351 #define getsockopt(sockfd, level, optname, optval, optlen) \
352 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
353 #define setsockopt(sockfd, level, optname, optval, optlen) \
354 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
355 #define getsockname(sockfd, addr, addrlen) \
356 getsockname (sockfd, addr, (int *)addrlen)
357 #define getpeername(sockfd, addr, addrlen) \
358 getpeername (sockfd, addr, (int *)addrlen)
359 #define recv(sockfd, buf, len, flags) \
360 recv (sockfd, (gpointer)buf, len, flags)
364 address_to_string (GSocketAddress *address)
366 GString *ret = g_string_new ("");
368 if (G_IS_INET_SOCKET_ADDRESS (address))
370 GInetSocketAddress *isa = G_INET_SOCKET_ADDRESS (address);
371 GInetAddress *ia = g_inet_socket_address_get_address (isa);
372 GSocketFamily family = g_inet_address_get_family (ia);
375 /* Represent IPv6 addresses in URL style:
376 * ::1 port 12345 -> [::1]:12345 */
377 if (family == G_SOCKET_FAMILY_IPV6)
378 g_string_append_c (ret, '[');
380 tmp = g_inet_address_to_string (ia);
381 g_string_append (ret, tmp);
384 if (family == G_SOCKET_FAMILY_IPV6)
386 guint32 scope = g_inet_socket_address_get_scope_id (isa);
389 g_string_append_printf (ret, "%%%u", scope);
391 g_string_append_c (ret, ']');
394 g_string_append_c (ret, ':');
396 g_string_append_printf (ret, "%u", g_inet_socket_address_get_port (isa));
400 /* For unknown address types, just show the type */
401 g_string_append_printf (ret, "(%s)", G_OBJECT_TYPE_NAME (address));
404 return g_string_free (ret, FALSE);
408 check_socket (GSocket *socket,
411 if (!socket->priv->inited)
413 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
414 _("Invalid socket, not initialized"));
418 if (socket->priv->construct_error)
420 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
421 _("Invalid socket, initialization failed due to: %s"),
422 socket->priv->construct_error->message);
426 if (socket->priv->closed)
428 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
429 _("Socket is already closed"));
437 check_timeout (GSocket *socket,
440 if (socket->priv->timed_out)
442 socket->priv->timed_out = FALSE;
443 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
444 _("Socket I/O timed out"));
452 g_socket_details_from_fd (GSocket *socket)
455 struct sockaddr_storage storage;
463 fd = socket->priv->fd;
464 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
466 errsv = get_socket_errno ();
473 socket->priv->type = G_SOCKET_TYPE_STREAM;
477 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
481 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
485 socket->priv->type = G_SOCKET_TYPE_INVALID;
489 addrlen = sizeof address;
490 if (getsockname (fd, &address.sa, &addrlen) != 0)
492 errsv = get_socket_errno ();
498 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
499 sizeof address.storage.ss_family <= addrlen);
500 family = address.storage.ss_family;
504 /* On Solaris, this happens if the socket is not yet connected.
505 * But we can use SO_DOMAIN as a workaround there.
508 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
510 errsv = get_socket_errno ();
514 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
522 case G_SOCKET_FAMILY_IPV4:
523 case G_SOCKET_FAMILY_IPV6:
524 socket->priv->family = address.storage.ss_family;
525 switch (socket->priv->type)
527 case G_SOCKET_TYPE_STREAM:
528 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
531 case G_SOCKET_TYPE_DATAGRAM:
532 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
535 case G_SOCKET_TYPE_SEQPACKET:
536 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
544 case G_SOCKET_FAMILY_UNIX:
545 socket->priv->family = G_SOCKET_FAMILY_UNIX;
546 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
550 socket->priv->family = G_SOCKET_FAMILY_INVALID;
554 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
556 addrlen = sizeof address;
557 if (getpeername (fd, &address.sa, &addrlen) >= 0)
559 socket->priv->connected_read = TRUE;
560 socket->priv->connected_write = TRUE;
564 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
566 socket->priv->keepalive = !!value;
570 /* Can't read, maybe not supported, assume FALSE */
571 socket->priv->keepalive = FALSE;
577 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
578 socket_io_error_from_errno (errsv),
579 _("creating GSocket from fd: %s"),
580 socket_strerror (errsv));
583 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
585 g_socket (gint domain,
593 fd = socket (domain, type | SOCK_CLOEXEC, protocol);
598 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
599 if (fd < 0 && (errsv == EINVAL || errsv == EPROTOTYPE))
601 fd = socket (domain, type, protocol);
605 errsv = get_socket_errno ();
607 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
608 _("Unable to create socket: %s"), socket_strerror (errsv));
617 /* We always want to set close-on-exec to protect users. If you
618 need to so some weird inheritance to exec you can re-enable this
619 using lower level hacks with g_socket_get_fd(). */
620 flags = fcntl (fd, F_GETFD, 0);
622 (flags & FD_CLOEXEC) == 0)
625 fcntl (fd, F_SETFD, flags);
634 g_socket_create_socket (GSocketFamily family,
643 case G_SOCKET_TYPE_STREAM:
644 native_type = SOCK_STREAM;
647 case G_SOCKET_TYPE_DATAGRAM:
648 native_type = SOCK_DGRAM;
651 case G_SOCKET_TYPE_SEQPACKET:
652 native_type = SOCK_SEQPACKET;
656 g_assert_not_reached ();
661 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
662 _("Unable to create socket: %s"), _("Unknown family was specified"));
668 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
669 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
673 return g_socket (family, native_type, protocol, error);
677 g_socket_constructed (GObject *object)
679 GSocket *socket = G_SOCKET (object);
681 if (socket->priv->fd >= 0)
682 /* create socket->priv info from the fd */
683 g_socket_details_from_fd (socket);
686 /* create the fd from socket->priv info */
687 socket->priv->fd = g_socket_create_socket (socket->priv->family,
689 socket->priv->protocol,
690 &socket->priv->construct_error);
692 if (socket->priv->fd != -1)
695 GError *error = NULL;
700 /* Always use native nonblocking sockets, as Windows sets sockets to
701 * nonblocking automatically in certain operations. This way we make
702 * things work the same on all platforms.
705 if (!g_unix_set_fd_nonblocking (socket->priv->fd, TRUE, &error))
707 g_warning ("Error setting socket nonblocking: %s", error->message);
708 g_clear_error (&error);
713 if (ioctlsocket (socket->priv->fd, FIONBIO, &arg) == SOCKET_ERROR)
715 int errsv = get_socket_errno ();
716 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
721 /* See note about SIGPIPE below. */
722 g_socket_set_option (socket, SOL_SOCKET, SO_NOSIGPIPE, TRUE, NULL);
728 g_socket_get_property (GObject *object,
733 GSocket *socket = G_SOCKET (object);
734 GSocketAddress *address;
739 g_value_set_enum (value, socket->priv->family);
743 g_value_set_enum (value, socket->priv->type);
747 g_value_set_enum (value, socket->priv->protocol);
751 g_value_set_int (value, socket->priv->fd);
755 g_value_set_boolean (value, socket->priv->blocking);
758 case PROP_LISTEN_BACKLOG:
759 g_value_set_int (value, socket->priv->listen_backlog);
763 g_value_set_boolean (value, socket->priv->keepalive);
766 case PROP_LOCAL_ADDRESS:
767 address = g_socket_get_local_address (socket, NULL);
768 g_value_take_object (value, address);
771 case PROP_REMOTE_ADDRESS:
772 address = g_socket_get_remote_address (socket, NULL);
773 g_value_take_object (value, address);
777 g_value_set_uint (value, socket->priv->timeout);
781 g_value_set_uint (value, g_socket_get_ttl (socket));
785 g_value_set_boolean (value, g_socket_get_broadcast (socket));
788 case PROP_MULTICAST_LOOPBACK:
789 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
792 case PROP_MULTICAST_TTL:
793 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
797 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
802 g_socket_set_property (GObject *object,
807 GSocket *socket = G_SOCKET (object);
812 socket->priv->family = g_value_get_enum (value);
816 socket->priv->type = g_value_get_enum (value);
820 socket->priv->protocol = g_value_get_enum (value);
824 socket->priv->fd = g_value_get_int (value);
828 g_socket_set_blocking (socket, g_value_get_boolean (value));
831 case PROP_LISTEN_BACKLOG:
832 g_socket_set_listen_backlog (socket, g_value_get_int (value));
836 g_socket_set_keepalive (socket, g_value_get_boolean (value));
840 g_socket_set_timeout (socket, g_value_get_uint (value));
844 g_socket_set_ttl (socket, g_value_get_uint (value));
848 g_socket_set_broadcast (socket, g_value_get_boolean (value));
851 case PROP_MULTICAST_LOOPBACK:
852 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
855 case PROP_MULTICAST_TTL:
856 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
860 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
865 g_socket_finalize (GObject *object)
867 GSocket *socket = G_SOCKET (object);
870 g_clear_error (&socket->priv->construct_error);
872 if (socket->priv->fd != -1 &&
873 !socket->priv->closed)
874 g_socket_close (socket, NULL);
876 if (socket->priv->remote_address)
877 g_object_unref (socket->priv->remote_address);
880 if (socket->priv->event != WSA_INVALID_EVENT)
882 WSACloseEvent (socket->priv->event);
883 socket->priv->event = WSA_INVALID_EVENT;
886 g_assert (socket->priv->requested_conditions == NULL);
887 g_mutex_clear (&socket->priv->win32_source_lock);
888 g_cond_clear (&socket->priv->win32_source_cond);
891 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
893 if (socket->priv->recv_addr_cache[i].addr)
895 g_object_unref (socket->priv->recv_addr_cache[i].addr);
896 g_free (socket->priv->recv_addr_cache[i].native);
900 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
901 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
905 g_socket_class_init (GSocketClass *klass)
907 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
910 /* There is no portable, thread-safe way to avoid having the process
911 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
912 * forced to simply ignore the signal process-wide.
914 * Even if we ignore it though, gdb will still stop if the app
915 * receives a SIGPIPE, which can be confusing and annoying. So when
916 * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
917 * prevent the signal from occurring at all.
919 signal (SIGPIPE, SIG_IGN);
922 gobject_class->finalize = g_socket_finalize;
923 gobject_class->constructed = g_socket_constructed;
924 gobject_class->set_property = g_socket_set_property;
925 gobject_class->get_property = g_socket_get_property;
927 g_object_class_install_property (gobject_class, PROP_FAMILY,
928 g_param_spec_enum ("family",
930 P_("The sockets address family"),
931 G_TYPE_SOCKET_FAMILY,
932 G_SOCKET_FAMILY_INVALID,
933 G_PARAM_CONSTRUCT_ONLY |
935 G_PARAM_STATIC_STRINGS));
937 g_object_class_install_property (gobject_class, PROP_TYPE,
938 g_param_spec_enum ("type",
940 P_("The sockets type"),
942 G_SOCKET_TYPE_STREAM,
943 G_PARAM_CONSTRUCT_ONLY |
945 G_PARAM_STATIC_STRINGS));
947 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
948 g_param_spec_enum ("protocol",
949 P_("Socket protocol"),
950 P_("The id of the protocol to use, or -1 for unknown"),
951 G_TYPE_SOCKET_PROTOCOL,
952 G_SOCKET_PROTOCOL_UNKNOWN,
953 G_PARAM_CONSTRUCT_ONLY |
955 G_PARAM_STATIC_STRINGS));
957 g_object_class_install_property (gobject_class, PROP_FD,
958 g_param_spec_int ("fd",
959 P_("File descriptor"),
960 P_("The sockets file descriptor"),
964 G_PARAM_CONSTRUCT_ONLY |
966 G_PARAM_STATIC_STRINGS));
968 g_object_class_install_property (gobject_class, PROP_BLOCKING,
969 g_param_spec_boolean ("blocking",
971 P_("Whether or not I/O on this socket is blocking"),
974 G_PARAM_STATIC_STRINGS));
976 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
977 g_param_spec_int ("listen-backlog",
978 P_("Listen backlog"),
979 P_("Outstanding connections in the listen queue"),
984 G_PARAM_STATIC_STRINGS));
986 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
987 g_param_spec_boolean ("keepalive",
988 P_("Keep connection alive"),
989 P_("Keep connection alive by sending periodic pings"),
992 G_PARAM_STATIC_STRINGS));
994 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
995 g_param_spec_object ("local-address",
997 P_("The local address the socket is bound to"),
998 G_TYPE_SOCKET_ADDRESS,
1000 G_PARAM_STATIC_STRINGS));
1002 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
1003 g_param_spec_object ("remote-address",
1004 P_("Remote address"),
1005 P_("The remote address the socket is connected to"),
1006 G_TYPE_SOCKET_ADDRESS,
1008 G_PARAM_STATIC_STRINGS));
1013 * The timeout in seconds on socket I/O
1017 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
1018 g_param_spec_uint ("timeout",
1020 P_("The timeout in seconds on socket I/O"),
1025 G_PARAM_STATIC_STRINGS));
1028 * GSocket:broadcast:
1030 * Whether the socket should allow sending to broadcast addresses.
1034 g_object_class_install_property (gobject_class, PROP_BROADCAST,
1035 g_param_spec_boolean ("broadcast",
1037 P_("Whether to allow sending to broadcast addresses"),
1040 G_PARAM_STATIC_STRINGS));
1045 * Time-to-live for outgoing unicast packets
1049 g_object_class_install_property (gobject_class, PROP_TTL,
1050 g_param_spec_uint ("ttl",
1052 P_("Time-to-live of outgoing unicast packets"),
1055 G_PARAM_STATIC_STRINGS));
1058 * GSocket:multicast-loopback:
1060 * Whether outgoing multicast packets loop back to the local host.
1064 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
1065 g_param_spec_boolean ("multicast-loopback",
1066 P_("Multicast loopback"),
1067 P_("Whether outgoing multicast packets loop back to the local host"),
1070 G_PARAM_STATIC_STRINGS));
1073 * GSocket:multicast-ttl:
1075 * Time-to-live out outgoing multicast packets
1079 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
1080 g_param_spec_uint ("multicast-ttl",
1081 P_("Multicast TTL"),
1082 P_("Time-to-live of outgoing multicast packets"),
1085 G_PARAM_STATIC_STRINGS));
1089 g_socket_initable_iface_init (GInitableIface *iface)
1091 iface->init = g_socket_initable_init;
1095 g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface)
1097 iface->receive_messages = g_socket_datagram_based_receive_messages;
1098 iface->send_messages = g_socket_datagram_based_send_messages;
1099 iface->create_source = g_socket_datagram_based_create_source;
1100 iface->condition_check = g_socket_datagram_based_condition_check;
1101 iface->condition_wait = g_socket_datagram_based_condition_wait;
1105 g_socket_init (GSocket *socket)
1107 socket->priv = g_socket_get_instance_private (socket);
1109 socket->priv->fd = -1;
1110 socket->priv->blocking = TRUE;
1111 socket->priv->listen_backlog = 10;
1112 socket->priv->construct_error = NULL;
1114 socket->priv->event = WSA_INVALID_EVENT;
1115 g_mutex_init (&socket->priv->win32_source_lock);
1116 g_cond_init (&socket->priv->win32_source_cond);
1121 g_socket_initable_init (GInitable *initable,
1122 GCancellable *cancellable,
1127 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
1129 socket = G_SOCKET (initable);
1131 if (cancellable != NULL)
1133 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1134 _("Cancellable initialization not supported"));
1138 socket->priv->inited = TRUE;
1140 if (socket->priv->construct_error)
1143 *error = g_error_copy (socket->priv->construct_error);
1152 check_datagram_based (GDatagramBased *self,
1155 switch (g_socket_get_socket_type (G_SOCKET (self)))
1157 case G_SOCKET_TYPE_INVALID:
1158 case G_SOCKET_TYPE_STREAM:
1159 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1160 _("Cannot use datagram operations on a non-datagram "
1163 case G_SOCKET_TYPE_DATAGRAM:
1164 case G_SOCKET_TYPE_SEQPACKET:
1169 /* Due to us sharing #GSocketSource with the #GSocket implementation, it is
1170 * pretty tricky to split out #GSocket:timeout so that it does not affect
1171 * #GDatagramBased operations (but still affects #GSocket operations). It is
1172 * not worth that effort — just disallow it and require the user to specify
1173 * timeouts on a per-operation basis. */
1174 if (g_socket_get_timeout (G_SOCKET (self)) != 0)
1176 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1177 _("Cannot use datagram operations on a socket with a "
1186 g_socket_datagram_based_receive_messages (GDatagramBased *self,
1187 GInputMessage *messages,
1191 GCancellable *cancellable,
1194 if (!check_datagram_based (self, error))
1197 return g_socket_receive_messages_with_timeout (G_SOCKET (self), messages,
1198 num_messages, flags, timeout_us,
1199 cancellable, error);
1203 g_socket_datagram_based_send_messages (GDatagramBased *self,
1204 GOutputMessage *messages,
1208 GCancellable *cancellable,
1211 if (!check_datagram_based (self, error))
1214 return g_socket_send_messages_with_timeout (G_SOCKET (self), messages,
1215 num_messages, flags, timeout_us,
1216 cancellable, error);
1220 g_socket_datagram_based_create_source (GDatagramBased *self,
1221 GIOCondition condition,
1222 GCancellable *cancellable)
1224 if (!check_datagram_based (self, NULL))
1227 return g_socket_create_source (G_SOCKET (self), condition, cancellable);
1231 g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
1232 GIOCondition condition)
1234 if (!check_datagram_based (datagram_based, NULL))
1237 return g_socket_condition_check (G_SOCKET (datagram_based), condition);
1241 g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
1242 GIOCondition condition,
1244 GCancellable *cancellable,
1247 if (!check_datagram_based (datagram_based, error))
1250 return g_socket_condition_timed_wait (G_SOCKET (datagram_based), condition,
1251 timeout_us, cancellable, error);
1256 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1257 * @type: the socket type to use.
1258 * @protocol: the id of the protocol to use, or 0 for default.
1259 * @error: #GError for error reporting, or %NULL to ignore.
1261 * Creates a new #GSocket with the defined family, type and protocol.
1262 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1263 * for the family and type is used.
1265 * The @protocol is a family and type specific int that specifies what
1266 * kind of protocol to use. #GSocketProtocol lists several common ones.
1267 * Many families only support one protocol, and use 0 for this, others
1268 * support several and using 0 means to use the default protocol for
1269 * the family and type.
1271 * The protocol id is passed directly to the operating
1272 * system, so you can use protocols not listed in #GSocketProtocol if you
1273 * know the protocol number used for it.
1275 * Returns: a #GSocket or %NULL on error.
1276 * Free the returned object with g_object_unref().
1281 g_socket_new (GSocketFamily family,
1283 GSocketProtocol protocol,
1286 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1290 "protocol", protocol,
1295 * g_socket_new_from_fd:
1296 * @fd: a native socket file descriptor.
1297 * @error: #GError for error reporting, or %NULL to ignore.
1299 * Creates a new #GSocket from a native file descriptor
1300 * or winsock SOCKET handle.
1302 * This reads all the settings from the file descriptor so that
1303 * all properties should work. Note that the file descriptor
1304 * will be set to non-blocking mode, independent on the blocking
1305 * mode of the #GSocket.
1307 * On success, the returned #GSocket takes ownership of @fd. On failure, the
1308 * caller must close @fd themselves.
1310 * Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
1311 * descriptor. Instead, a GError will be set with code %G_IO_ERROR_FAILED
1313 * Returns: a #GSocket or %NULL on error.
1314 * Free the returned object with g_object_unref().
1319 g_socket_new_from_fd (gint fd,
1322 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1329 * g_socket_set_blocking:
1330 * @socket: a #GSocket.
1331 * @blocking: Whether to use blocking I/O or not.
1333 * Sets the blocking mode of the socket. In blocking mode
1334 * all operations (which don’t take an explicit blocking parameter) block until
1335 * they succeed or there is an error. In
1336 * non-blocking mode all functions return results immediately or
1337 * with a %G_IO_ERROR_WOULD_BLOCK error.
1339 * All sockets are created in blocking mode. However, note that the
1340 * platform level socket is always non-blocking, and blocking mode
1341 * is a GSocket level feature.
1346 g_socket_set_blocking (GSocket *socket,
1349 g_return_if_fail (G_IS_SOCKET (socket));
1351 blocking = !!blocking;
1353 if (socket->priv->blocking == blocking)
1356 socket->priv->blocking = blocking;
1357 g_object_notify (G_OBJECT (socket), "blocking");
1361 * g_socket_get_blocking:
1362 * @socket: a #GSocket.
1364 * Gets the blocking mode of the socket. For details on blocking I/O,
1365 * see g_socket_set_blocking().
1367 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1372 g_socket_get_blocking (GSocket *socket)
1374 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1376 return socket->priv->blocking;
1380 * g_socket_set_keepalive:
1381 * @socket: a #GSocket.
1382 * @keepalive: Value for the keepalive flag
1384 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1385 * this flag is set on a socket, the system will attempt to verify that the
1386 * remote socket endpoint is still present if a sufficiently long period of
1387 * time passes with no data being exchanged. If the system is unable to
1388 * verify the presence of the remote endpoint, it will automatically close
1391 * This option is only functional on certain kinds of sockets. (Notably,
1392 * %G_SOCKET_PROTOCOL_TCP sockets.)
1394 * The exact time between pings is system- and protocol-dependent, but will
1395 * normally be at least two hours. Most commonly, you would set this flag
1396 * on a server socket if you want to allow clients to remain idle for long
1397 * periods of time, but also want to ensure that connections are eventually
1398 * garbage-collected if clients crash or become unreachable.
1403 g_socket_set_keepalive (GSocket *socket,
1406 GError *error = NULL;
1408 g_return_if_fail (G_IS_SOCKET (socket));
1410 keepalive = !!keepalive;
1411 if (socket->priv->keepalive == keepalive)
1414 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1417 g_warning ("error setting keepalive: %s", error->message);
1418 g_error_free (error);
1422 socket->priv->keepalive = keepalive;
1423 g_object_notify (G_OBJECT (socket), "keepalive");
1427 * g_socket_get_keepalive:
1428 * @socket: a #GSocket.
1430 * Gets the keepalive mode of the socket. For details on this,
1431 * see g_socket_set_keepalive().
1433 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1438 g_socket_get_keepalive (GSocket *socket)
1440 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1442 return socket->priv->keepalive;
1446 * g_socket_get_listen_backlog:
1447 * @socket: a #GSocket.
1449 * Gets the listen backlog setting of the socket. For details on this,
1450 * see g_socket_set_listen_backlog().
1452 * Returns: the maximum number of pending connections.
1457 g_socket_get_listen_backlog (GSocket *socket)
1459 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1461 return socket->priv->listen_backlog;
1465 * g_socket_set_listen_backlog:
1466 * @socket: a #GSocket.
1467 * @backlog: the maximum number of pending connections.
1469 * Sets the maximum number of outstanding connections allowed
1470 * when listening on this socket. If more clients than this are
1471 * connecting to the socket and the application is not handling them
1472 * on time then the new connections will be refused.
1474 * Note that this must be called before g_socket_listen() and has no
1475 * effect if called after that.
1480 g_socket_set_listen_backlog (GSocket *socket,
1483 g_return_if_fail (G_IS_SOCKET (socket));
1484 g_return_if_fail (!socket->priv->listening);
1486 if (backlog != socket->priv->listen_backlog)
1488 socket->priv->listen_backlog = backlog;
1489 g_object_notify (G_OBJECT (socket), "listen-backlog");
1494 * g_socket_get_timeout:
1495 * @socket: a #GSocket.
1497 * Gets the timeout setting of the socket. For details on this, see
1498 * g_socket_set_timeout().
1500 * Returns: the timeout in seconds
1505 g_socket_get_timeout (GSocket *socket)
1507 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1509 return socket->priv->timeout;
1513 * g_socket_set_timeout:
1514 * @socket: a #GSocket.
1515 * @timeout: the timeout for @socket, in seconds, or 0 for none
1517 * Sets the time in seconds after which I/O operations on @socket will
1518 * time out if they have not yet completed.
1520 * On a blocking socket, this means that any blocking #GSocket
1521 * operation will time out after @timeout seconds of inactivity,
1522 * returning %G_IO_ERROR_TIMED_OUT.
1524 * On a non-blocking socket, calls to g_socket_condition_wait() will
1525 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1526 * created with g_socket_create_source() will trigger after
1527 * @timeout seconds of inactivity, with the requested condition
1528 * set, at which point calling g_socket_receive(), g_socket_send(),
1529 * g_socket_check_connect_result(), etc, will fail with
1530 * %G_IO_ERROR_TIMED_OUT.
1532 * If @timeout is 0 (the default), operations will never time out
1535 * Note that if an I/O operation is interrupted by a signal, this may
1536 * cause the timeout to be reset.
1541 g_socket_set_timeout (GSocket *socket,
1544 g_return_if_fail (G_IS_SOCKET (socket));
1546 if (timeout != socket->priv->timeout)
1548 socket->priv->timeout = timeout;
1549 g_object_notify (G_OBJECT (socket), "timeout");
1555 * @socket: a #GSocket.
1557 * Gets the unicast time-to-live setting on @socket; see
1558 * g_socket_set_ttl() for more details.
1560 * Returns: the time-to-live setting on @socket
1565 g_socket_get_ttl (GSocket *socket)
1567 GError *error = NULL;
1570 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1572 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1574 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1577 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1579 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1583 g_return_val_if_reached (0);
1587 g_warning ("error getting unicast ttl: %s", error->message);
1588 g_error_free (error);
1597 * @socket: a #GSocket.
1598 * @ttl: the time-to-live value for all unicast packets on @socket
1600 * Sets the time-to-live for outgoing unicast packets on @socket.
1601 * By default the platform-specific default value is used.
1606 g_socket_set_ttl (GSocket *socket,
1609 GError *error = NULL;
1611 g_return_if_fail (G_IS_SOCKET (socket));
1613 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1615 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1618 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1620 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1622 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1626 g_return_if_reached ();
1630 g_warning ("error setting unicast ttl: %s", error->message);
1631 g_error_free (error);
1635 g_object_notify (G_OBJECT (socket), "ttl");
1639 * g_socket_get_broadcast:
1640 * @socket: a #GSocket.
1642 * Gets the broadcast setting on @socket; if %TRUE,
1643 * it is possible to send packets to broadcast
1646 * Returns: the broadcast setting on @socket
1651 g_socket_get_broadcast (GSocket *socket)
1653 GError *error = NULL;
1656 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1658 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1661 g_warning ("error getting broadcast: %s", error->message);
1662 g_error_free (error);
1670 * g_socket_set_broadcast:
1671 * @socket: a #GSocket.
1672 * @broadcast: whether @socket should allow sending to broadcast
1675 * Sets whether @socket should allow sending to broadcast addresses.
1676 * This is %FALSE by default.
1681 g_socket_set_broadcast (GSocket *socket,
1684 GError *error = NULL;
1686 g_return_if_fail (G_IS_SOCKET (socket));
1688 broadcast = !!broadcast;
1690 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1693 g_warning ("error setting broadcast: %s", error->message);
1694 g_error_free (error);
1698 g_object_notify (G_OBJECT (socket), "broadcast");
1702 * g_socket_get_multicast_loopback:
1703 * @socket: a #GSocket.
1705 * Gets the multicast loopback setting on @socket; if %TRUE (the
1706 * default), outgoing multicast packets will be looped back to
1707 * multicast listeners on the same host.
1709 * Returns: the multicast loopback setting on @socket
1714 g_socket_get_multicast_loopback (GSocket *socket)
1716 GError *error = NULL;
1719 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1721 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1723 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1726 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1728 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1732 g_return_val_if_reached (FALSE);
1736 g_warning ("error getting multicast loopback: %s", error->message);
1737 g_error_free (error);
1745 * g_socket_set_multicast_loopback:
1746 * @socket: a #GSocket.
1747 * @loopback: whether @socket should receive messages sent to its
1748 * multicast groups from the local host
1750 * Sets whether outgoing multicast packets will be received by sockets
1751 * listening on that multicast address on the same host. This is %TRUE
1757 g_socket_set_multicast_loopback (GSocket *socket,
1760 GError *error = NULL;
1762 g_return_if_fail (G_IS_SOCKET (socket));
1764 loopback = !!loopback;
1766 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1768 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1771 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1773 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1775 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1779 g_return_if_reached ();
1783 g_warning ("error setting multicast loopback: %s", error->message);
1784 g_error_free (error);
1788 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1792 * g_socket_get_multicast_ttl:
1793 * @socket: a #GSocket.
1795 * Gets the multicast time-to-live setting on @socket; see
1796 * g_socket_set_multicast_ttl() for more details.
1798 * Returns: the multicast time-to-live setting on @socket
1803 g_socket_get_multicast_ttl (GSocket *socket)
1805 GError *error = NULL;
1808 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1810 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1812 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1815 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1817 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1821 g_return_val_if_reached (FALSE);
1825 g_warning ("error getting multicast ttl: %s", error->message);
1826 g_error_free (error);
1834 * g_socket_set_multicast_ttl:
1835 * @socket: a #GSocket.
1836 * @ttl: the time-to-live value for all multicast datagrams on @socket
1838 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1839 * By default, this is 1, meaning that multicast packets will not leave
1840 * the local network.
1845 g_socket_set_multicast_ttl (GSocket *socket,
1848 GError *error = NULL;
1850 g_return_if_fail (G_IS_SOCKET (socket));
1852 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1854 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1857 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1859 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1861 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1865 g_return_if_reached ();
1869 g_warning ("error setting multicast ttl: %s", error->message);
1870 g_error_free (error);
1874 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1878 * g_socket_get_family:
1879 * @socket: a #GSocket.
1881 * Gets the socket family of the socket.
1883 * Returns: a #GSocketFamily
1888 g_socket_get_family (GSocket *socket)
1890 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1892 return socket->priv->family;
1896 * g_socket_get_socket_type:
1897 * @socket: a #GSocket.
1899 * Gets the socket type of the socket.
1901 * Returns: a #GSocketType
1906 g_socket_get_socket_type (GSocket *socket)
1908 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1910 return socket->priv->type;
1914 * g_socket_get_protocol:
1915 * @socket: a #GSocket.
1917 * Gets the socket protocol id the socket was created with.
1918 * In case the protocol is unknown, -1 is returned.
1920 * Returns: a protocol id, or -1 if unknown
1925 g_socket_get_protocol (GSocket *socket)
1927 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1929 return socket->priv->protocol;
1934 * @socket: a #GSocket.
1936 * Returns the underlying OS socket object. On unix this
1937 * is a socket file descriptor, and on Windows this is
1938 * a Winsock2 SOCKET handle. This may be useful for
1939 * doing platform specific or otherwise unusual operations
1942 * Returns: the file descriptor of the socket.
1947 g_socket_get_fd (GSocket *socket)
1949 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1951 return socket->priv->fd;
1955 * g_socket_get_local_address:
1956 * @socket: a #GSocket.
1957 * @error: #GError for error reporting, or %NULL to ignore.
1959 * Try to get the local address of a bound socket. This is only
1960 * useful if the socket has been bound to a local address,
1961 * either explicitly or implicitly when connecting.
1963 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1964 * Free the returned object with g_object_unref().
1969 g_socket_get_local_address (GSocket *socket,
1973 struct sockaddr_storage storage;
1976 guint len = sizeof (buffer);
1978 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1980 if (getsockname (socket->priv->fd, &buffer.sa, &len) < 0)
1982 int errsv = get_socket_errno ();
1983 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1984 _("could not get local address: %s"), socket_strerror (errsv));
1988 return g_socket_address_new_from_native (&buffer.storage, len);
1992 * g_socket_get_remote_address:
1993 * @socket: a #GSocket.
1994 * @error: #GError for error reporting, or %NULL to ignore.
1996 * Try to get the remote address of a connected socket. This is only
1997 * useful for connection oriented sockets that have been connected.
1999 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
2000 * Free the returned object with g_object_unref().
2005 g_socket_get_remote_address (GSocket *socket,
2009 struct sockaddr_storage storage;
2012 guint len = sizeof (buffer);
2014 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2016 if (socket->priv->connect_pending)
2018 if (!g_socket_check_connect_result (socket, error))
2021 socket->priv->connect_pending = FALSE;
2024 if (!socket->priv->remote_address)
2026 if (getpeername (socket->priv->fd, &buffer.sa, &len) < 0)
2028 int errsv = get_socket_errno ();
2029 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2030 _("could not get remote address: %s"), socket_strerror (errsv));
2034 socket->priv->remote_address = g_socket_address_new_from_native (&buffer.storage, len);
2037 return g_object_ref (socket->priv->remote_address);
2041 * g_socket_is_connected:
2042 * @socket: a #GSocket.
2044 * Check whether the socket is connected. This is only useful for
2045 * connection-oriented sockets.
2047 * If using g_socket_shutdown(), this function will return %TRUE until the
2048 * socket has been shut down for reading and writing. If you do a non-blocking
2049 * connect, this function will not return %TRUE until after you call
2050 * g_socket_check_connect_result().
2052 * Returns: %TRUE if socket is connected, %FALSE otherwise.
2057 g_socket_is_connected (GSocket *socket)
2059 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2061 return (socket->priv->connected_read || socket->priv->connected_write);
2066 * @socket: a #GSocket.
2067 * @error: #GError for error reporting, or %NULL to ignore.
2069 * Marks the socket as a server socket, i.e. a socket that is used
2070 * to accept incoming requests using g_socket_accept().
2072 * Before calling this the socket must be bound to a local address using
2075 * To set the maximum amount of outstanding clients, use
2076 * g_socket_set_listen_backlog().
2078 * Returns: %TRUE on success, %FALSE on error.
2083 g_socket_listen (GSocket *socket,
2086 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2088 if (!check_socket (socket, error))
2091 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
2093 int errsv = get_socket_errno ();
2095 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2096 _("could not listen: %s"), socket_strerror (errsv));
2100 socket->priv->listening = TRUE;
2107 * @socket: a #GSocket.
2108 * @address: a #GSocketAddress specifying the local address.
2109 * @allow_reuse: whether to allow reusing this address
2110 * @error: #GError for error reporting, or %NULL to ignore.
2112 * When a socket is created it is attached to an address family, but it
2113 * doesn't have an address in this family. g_socket_bind() assigns the
2114 * address (sometimes called name) of the socket.
2116 * It is generally required to bind to a local address before you can
2117 * receive connections. (See g_socket_listen() and g_socket_accept() ).
2118 * In certain situations, you may also want to bind a socket that will be
2119 * used to initiate connections, though this is not normally required.
2121 * If @socket is a TCP socket, then @allow_reuse controls the setting
2122 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
2123 * server sockets (sockets that you will eventually call
2124 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
2125 * set this flag on a server socket may cause g_socket_bind() to return
2126 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
2127 * immediately restarted.)
2129 * If @socket is a UDP socket, then @allow_reuse determines whether or
2130 * not other UDP sockets can be bound to the same address at the same
2131 * time. In particular, you can have several UDP sockets bound to the
2132 * same address, and they will all receive all of the multicast and
2133 * broadcast packets sent to that address. (The behavior of unicast
2134 * UDP packets to an address with multiple listeners is not defined.)
2136 * Returns: %TRUE on success, %FALSE on error.
2141 g_socket_bind (GSocket *socket,
2142 GSocketAddress *address,
2143 gboolean reuse_address,
2147 struct sockaddr_storage storage;
2150 gboolean so_reuseaddr;
2152 gboolean so_reuseport;
2155 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2157 if (!check_socket (socket, error))
2160 if (!g_socket_address_to_native (address, &addr.storage, sizeof addr, error))
2163 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
2164 * sockets, but has nasty side effects we don't want for TCP
2167 * On other platforms, we set SO_REUSEPORT, if it exists, for
2168 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
2169 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
2170 * the desired semantics on UDP (as it does on Linux, although
2171 * Linux has SO_REUSEPORT too as of 3.9).
2175 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2177 so_reuseaddr = !!reuse_address;
2181 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2184 /* Ignore errors here, the only likely error is "not supported", and
2185 * this is a "best effort" thing mainly.
2187 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
2189 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
2192 if (bind (socket->priv->fd, &addr.sa,
2193 g_socket_address_get_native_size (address)) < 0)
2195 int errsv = get_socket_errno ();
2196 gchar *address_string = address_to_string (address);
2199 G_IO_ERROR, socket_io_error_from_errno (errsv),
2200 _("Error binding to address %s: %s"),
2201 address_string, socket_strerror (errsv));
2202 g_free (address_string);
2211 g_socket_w32_get_adapter_ipv4_addr (const gchar *name_or_ip)
2213 ULONG bufsize = 15000; /* MS-recommended initial bufsize */
2214 DWORD ret = ERROR_BUFFER_OVERFLOW;
2215 unsigned int malloc_iterations = 0;
2216 PIP_ADAPTER_ADDRESSES addr_buf = NULL, eth_adapter;
2217 wchar_t *wchar_name_or_ip = NULL;
2219 NET_IFINDEX if_index;
2222 * For Windows OS only - return adapter IPv4 address in network byte order.
2224 * Input string can be either friendly name of adapter, IP address of adapter,
2225 * indextoname, or fullname of adapter.
2227 * 192.168.1.109 ===> IP address given directly,
2228 * convert directly with inet_addr() function
2229 * Wi-Fi ===> Adapter friendly name "Wi-Fi",
2230 * scan with GetAdapterAddresses and adapter->FriendlyName
2231 * ethernet_32774 ===> Adapter name as returned by if_indextoname
2232 * {33E8F5CD-BAEA-4214-BE13-B79AB8080CAB} ===> Adaptername,
2233 * as returned in GetAdapterAddresses and adapter->AdapterName
2236 /* Step 1: Check if string is an IP address: */
2237 ip_result = inet_addr (name_or_ip);
2238 if (ip_result != INADDR_NONE)
2239 return ip_result; /* Success, IP address string was given directly */
2242 * Step 2: Check if name represents a valid Interface index (e.g. ethernet_75521)
2243 * function if_nametoindex will return >=1 if a valid index, or 0=no match
2244 * valid index will be used later in GetAdaptersAddress loop for lookup of adapter IP address
2246 if_index = if_nametoindex (name_or_ip);
2248 /* Step 3: Prepare wchar string for friendly name comparison */
2251 size_t if_name_len = strlen (name_or_ip);
2252 if (if_name_len >= MAX_ADAPTER_NAME_LENGTH + 4)
2254 /* Name-check only needed if index=0... */
2255 wchar_name_or_ip = (wchar_t *) g_try_malloc ((if_name_len + 1) * sizeof(wchar_t));
2256 if (wchar_name_or_ip)
2257 mbstowcs (wchar_name_or_ip, name_or_ip, if_name_len + 1);
2258 /* NOTE: Even if malloc fails here, some comparisons can still be done later... so no exit here! */
2262 * Step 4: Allocate memory and get adapter addresses.
2263 * Buffer allocation loop recommended by MS, since size can be dynamic
2264 * https://docs.microsoft.com/en-us/windows/desktop/api/iphlpapi/nf-iphlpapi-getadaptersaddresses
2266 #define MAX_ALLOC_ITERATIONS 3
2269 malloc_iterations++;
2270 addr_buf = (PIP_ADAPTER_ADDRESSES) g_try_realloc (addr_buf, bufsize);
2272 ret = GetAdaptersAddresses (AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, addr_buf, &bufsize);
2275 ret == ERROR_BUFFER_OVERFLOW &&
2276 malloc_iterations < MAX_ALLOC_ITERATIONS);
2277 #undef MAX_ALLOC_ITERATIONS
2279 if (addr_buf == 0 || ret != NO_ERROR)
2282 g_free (wchar_name_or_ip);
2286 /* Step 5: Loop through adapters and check match for index or name */
2287 for (eth_adapter = addr_buf; eth_adapter != NULL; eth_adapter = eth_adapter->Next)
2289 /* Check if match for interface index/name: */
2290 gboolean any_match = (if_index > 0) && (eth_adapter->IfIndex == if_index);
2292 /* Check if match for friendly name - but only if NO if_index! */
2293 if (!any_match && if_index == 0 && eth_adapter->FriendlyName &&
2294 eth_adapter->FriendlyName[0] != 0 && wchar_name_or_ip != NULL)
2295 any_match = (_wcsicmp (eth_adapter->FriendlyName, wchar_name_or_ip) == 0);
2297 /* Check if match for adapter low level name - but only if NO if_index: */
2298 if (!any_match && if_index == 0 && eth_adapter->AdapterName &&
2299 eth_adapter->AdapterName[0] != 0)
2300 any_match = (stricmp (eth_adapter->AdapterName, name_or_ip) == 0);
2304 /* We have match for this adapter, lets get its local unicast IP address! */
2305 PIP_ADAPTER_UNICAST_ADDRESS uni_addr;
2306 for (uni_addr = eth_adapter->FirstUnicastAddress;
2307 uni_addr != NULL; uni_addr = uni_addr->Next)
2309 if (uni_addr->Address.lpSockaddr->sa_family == AF_INET)
2311 ip_result = ((PSOCKADDR_IN) uni_addr->Address.lpSockaddr)->sin_addr.S_un.S_addr;
2312 break; /* finished, exit unicast addr loop */
2319 g_free (wchar_name_or_ip);
2326 g_socket_multicast_group_operation (GSocket *socket,
2327 GInetAddress *group,
2328 gboolean source_specific,
2330 gboolean join_group,
2333 const guint8 *native_addr;
2334 gint optname, result;
2336 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2337 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2338 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2340 if (!check_socket (socket, error))
2343 native_addr = g_inet_address_to_bytes (group);
2344 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2346 #ifdef HAVE_IP_MREQN
2347 struct ip_mreqn mc_req;
2349 struct ip_mreq mc_req;
2352 memset (&mc_req, 0, sizeof (mc_req));
2353 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2355 #ifdef HAVE_IP_MREQN
2357 mc_req.imr_ifindex = if_nametoindex (iface);
2359 mc_req.imr_ifindex = 0; /* Pick any. */
2360 #elif defined(G_OS_WIN32)
2362 mc_req.imr_interface.s_addr = g_socket_w32_get_adapter_ipv4_addr (iface);
2364 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2366 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2369 if (source_specific)
2371 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2372 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2374 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2376 _("Error joining multicast group: %s") :
2377 _("Error leaving multicast group: %s"),
2378 _("No support for source-specific multicast"));
2383 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2384 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2385 &mc_req, sizeof (mc_req));
2387 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2389 struct ipv6_mreq mc_req_ipv6;
2391 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2392 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2393 #ifdef HAVE_IF_NAMETOINDEX
2395 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2398 mc_req_ipv6.ipv6mr_interface = 0;
2400 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2401 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2402 &mc_req_ipv6, sizeof (mc_req_ipv6));
2405 g_return_val_if_reached (FALSE);
2409 int errsv = get_socket_errno ();
2411 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2413 _("Error joining multicast group: %s") :
2414 _("Error leaving multicast group: %s"),
2415 socket_strerror (errsv));
2423 * g_socket_join_multicast_group:
2424 * @socket: a #GSocket.
2425 * @group: a #GInetAddress specifying the group address to join.
2426 * @iface: (nullable): Name of the interface to use, or %NULL
2427 * @source_specific: %TRUE if source-specific multicast should be used
2428 * @error: #GError for error reporting, or %NULL to ignore.
2430 * Registers @socket to receive multicast messages sent to @group.
2431 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2432 * been bound to an appropriate interface and port with
2435 * If @iface is %NULL, the system will automatically pick an interface
2436 * to bind to based on @group.
2438 * If @source_specific is %TRUE, source-specific multicast as defined
2439 * in RFC 4604 is used. Note that on older platforms this may fail
2440 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2442 * To bind to a given source-specific multicast address, use
2443 * g_socket_join_multicast_group_ssm() instead.
2445 * Returns: %TRUE on success, %FALSE on error.
2450 g_socket_join_multicast_group (GSocket *socket,
2451 GInetAddress *group,
2452 gboolean source_specific,
2456 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2460 * g_socket_leave_multicast_group:
2461 * @socket: a #GSocket.
2462 * @group: a #GInetAddress specifying the group address to leave.
2463 * @iface: (nullable): Interface used
2464 * @source_specific: %TRUE if source-specific multicast was used
2465 * @error: #GError for error reporting, or %NULL to ignore.
2467 * Removes @socket from the multicast group defined by @group, @iface,
2468 * and @source_specific (which must all have the same values they had
2469 * when you joined the group).
2471 * @socket remains bound to its address and port, and can still receive
2472 * unicast messages after calling this.
2474 * To unbind to a given source-specific multicast address, use
2475 * g_socket_leave_multicast_group_ssm() instead.
2477 * Returns: %TRUE on success, %FALSE on error.
2482 g_socket_leave_multicast_group (GSocket *socket,
2483 GInetAddress *group,
2484 gboolean source_specific,
2488 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2492 g_socket_multicast_group_operation_ssm (GSocket *socket,
2493 GInetAddress *group,
2494 GInetAddress *source_specific,
2496 gboolean join_group,
2501 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2502 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2503 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2504 g_return_val_if_fail (iface == NULL || *iface != '\0', FALSE);
2505 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2507 if (!source_specific)
2509 return g_socket_multicast_group_operation (socket, group, FALSE, iface,
2513 if (!check_socket (socket, error))
2516 switch (g_inet_address_get_family (group))
2518 case G_SOCKET_FAMILY_INVALID:
2519 case G_SOCKET_FAMILY_UNIX:
2521 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2523 _("Error joining multicast group: %s") :
2524 _("Error leaving multicast group: %s"),
2525 _("Unsupported socket family"));
2530 case G_SOCKET_FAMILY_IPV4:
2532 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2534 #ifdef BROKEN_IP_MREQ_SOURCE_STRUCT
2535 #define S_ADDR_FIELD(src) src.imr_interface
2537 #define S_ADDR_FIELD(src) src.imr_interface.s_addr
2541 struct ip_mreq_source mc_req_src;
2543 if (g_inet_address_get_family (source_specific) !=
2544 G_SOCKET_FAMILY_IPV4)
2546 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2548 _("Error joining multicast group: %s") :
2549 _("Error leaving multicast group: %s"),
2550 _("source-specific not an IPv4 address"));
2554 memset (&mc_req_src, 0, sizeof (mc_req_src));
2556 /* By default use the default IPv4 multicast interface. */
2557 S_ADDR_FIELD(mc_req_src) = g_htonl (INADDR_ANY);
2561 #if defined(G_OS_WIN32)
2562 S_ADDR_FIELD(mc_req_src) = g_socket_w32_get_adapter_ipv4_addr (iface);
2563 #elif defined (HAVE_SIOCGIFADDR)
2566 struct sockaddr_in *iface_addr;
2567 size_t if_name_len = strlen (iface);
2569 memset (&ifr, 0, sizeof (ifr));
2571 if (if_name_len >= sizeof (ifr.ifr_name))
2573 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FILENAME_TOO_LONG,
2574 _("Interface name too long"));
2578 memcpy (ifr.ifr_name, iface, if_name_len);
2580 /* Get the IPv4 address of the given network interface name. */
2581 ret = ioctl (socket->priv->fd, SIOCGIFADDR, &ifr);
2586 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2587 _("Interface not found: %s"), g_strerror (errsv));
2591 iface_addr = (struct sockaddr_in *) &ifr.ifr_addr;
2592 S_ADDR_FIELD(mc_req_src) = iface_addr->sin_addr.s_addr;
2593 #endif /* defined(G_OS_WIN32) && defined (HAVE_IF_NAMETOINDEX) */
2595 memcpy (&mc_req_src.imr_multiaddr, g_inet_address_to_bytes (group),
2596 g_inet_address_get_native_size (group));
2597 memcpy (&mc_req_src.imr_sourceaddr,
2598 g_inet_address_to_bytes (source_specific),
2599 g_inet_address_get_native_size (source_specific));
2602 join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2603 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2604 &mc_req_src, sizeof (mc_req_src));
2609 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2611 _("Error joining multicast group: %s") :
2612 _("Error leaving multicast group: %s"),
2613 _("No support for IPv4 source-specific multicast"));
2615 #endif /* IP_ADD_SOURCE_MEMBERSHIP */
2619 case G_SOCKET_FAMILY_IPV6:
2621 #ifdef MCAST_JOIN_SOURCE_GROUP
2624 struct group_source_req mc_req_src;
2625 GSocketAddress *saddr_group, *saddr_source_specific;
2626 guint iface_index = 0;
2628 #if defined (HAVE_IF_NAMETOINDEX)
2631 iface_index = if_nametoindex (iface);
2632 if (iface_index == 0)
2636 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2637 _("Interface not found: %s"), g_strerror (errsv));
2641 #endif /* defined (HAVE_IF_NAMETOINDEX) */
2642 mc_req_src.gsr_interface = iface_index;
2644 saddr_group = g_inet_socket_address_new (group, 0);
2645 res = g_socket_address_to_native (saddr_group, &mc_req_src.gsr_group,
2646 sizeof (mc_req_src.gsr_group),
2648 g_object_unref (saddr_group);
2652 saddr_source_specific = g_inet_socket_address_new (source_specific, 0);
2653 res = g_socket_address_to_native (saddr_source_specific,
2654 &mc_req_src.gsr_source,
2655 sizeof (mc_req_src.gsr_source),
2657 g_object_unref (saddr_source_specific);
2663 join_group ? MCAST_JOIN_SOURCE_GROUP : MCAST_LEAVE_SOURCE_GROUP;
2664 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2665 &mc_req_src, sizeof (mc_req_src));
2667 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2669 _("Error joining multicast group: %s") :
2670 _("Error leaving multicast group: %s"),
2671 _("No support for IPv6 source-specific multicast"));
2673 #endif /* MCAST_JOIN_SOURCE_GROUP */
2678 g_return_val_if_reached (FALSE);
2683 int errsv = get_socket_errno ();
2685 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2687 _("Error joining multicast group: %s") :
2688 _("Error leaving multicast group: %s"),
2689 socket_strerror (errsv));
2697 * g_socket_join_multicast_group_ssm:
2698 * @socket: a #GSocket.
2699 * @group: a #GInetAddress specifying the group address to join.
2700 * @source_specific: (nullable): a #GInetAddress specifying the
2701 * source-specific multicast address or %NULL to ignore.
2702 * @iface: (nullable): Name of the interface to use, or %NULL
2703 * @error: #GError for error reporting, or %NULL to ignore.
2705 * Registers @socket to receive multicast messages sent to @group.
2706 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2707 * been bound to an appropriate interface and port with
2710 * If @iface is %NULL, the system will automatically pick an interface
2711 * to bind to based on @group.
2713 * If @source_specific is not %NULL, use source-specific multicast as
2714 * defined in RFC 4604. Note that on older platforms this may fail
2715 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2717 * Note that this function can be called multiple times for the same
2718 * @group with different @source_specific in order to receive multicast
2719 * packets from more than one source.
2721 * Returns: %TRUE on success, %FALSE on error.
2726 g_socket_join_multicast_group_ssm (GSocket *socket,
2727 GInetAddress *group,
2728 GInetAddress *source_specific,
2732 return g_socket_multicast_group_operation_ssm (socket, group,
2733 source_specific, iface, TRUE, error);
2737 * g_socket_leave_multicast_group_ssm:
2738 * @socket: a #GSocket.
2739 * @group: a #GInetAddress specifying the group address to leave.
2740 * @source_specific: (nullable): a #GInetAddress specifying the
2741 * source-specific multicast address or %NULL to ignore.
2742 * @iface: (nullable): Name of the interface to use, or %NULL
2743 * @error: #GError for error reporting, or %NULL to ignore.
2745 * Removes @socket from the multicast group defined by @group, @iface,
2746 * and @source_specific (which must all have the same values they had
2747 * when you joined the group).
2749 * @socket remains bound to its address and port, and can still receive
2750 * unicast messages after calling this.
2752 * Returns: %TRUE on success, %FALSE on error.
2757 g_socket_leave_multicast_group_ssm (GSocket *socket,
2758 GInetAddress *group,
2759 GInetAddress *source_specific,
2763 return g_socket_multicast_group_operation_ssm (socket, group,
2764 source_specific, iface, FALSE, error);
2768 * g_socket_speaks_ipv4:
2769 * @socket: a #GSocket
2771 * Checks if a socket is capable of speaking IPv4.
2773 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2774 * and under some combinations of circumstances IPv6 sockets are also
2775 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2778 * No other types of sockets are currently considered as being capable
2781 * Returns: %TRUE if this socket can be used with IPv4.
2786 g_socket_speaks_ipv4 (GSocket *socket)
2788 switch (socket->priv->family)
2790 case G_SOCKET_FAMILY_IPV4:
2793 case G_SOCKET_FAMILY_IPV6:
2794 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2798 if (!g_socket_get_option (socket,
2799 IPPROTO_IPV6, IPV6_V6ONLY,
2816 * @socket: a #GSocket.
2817 * @cancellable: (nullable): a %GCancellable or %NULL
2818 * @error: #GError for error reporting, or %NULL to ignore.
2820 * Accept incoming connections on a connection-based socket. This removes
2821 * the first outstanding connection request from the listening socket and
2822 * creates a #GSocket object for it.
2824 * The @socket must be bound to a local address with g_socket_bind() and
2825 * must be listening for incoming connections (g_socket_listen()).
2827 * If there are no outstanding connections then the operation will block
2828 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2829 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2831 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2832 * Free the returned object with g_object_unref().
2837 g_socket_accept (GSocket *socket,
2838 GCancellable *cancellable,
2841 GSocket *new_socket;
2844 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2846 if (!check_socket (socket, error))
2849 if (!check_timeout (socket, error))
2854 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2856 int errsv = get_socket_errno ();
2861 #ifdef WSAEWOULDBLOCK
2862 if (errsv == WSAEWOULDBLOCK)
2864 if (errsv == EWOULDBLOCK ||
2868 win32_unset_event_mask (socket, FD_ACCEPT);
2870 if (socket->priv->blocking)
2872 if (!g_socket_condition_wait (socket,
2873 G_IO_IN, cancellable, error))
2880 socket_set_error_lazy (error, errsv, _("Error accepting connection: %s"));
2886 win32_unset_event_mask (socket, FD_ACCEPT);
2890 /* The socket inherits the accepting sockets event mask and even object,
2891 we need to remove that */
2892 WSAEventSelect (ret, NULL, 0);
2898 /* We always want to set close-on-exec to protect users. If you
2899 need to so some weird inheritance to exec you can re-enable this
2900 using lower level hacks with g_socket_get_fd(). */
2901 flags = fcntl (ret, F_GETFD, 0);
2903 (flags & FD_CLOEXEC) == 0)
2905 flags |= FD_CLOEXEC;
2906 fcntl (ret, F_SETFD, flags);
2911 new_socket = g_socket_new_from_fd (ret, error);
2912 if (new_socket == NULL)
2921 new_socket->priv->protocol = socket->priv->protocol;
2928 * @socket: a #GSocket.
2929 * @address: a #GSocketAddress specifying the remote address.
2930 * @cancellable: (nullable): a %GCancellable or %NULL
2931 * @error: #GError for error reporting, or %NULL to ignore.
2933 * Connect the socket to the specified remote address.
2935 * For connection oriented socket this generally means we attempt to make
2936 * a connection to the @address. For a connection-less socket it sets
2937 * the default address for g_socket_send() and discards all incoming datagrams
2938 * from other sources.
2940 * Generally connection oriented sockets can only connect once, but
2941 * connection-less sockets can connect multiple times to change the
2944 * If the connect call needs to do network I/O it will block, unless
2945 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2946 * and the user can be notified of the connection finishing by waiting
2947 * for the G_IO_OUT condition. The result of the connection must then be
2948 * checked with g_socket_check_connect_result().
2950 * Returns: %TRUE if connected, %FALSE on error.
2955 g_socket_connect (GSocket *socket,
2956 GSocketAddress *address,
2957 GCancellable *cancellable,
2961 struct sockaddr_storage storage;
2965 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2967 if (!check_socket (socket, error))
2970 if (!g_socket_address_to_native (address, &buffer.storage, sizeof buffer, error))
2973 if (socket->priv->remote_address)
2974 g_object_unref (socket->priv->remote_address);
2975 socket->priv->remote_address = g_object_ref (address);
2979 if (connect (socket->priv->fd, &buffer.sa,
2980 g_socket_address_get_native_size (address)) < 0)
2982 int errsv = get_socket_errno ();
2988 if (errsv == EINPROGRESS)
2990 if (errsv == WSAEWOULDBLOCK)
2993 win32_unset_event_mask (socket, FD_CONNECT);
2995 if (socket->priv->blocking)
2997 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2999 if (g_socket_check_connect_result (socket, error))
3005 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
3006 _("Connection in progress"));
3007 socket->priv->connect_pending = TRUE;
3011 g_set_error_literal (error, G_IO_ERROR,
3012 socket_io_error_from_errno (errsv),
3013 socket_strerror (errsv));
3020 win32_unset_event_mask (socket, FD_CONNECT);
3022 socket->priv->connected_read = TRUE;
3023 socket->priv->connected_write = TRUE;
3029 * g_socket_check_connect_result:
3030 * @socket: a #GSocket
3031 * @error: #GError for error reporting, or %NULL to ignore.
3033 * Checks and resets the pending connect error for the socket.
3034 * This is used to check for errors when g_socket_connect() is
3035 * used in non-blocking mode.
3037 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
3042 g_socket_check_connect_result (GSocket *socket,
3047 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3049 if (!check_socket (socket, error))
3052 if (!check_timeout (socket, error))
3055 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
3057 g_prefix_error (error, _("Unable to get pending error: "));
3063 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
3064 socket_strerror (value));
3065 if (socket->priv->remote_address)
3067 g_object_unref (socket->priv->remote_address);
3068 socket->priv->remote_address = NULL;
3073 socket->priv->connected_read = TRUE;
3074 socket->priv->connected_write = TRUE;
3080 * g_socket_get_available_bytes:
3081 * @socket: a #GSocket
3083 * Get the amount of data pending in the OS input buffer, without blocking.
3085 * If @socket is a UDP or SCTP socket, this will return the size of
3086 * just the next packet, even if additional packets are buffered after
3089 * Note that on Windows, this function is rather inefficient in the
3090 * UDP case, and so if you know any plausible upper bound on the size
3091 * of the incoming packet, it is better to just do a
3092 * g_socket_receive() with a buffer of that size, rather than calling
3093 * g_socket_get_available_bytes() first and then doing a receive of
3094 * exactly the right size.
3096 * Returns: the number of bytes that can be read from the socket
3097 * without blocking or truncating, or -1 on error.
3102 g_socket_get_available_bytes (GSocket *socket)
3105 const gint bufsize = 64 * 1024;
3106 static guchar *buf = NULL;
3114 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3116 if (!check_socket (socket, NULL))
3120 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
3123 if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
3125 if (G_UNLIKELY (g_once_init_enter (&buf)))
3126 g_once_init_leave (&buf, g_malloc (bufsize));
3128 /* On datagram sockets, FIONREAD ioctl is not reliable because many
3129 * systems add internal header size to the reported size, making it
3130 * unusable for this function. */
3131 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
3134 int errsv = get_socket_errno ();
3136 if (errsv == WSAEWOULDBLOCK)
3138 if (errsv == EWOULDBLOCK || errsv == EAGAIN)
3146 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
3148 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
3157 /* Block on a timed wait for @condition until (@start_time + @timeout).
3158 * Return %G_IO_ERROR_TIMED_OUT if the timeout is reached; otherwise %TRUE.
3161 block_on_timeout (GSocket *socket,
3162 GIOCondition condition,
3165 GCancellable *cancellable,
3168 gint64 wait_timeout = -1;
3170 g_return_val_if_fail (timeout_us != 0, TRUE);
3172 /* check if we've timed out or how much time to wait at most */
3173 if (timeout_us >= 0)
3175 gint64 elapsed = g_get_monotonic_time () - start_time;
3177 if (elapsed >= timeout_us)
3179 g_set_error_literal (error,
3180 G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3181 _("Socket I/O timed out"));
3185 wait_timeout = timeout_us - elapsed;
3188 return g_socket_condition_timed_wait (socket, condition, wait_timeout,
3189 cancellable, error);
3193 g_socket_receive_with_timeout (GSocket *socket,
3197 GCancellable *cancellable,
3203 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3205 start_time = g_get_monotonic_time ();
3207 if (!check_socket (socket, error))
3210 if (!check_timeout (socket, error))
3213 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3218 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
3220 int errsv = get_socket_errno ();
3225 #ifdef WSAEWOULDBLOCK
3226 if (errsv == WSAEWOULDBLOCK)
3228 if (errsv == EWOULDBLOCK ||
3232 win32_unset_event_mask (socket, FD_READ);
3234 if (timeout_us != 0)
3236 if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
3237 cancellable, error))
3244 win32_unset_event_mask (socket, FD_READ);
3246 socket_set_error_lazy (error, errsv, _("Error receiving data: %s"));
3250 win32_unset_event_mask (socket, FD_READ);
3260 * @socket: a #GSocket
3261 * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3262 * a buffer to read data into (which should be at least @size bytes long).
3263 * @size: the number of bytes you want to read from the socket
3264 * @cancellable: (nullable): a %GCancellable or %NULL
3265 * @error: #GError for error reporting, or %NULL to ignore.
3267 * Receive data (up to @size bytes) from a socket. This is mainly used by
3268 * connection-oriented sockets; it is identical to g_socket_receive_from()
3269 * with @address set to %NULL.
3271 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
3272 * g_socket_receive() will always read either 0 or 1 complete messages from
3273 * the socket. If the received message is too large to fit in @buffer, then
3274 * the data beyond @size bytes will be discarded, without any explicit
3275 * indication that this has occurred.
3277 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
3278 * number of bytes, up to @size. If more than @size bytes have been
3279 * received, the additional data will be returned in future calls to
3280 * g_socket_receive().
3282 * If the socket is in blocking mode the call will block until there
3283 * is some data to receive, the connection is closed, or there is an
3284 * error. If there is no data available and the socket is in
3285 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3286 * returned. To be notified when data is available, wait for the
3287 * %G_IO_IN condition.
3289 * On error -1 is returned and @error is set accordingly.
3291 * Returns: Number of bytes read, or 0 if the connection was closed by
3292 * the peer, or -1 on error
3297 g_socket_receive (GSocket *socket,
3300 GCancellable *cancellable,
3303 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3304 socket->priv->blocking ? -1 : 0,
3305 cancellable, error);
3309 * g_socket_receive_with_blocking:
3310 * @socket: a #GSocket
3311 * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3312 * a buffer to read data into (which should be at least @size bytes long).
3313 * @size: the number of bytes you want to read from the socket
3314 * @blocking: whether to do blocking or non-blocking I/O
3315 * @cancellable: (nullable): a %GCancellable or %NULL
3316 * @error: #GError for error reporting, or %NULL to ignore.
3318 * This behaves exactly the same as g_socket_receive(), except that
3319 * the choice of blocking or non-blocking behavior is determined by
3320 * the @blocking argument rather than by @socket's properties.
3322 * Returns: Number of bytes read, or 0 if the connection was closed by
3323 * the peer, or -1 on error
3328 g_socket_receive_with_blocking (GSocket *socket,
3332 GCancellable *cancellable,
3335 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3336 blocking ? -1 : 0, cancellable, error);
3340 * g_socket_receive_from:
3341 * @socket: a #GSocket
3342 * @address: (out) (optional): a pointer to a #GSocketAddress
3344 * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3345 * a buffer to read data into (which should be at least @size bytes long).
3346 * @size: the number of bytes you want to read from the socket
3347 * @cancellable: (nullable): a %GCancellable or %NULL
3348 * @error: #GError for error reporting, or %NULL to ignore.
3350 * Receive data (up to @size bytes) from a socket.
3352 * If @address is non-%NULL then @address will be set equal to the
3353 * source address of the received packet.
3354 * @address is owned by the caller.
3356 * See g_socket_receive() for additional information.
3358 * Returns: Number of bytes read, or 0 if the connection was closed by
3359 * the peer, or -1 on error
3364 g_socket_receive_from (GSocket *socket,
3365 GSocketAddress **address,
3368 GCancellable *cancellable,
3376 return g_socket_receive_message (socket,
3384 /* See the comment about SIGPIPE above. */
3386 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
3388 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
3392 g_socket_send_with_timeout (GSocket *socket,
3393 const guint8 *buffer,
3396 GCancellable *cancellable,
3402 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3404 start_time = g_get_monotonic_time ();
3406 if (!check_socket (socket, error))
3409 if (!check_timeout (socket, error))
3412 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3417 if ((ret = send (socket->priv->fd, (const char *)buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
3419 int errsv = get_socket_errno ();
3424 #ifdef WSAEWOULDBLOCK
3425 if (errsv == WSAEWOULDBLOCK)
3427 if (errsv == EWOULDBLOCK ||
3431 win32_unset_event_mask (socket, FD_WRITE);
3433 if (timeout_us != 0)
3435 if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
3436 cancellable, error))
3443 socket_set_error_lazy (error, errsv, _("Error sending data: %s"));
3454 * @socket: a #GSocket
3455 * @buffer: (array length=size) (element-type guint8): the buffer
3456 * containing the data to send.
3457 * @size: the number of bytes to send
3458 * @cancellable: (nullable): a %GCancellable or %NULL
3459 * @error: #GError for error reporting, or %NULL to ignore.
3461 * Tries to send @size bytes from @buffer on the socket. This is
3462 * mainly used by connection-oriented sockets; it is identical to
3463 * g_socket_send_to() with @address set to %NULL.
3465 * If the socket is in blocking mode the call will block until there is
3466 * space for the data in the socket queue. If there is no space available
3467 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3468 * will be returned. To be notified when space is available, wait for the
3469 * %G_IO_OUT condition. Note though that you may still receive
3470 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3471 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3472 * very common due to the way the underlying APIs work.)
3474 * On error -1 is returned and @error is set accordingly.
3476 * Returns: Number of bytes written (which may be less than @size), or -1
3482 g_socket_send (GSocket *socket,
3483 const gchar *buffer,
3485 GCancellable *cancellable,
3488 return g_socket_send_with_blocking (socket, buffer, size,
3489 socket->priv->blocking,
3490 cancellable, error);
3494 * g_socket_send_with_blocking:
3495 * @socket: a #GSocket
3496 * @buffer: (array length=size) (element-type guint8): the buffer
3497 * containing the data to send.
3498 * @size: the number of bytes to send
3499 * @blocking: whether to do blocking or non-blocking I/O
3500 * @cancellable: (nullable): a %GCancellable or %NULL
3501 * @error: #GError for error reporting, or %NULL to ignore.
3503 * This behaves exactly the same as g_socket_send(), except that
3504 * the choice of blocking or non-blocking behavior is determined by
3505 * the @blocking argument rather than by @socket's properties.
3507 * Returns: Number of bytes written (which may be less than @size), or -1
3513 g_socket_send_with_blocking (GSocket *socket,
3514 const gchar *buffer,
3517 GCancellable *cancellable,
3520 return g_socket_send_with_timeout (socket, (const guint8 *) buffer, size,
3521 blocking ? -1 : 0, cancellable, error);
3526 * @socket: a #GSocket
3527 * @address: (nullable): a #GSocketAddress, or %NULL
3528 * @buffer: (array length=size) (element-type guint8): the buffer
3529 * containing the data to send.
3530 * @size: the number of bytes to send
3531 * @cancellable: (nullable): a %GCancellable or %NULL
3532 * @error: #GError for error reporting, or %NULL to ignore.
3534 * Tries to send @size bytes from @buffer to @address. If @address is
3535 * %NULL then the message is sent to the default receiver (set by
3536 * g_socket_connect()).
3538 * See g_socket_send() for additional information.
3540 * Returns: Number of bytes written (which may be less than @size), or -1
3546 g_socket_send_to (GSocket *socket,
3547 GSocketAddress *address,
3548 const gchar *buffer,
3550 GCancellable *cancellable,
3558 return g_socket_send_message (socket,
3568 * g_socket_shutdown:
3569 * @socket: a #GSocket
3570 * @shutdown_read: whether to shut down the read side
3571 * @shutdown_write: whether to shut down the write side
3572 * @error: #GError for error reporting, or %NULL to ignore.
3574 * Shut down part or all of a full-duplex connection.
3576 * If @shutdown_read is %TRUE then the receiving side of the connection
3577 * is shut down, and further reading is disallowed.
3579 * If @shutdown_write is %TRUE then the sending side of the connection
3580 * is shut down, and further writing is disallowed.
3582 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
3584 * One example where it is useful to shut down only one side of a connection is
3585 * graceful disconnect for TCP connections where you close the sending side,
3586 * then wait for the other side to close the connection, thus ensuring that the
3587 * other side saw all sent data.
3589 * Returns: %TRUE on success, %FALSE on error
3594 g_socket_shutdown (GSocket *socket,
3595 gboolean shutdown_read,
3596 gboolean shutdown_write,
3601 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3603 if (!check_socket (socket, error))
3607 if (!shutdown_read && !shutdown_write)
3611 if (shutdown_read && shutdown_write)
3613 else if (shutdown_read)
3618 if (shutdown_read && shutdown_write)
3620 else if (shutdown_read)
3626 if (shutdown (socket->priv->fd, how) != 0)
3628 int errsv = get_socket_errno ();
3629 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
3630 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
3635 socket->priv->connected_read = FALSE;
3637 socket->priv->connected_write = FALSE;
3644 * @socket: a #GSocket
3645 * @error: #GError for error reporting, or %NULL to ignore.
3647 * Closes the socket, shutting down any active connection.
3649 * Closing a socket does not wait for all outstanding I/O operations
3650 * to finish, so the caller should not rely on them to be guaranteed
3651 * to complete even if the close returns with no error.
3653 * Once the socket is closed, all other operations will return
3654 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
3657 * Sockets will be automatically closed when the last reference
3658 * is dropped, but you might want to call this function to make sure
3659 * resources are released as early as possible.
3661 * Beware that due to the way that TCP works, it is possible for
3662 * recently-sent data to be lost if either you close a socket while the
3663 * %G_IO_IN condition is set, or else if the remote connection tries to
3664 * send something to you after you close the socket but before it has
3665 * finished reading all of the data you sent. There is no easy generic
3666 * way to avoid this problem; the easiest fix is to design the network
3667 * protocol such that the client will never send data "out of turn".
3668 * Another solution is for the server to half-close the connection by
3669 * calling g_socket_shutdown() with only the @shutdown_write flag set,
3670 * and then wait for the client to notice this and close its side of the
3671 * connection, after which the server can safely call g_socket_close().
3672 * (This is what #GTcpConnection does if you call
3673 * g_tcp_connection_set_graceful_disconnect(). But of course, this
3674 * only works if the client will close its connection after the server
3677 * Returns: %TRUE on success, %FALSE on error
3682 g_socket_close (GSocket *socket,
3687 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3689 if (socket->priv->closed)
3690 return TRUE; /* Multiple close not an error */
3692 if (!check_socket (socket, error))
3698 res = closesocket (socket->priv->fd);
3700 res = close (socket->priv->fd);
3704 int errsv = get_socket_errno ();
3709 g_set_error (error, G_IO_ERROR,
3710 socket_io_error_from_errno (errsv),
3711 _("Error closing socket: %s"),
3712 socket_strerror (errsv));
3718 socket->priv->fd = -1;
3719 socket->priv->connected_read = FALSE;
3720 socket->priv->connected_write = FALSE;
3721 socket->priv->closed = TRUE;
3722 if (socket->priv->remote_address)
3724 g_object_unref (socket->priv->remote_address);
3725 socket->priv->remote_address = NULL;
3732 * g_socket_is_closed:
3733 * @socket: a #GSocket
3735 * Checks whether a socket is closed.
3737 * Returns: %TRUE if socket is closed, %FALSE otherwise
3742 g_socket_is_closed (GSocket *socket)
3744 return socket->priv->closed;
3747 /* Broken source, used on errors */
3749 broken_dispatch (GSource *source,
3750 GSourceFunc callback,
3756 static GSourceFuncs broken_funcs =
3766 network_events_for_condition (GIOCondition condition)
3770 if (condition & G_IO_IN)
3771 event_mask |= (FD_READ | FD_ACCEPT);
3772 if (condition & G_IO_OUT)
3773 event_mask |= (FD_WRITE | FD_CONNECT);
3774 event_mask |= FD_CLOSE;
3780 ensure_event (GSocket *socket)
3782 if (socket->priv->event == WSA_INVALID_EVENT)
3783 socket->priv->event = WSACreateEvent();
3787 update_select_events (GSocket *socket)
3794 ensure_event (socket);
3797 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3800 event_mask |= network_events_for_condition (*ptr);
3803 if (event_mask != socket->priv->selected_events)
3805 /* If no events selected, disable event so we can unset
3808 if (event_mask == 0)
3811 event = socket->priv->event;
3813 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3814 socket->priv->selected_events = event_mask;
3819 add_condition_watch (GSocket *socket,
3820 GIOCondition *condition)
3822 g_mutex_lock (&socket->priv->win32_source_lock);
3823 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3825 socket->priv->requested_conditions =
3826 g_list_prepend (socket->priv->requested_conditions, condition);
3828 update_select_events (socket);
3829 g_mutex_unlock (&socket->priv->win32_source_lock);
3833 remove_condition_watch (GSocket *socket,
3834 GIOCondition *condition)
3836 g_mutex_lock (&socket->priv->win32_source_lock);
3837 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3839 socket->priv->requested_conditions =
3840 g_list_remove (socket->priv->requested_conditions, condition);
3842 update_select_events (socket);
3843 g_mutex_unlock (&socket->priv->win32_source_lock);
3847 update_condition_unlocked (GSocket *socket)
3849 WSANETWORKEVENTS events;
3850 GIOCondition condition;
3852 if (WSAEnumNetworkEvents (socket->priv->fd,
3853 socket->priv->event,
3856 socket->priv->current_events |= events.lNetworkEvents;
3857 if (events.lNetworkEvents & FD_WRITE &&
3858 events.iErrorCode[FD_WRITE_BIT] != 0)
3859 socket->priv->current_errors |= FD_WRITE;
3860 if (events.lNetworkEvents & FD_CONNECT &&
3861 events.iErrorCode[FD_CONNECT_BIT] != 0)
3862 socket->priv->current_errors |= FD_CONNECT;
3866 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3867 condition |= G_IO_IN;
3869 if (socket->priv->current_events & FD_CLOSE)
3871 int r, errsv, buffer;
3873 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3875 errsv = get_socket_errno ();
3878 (r < 0 && errsv == WSAENOTCONN))
3879 condition |= G_IO_IN;
3881 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3882 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3883 condition |= G_IO_HUP;
3885 condition |= G_IO_ERR;
3888 if (socket->priv->closed)
3889 condition |= G_IO_HUP;
3891 /* Never report both G_IO_OUT and HUP, these are
3892 mutually exclusive (can't write to a closed socket) */
3893 if ((condition & G_IO_HUP) == 0 &&
3894 socket->priv->current_events & FD_WRITE)
3896 if (socket->priv->current_errors & FD_WRITE)
3897 condition |= G_IO_ERR;
3899 condition |= G_IO_OUT;
3903 if (socket->priv->current_events & FD_CONNECT)
3905 if (socket->priv->current_errors & FD_CONNECT)
3906 condition |= (G_IO_HUP | G_IO_ERR);
3908 condition |= G_IO_OUT;
3916 update_condition (GSocket *socket)
3919 g_mutex_lock (&socket->priv->win32_source_lock);
3920 res = update_condition_unlocked (socket);
3921 g_mutex_unlock (&socket->priv->win32_source_lock);
3934 GIOCondition condition;
3938 socket_source_prepare (GSource *source,
3941 GSocketSource *socket_source = (GSocketSource *)source;
3946 if ((socket_source->pollfd.revents & G_IO_NVAL) != 0)
3949 if (g_socket_is_closed (socket_source->socket))
3951 g_source_remove_poll (source, &socket_source->pollfd);
3952 socket_source->pollfd.revents = G_IO_NVAL;
3956 return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3958 return g_socket_is_closed (socket_source->socket) && socket_source->fd_tag != NULL;
3964 socket_source_check_win32 (GSource *source)
3968 return socket_source_prepare (source, &timeout);
3973 socket_source_dispatch (GSource *source,
3974 GSourceFunc callback,
3977 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3978 GSocketSource *socket_source = (GSocketSource *)source;
3979 GSocket *socket = socket_source->socket;
3985 events = update_condition (socket_source->socket);
3987 if (g_socket_is_closed (socket_source->socket))
3989 if (socket_source->fd_tag)
3990 g_source_remove_unix_fd (source, socket_source->fd_tag);
3991 socket_source->fd_tag = NULL;
3996 events = g_source_query_unix_fd (source, socket_source->fd_tag);
4000 timeout = g_source_get_ready_time (source);
4001 if (timeout >= 0 && timeout < g_source_get_time (source) &&
4002 !g_socket_is_closed (socket_source->socket))
4004 socket->priv->timed_out = TRUE;
4005 events |= (G_IO_IN | G_IO_OUT);
4008 ret = (*func) (socket, events & socket_source->condition, user_data);
4010 if (socket->priv->timeout && !g_socket_is_closed (socket_source->socket))
4011 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
4013 g_source_set_ready_time (source, -1);
4019 socket_source_finalize (GSource *source)
4021 GSocketSource *socket_source = (GSocketSource *)source;
4024 socket = socket_source->socket;
4027 remove_condition_watch (socket, &socket_source->condition);
4030 g_object_unref (socket);
4034 socket_source_closure_callback (GSocket *socket,
4035 GIOCondition condition,
4038 GClosure *closure = data;
4040 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
4041 GValue result_value = G_VALUE_INIT;
4044 g_value_init (&result_value, G_TYPE_BOOLEAN);
4046 g_value_init (¶ms[0], G_TYPE_SOCKET);
4047 g_value_set_object (¶ms[0], socket);
4048 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
4049 g_value_set_flags (¶ms[1], condition);
4051 g_closure_invoke (closure, &result_value, 2, params, NULL);
4053 result = g_value_get_boolean (&result_value);
4054 g_value_unset (&result_value);
4055 g_value_unset (¶ms[0]);
4056 g_value_unset (¶ms[1]);
4061 static GSourceFuncs socket_source_funcs =
4063 socket_source_prepare,
4065 socket_source_check_win32,
4069 socket_source_dispatch,
4070 socket_source_finalize,
4071 (GSourceFunc)socket_source_closure_callback,
4075 socket_source_new (GSocket *socket,
4076 GIOCondition condition,
4077 GCancellable *cancellable)
4080 GSocketSource *socket_source;
4083 ensure_event (socket);
4085 if (socket->priv->event == WSA_INVALID_EVENT)
4087 g_warning ("Failed to create WSAEvent");
4088 return g_source_new (&broken_funcs, sizeof (GSource));
4092 if (!check_socket (socket, NULL))
4094 g_warning ("Socket check failed");
4095 return g_source_new (&broken_funcs, sizeof (GSource));
4098 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
4100 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
4101 g_source_set_name (source, "GSocket");
4102 socket_source = (GSocketSource *)source;
4104 socket_source->socket = g_object_ref (socket);
4105 socket_source->condition = condition;
4109 GSource *cancellable_source;
4111 cancellable_source = g_cancellable_source_new (cancellable);
4112 g_source_add_child_source (source, cancellable_source);
4113 g_source_set_dummy_callback (cancellable_source);
4114 g_source_unref (cancellable_source);
4118 add_condition_watch (socket, &socket_source->condition);
4119 socket_source->pollfd.fd = (gintptr) socket->priv->event;
4120 socket_source->pollfd.events = condition;
4121 socket_source->pollfd.revents = 0;
4122 g_source_add_poll (source, &socket_source->pollfd);
4124 socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
4127 if (socket->priv->timeout)
4128 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
4130 g_source_set_ready_time (source, -1);
4136 * g_socket_create_source: (skip)
4137 * @socket: a #GSocket
4138 * @condition: a #GIOCondition mask to monitor
4139 * @cancellable: (nullable): a %GCancellable or %NULL
4141 * Creates a #GSource that can be attached to a %GMainContext to monitor
4142 * for the availability of the specified @condition on the socket. The #GSource
4143 * keeps a reference to the @socket.
4145 * The callback on the source is of the #GSocketSourceFunc type.
4147 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
4148 * these conditions will always be reported output if they are true.
4150 * @cancellable if not %NULL can be used to cancel the source, which will
4151 * cause the source to trigger, reporting the current condition (which
4152 * is likely 0 unless cancellation happened at the same time as a
4153 * condition change). You can check for this in the callback using
4154 * g_cancellable_is_cancelled().
4156 * If @socket has a timeout set, and it is reached before @condition
4157 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
4158 * %G_IO_OUT depending on @condition. However, @socket will have been
4159 * marked as having had a timeout, and so the next #GSocket I/O method
4160 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
4162 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
4167 g_socket_create_source (GSocket *socket,
4168 GIOCondition condition,
4169 GCancellable *cancellable)
4171 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
4173 return socket_source_new (socket, condition, cancellable);
4177 * g_socket_condition_check:
4178 * @socket: a #GSocket
4179 * @condition: a #GIOCondition mask to check
4181 * Checks on the readiness of @socket to perform operations.
4182 * The operations specified in @condition are checked for and masked
4183 * against the currently-satisfied conditions on @socket. The result
4186 * Note that on Windows, it is possible for an operation to return
4187 * %G_IO_ERROR_WOULD_BLOCK even immediately after
4188 * g_socket_condition_check() has claimed that the socket is ready for
4189 * writing. Rather than calling g_socket_condition_check() and then
4190 * writing to the socket if it succeeds, it is generally better to
4191 * simply try writing to the socket right away, and try again later if
4192 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
4194 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
4195 * these conditions will always be set in the output if they are true.
4197 * This call never blocks.
4199 * Returns: the @GIOCondition mask of the current state
4204 g_socket_condition_check (GSocket *socket,
4205 GIOCondition condition)
4207 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
4209 if (!check_socket (socket, NULL))
4214 GIOCondition current_condition;
4216 condition |= G_IO_ERR | G_IO_HUP;
4218 add_condition_watch (socket, &condition);
4219 current_condition = update_condition (socket);
4220 remove_condition_watch (socket, &condition);
4221 return condition & current_condition;
4227 poll_fd.fd = socket->priv->fd;
4228 poll_fd.events = condition;
4229 poll_fd.revents = 0;
4232 result = g_poll (&poll_fd, 1, 0);
4233 while (result == -1 && get_socket_errno () == EINTR);
4235 return poll_fd.revents;
4241 * g_socket_condition_wait:
4242 * @socket: a #GSocket
4243 * @condition: a #GIOCondition mask to wait for
4244 * @cancellable: (nullable): a #GCancellable, or %NULL
4245 * @error: a #GError pointer, or %NULL
4247 * Waits for @condition to become true on @socket. When the condition
4248 * is met, %TRUE is returned.
4250 * If @cancellable is cancelled before the condition is met, or if the
4251 * socket has a timeout set and it is reached before the condition is
4252 * met, then %FALSE is returned and @error, if non-%NULL, is set to
4253 * the appropriate value (%G_IO_ERROR_CANCELLED or
4254 * %G_IO_ERROR_TIMED_OUT).
4256 * See also g_socket_condition_timed_wait().
4258 * Returns: %TRUE if the condition was met, %FALSE otherwise
4263 g_socket_condition_wait (GSocket *socket,
4264 GIOCondition condition,
4265 GCancellable *cancellable,
4268 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4270 return g_socket_condition_timed_wait (socket, condition, -1,
4271 cancellable, error);
4275 * g_socket_condition_timed_wait:
4276 * @socket: a #GSocket
4277 * @condition: a #GIOCondition mask to wait for
4278 * @timeout_us: the maximum time (in microseconds) to wait, or -1
4279 * @cancellable: (nullable): a #GCancellable, or %NULL
4280 * @error: a #GError pointer, or %NULL
4282 * Waits for up to @timeout_us microseconds for @condition to become true
4283 * on @socket. If the condition is met, %TRUE is returned.
4285 * If @cancellable is cancelled before the condition is met, or if
4286 * @timeout_us (or the socket's #GSocket:timeout) is reached before the
4287 * condition is met, then %FALSE is returned and @error, if non-%NULL,
4288 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
4289 * %G_IO_ERROR_TIMED_OUT).
4291 * If you don't want a timeout, use g_socket_condition_wait().
4292 * (Alternatively, you can pass -1 for @timeout_us.)
4294 * Note that although @timeout_us is in microseconds for consistency with
4295 * other GLib APIs, this function actually only has millisecond
4296 * resolution, and the behavior is undefined if @timeout_us is not an
4297 * exact number of milliseconds.
4299 * Returns: %TRUE if the condition was met, %FALSE otherwise
4304 g_socket_condition_timed_wait (GSocket *socket,
4305 GIOCondition condition,
4307 GCancellable *cancellable,
4313 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4315 if (!check_socket (socket, error))
4318 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4321 if (socket->priv->timeout &&
4322 (timeout_us < 0 || socket->priv->timeout < timeout_us / G_USEC_PER_SEC))
4323 timeout_ms = (gint64) socket->priv->timeout * 1000;
4324 else if (timeout_us != -1)
4325 timeout_ms = timeout_us / 1000;
4329 start_time = g_get_monotonic_time ();
4333 GIOCondition current_condition;
4339 /* Always check these */
4340 condition |= G_IO_ERR | G_IO_HUP;
4342 add_condition_watch (socket, &condition);
4345 events[num_events++] = socket->priv->event;
4347 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
4348 events[num_events++] = (WSAEVENT)cancel_fd.fd;
4350 if (timeout_ms == -1)
4351 timeout_ms = WSA_INFINITE;
4353 g_mutex_lock (&socket->priv->win32_source_lock);
4354 current_condition = update_condition_unlocked (socket);
4355 while ((condition & current_condition) == 0)
4357 if (!socket->priv->waiting)
4359 socket->priv->waiting = TRUE;
4360 socket->priv->waiting_result = 0;
4361 g_mutex_unlock (&socket->priv->win32_source_lock);
4363 res = WSAWaitForMultipleEvents (num_events, events, FALSE, timeout_ms, FALSE);
4365 g_mutex_lock (&socket->priv->win32_source_lock);
4366 socket->priv->waiting = FALSE;
4367 socket->priv->waiting_result = res;
4368 g_cond_broadcast (&socket->priv->win32_source_cond);
4372 if (timeout_ms != WSA_INFINITE)
4374 if (!g_cond_wait_until (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock, timeout_ms))
4376 res = WSA_WAIT_TIMEOUT;
4381 res = socket->priv->waiting_result;
4386 g_cond_wait (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock);
4387 res = socket->priv->waiting_result;
4391 if (res == WSA_WAIT_FAILED)
4393 int errsv = get_socket_errno ();
4395 g_set_error (error, G_IO_ERROR,
4396 socket_io_error_from_errno (errsv),
4397 _("Waiting for socket condition: %s"),
4398 socket_strerror (errsv));
4401 else if (res == WSA_WAIT_TIMEOUT)
4403 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4404 _("Socket I/O timed out"));
4408 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4411 current_condition = update_condition_unlocked (socket);
4413 if (timeout_ms != WSA_INFINITE)
4415 timeout_ms -= (g_get_monotonic_time () - start_time) * 1000;
4420 g_mutex_unlock (&socket->priv->win32_source_lock);
4421 remove_condition_watch (socket, &condition);
4423 g_cancellable_release_fd (cancellable);
4425 return (condition & current_condition) != 0;
4433 poll_fd[0].fd = socket->priv->fd;
4434 poll_fd[0].events = condition;
4437 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
4443 result = g_poll (poll_fd, num, timeout_ms);
4445 if (result != -1 || errsv != EINTR)
4448 if (timeout_ms != -1)
4450 timeout_ms -= (g_get_monotonic_time () - start_time) / 1000;
4457 g_cancellable_release_fd (cancellable);
4461 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4462 _("Socket I/O timed out"));
4466 return !g_cancellable_set_error_if_cancelled (cancellable, error);
4473 /* Unfortunately these have to be macros rather than inline functions due to
4474 * using alloca(). */
4475 #define output_message_to_msghdr(message, prev_message, msg, prev_msg, error) \
4477 const GOutputMessage *_message = (message); \
4478 const GOutputMessage *_prev_message = (prev_message); \
4479 struct msghdr *_msg = (msg); \
4480 const struct msghdr *_prev_msg = (prev_msg); \
4481 GError **_error = (error); \
4483 _msg->msg_flags = 0; \
4486 if (_prev_message != NULL && _prev_message->address == _message->address) \
4488 _msg->msg_name = _prev_msg->msg_name; \
4489 _msg->msg_namelen = _prev_msg->msg_namelen; \
4491 else if (_message->address != NULL) \
4493 _msg->msg_namelen = g_socket_address_get_native_size (_message->address); \
4494 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4495 if (!g_socket_address_to_native (_message->address, _msg->msg_name, \
4496 _msg->msg_namelen, _error)) \
4501 _msg->msg_name = NULL; \
4502 _msg->msg_namelen = 0; \
4507 /* this entire expression will be evaluated at compile time */ \
4508 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4509 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4510 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4511 G_STRUCT_OFFSET (GOutputVector, buffer) && \
4512 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4513 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4514 G_STRUCT_OFFSET (GOutputVector, size)) \
4515 /* ABI is compatible */ \
4517 _msg->msg_iov = (struct iovec *) _message->vectors; \
4518 _msg->msg_iovlen = _message->num_vectors; \
4521 /* ABI is incompatible */ \
4525 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4526 for (i = 0; i < _message->num_vectors; i++) \
4528 _msg->msg_iov[i].iov_base = (void *) _message->vectors[i].buffer; \
4529 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4531 _msg->msg_iovlen = _message->num_vectors; \
4537 struct cmsghdr *cmsg; \
4540 _msg->msg_controllen = 0; \
4541 for (i = 0; i < _message->num_control_messages; i++) \
4542 _msg->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (_message->control_messages[i])); \
4544 if (_msg->msg_controllen == 0) \
4545 _msg->msg_control = NULL; \
4548 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4549 memset (_msg->msg_control, '\0', _msg->msg_controllen); \
4552 cmsg = CMSG_FIRSTHDR (_msg); \
4553 for (i = 0; i < _message->num_control_messages; i++) \
4555 cmsg->cmsg_level = g_socket_control_message_get_level (_message->control_messages[i]); \
4556 cmsg->cmsg_type = g_socket_control_message_get_msg_type (_message->control_messages[i]); \
4557 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (_message->control_messages[i])); \
4558 g_socket_control_message_serialize (_message->control_messages[i], \
4559 CMSG_DATA (cmsg)); \
4560 cmsg = CMSG_NXTHDR (_msg, cmsg); \
4562 g_assert (cmsg == NULL); \
4566 #define input_message_to_msghdr(message, msg) \
4568 const GInputMessage *_message = (message); \
4569 struct msghdr *_msg = (msg); \
4572 if (_message->address) \
4574 _msg->msg_namelen = sizeof (struct sockaddr_storage); \
4575 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4579 _msg->msg_name = NULL; \
4580 _msg->msg_namelen = 0; \
4584 /* this entire expression will be evaluated at compile time */ \
4585 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4586 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4587 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4588 G_STRUCT_OFFSET (GInputVector, buffer) && \
4589 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4590 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4591 G_STRUCT_OFFSET (GInputVector, size)) \
4592 /* ABI is compatible */ \
4594 _msg->msg_iov = (struct iovec *) _message->vectors; \
4595 _msg->msg_iovlen = _message->num_vectors; \
4598 /* ABI is incompatible */ \
4602 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4603 for (i = 0; i < _message->num_vectors; i++) \
4605 _msg->msg_iov[i].iov_base = _message->vectors[i].buffer; \
4606 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4608 _msg->msg_iovlen = _message->num_vectors; \
4612 if (_message->control_messages == NULL) \
4614 _msg->msg_controllen = 0; \
4615 _msg->msg_control = NULL; \
4619 _msg->msg_controllen = 2048; \
4620 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4624 _msg->msg_flags = _message->flags; \
4628 input_message_from_msghdr (const struct msghdr *msg,
4629 GInputMessage *message,
4632 /* decode address */
4633 if (message->address != NULL)
4635 *message->address = cache_recv_address (socket, msg->msg_name,
4639 /* decode control messages */
4641 GPtrArray *my_messages = NULL;
4642 struct cmsghdr *cmsg;
4644 if (msg->msg_controllen >= sizeof (struct cmsghdr))
4646 g_assert (message->control_messages != NULL);
4647 for (cmsg = CMSG_FIRSTHDR (msg);
4649 cmsg = CMSG_NXTHDR ((struct msghdr *) msg, cmsg))
4651 GSocketControlMessage *control_message;
4653 control_message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4655 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4657 if (control_message == NULL)
4658 /* We've already spewed about the problem in the
4659 deserialization code, so just continue */
4662 if (my_messages == NULL)
4663 my_messages = g_ptr_array_new ();
4664 g_ptr_array_add (my_messages, control_message);
4668 if (message->num_control_messages)
4669 *message->num_control_messages = my_messages != NULL ? my_messages->len : 0;
4671 if (message->control_messages)
4673 if (my_messages == NULL)
4675 *message->control_messages = NULL;
4679 g_ptr_array_add (my_messages, NULL);
4680 *message->control_messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4685 g_assert (my_messages == NULL);
4689 /* capture the flags */
4690 message->flags = msg->msg_flags;
4695 * g_socket_send_message:
4696 * @socket: a #GSocket
4697 * @address: (nullable): a #GSocketAddress, or %NULL
4698 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4699 * @num_vectors: the number of elements in @vectors, or -1
4700 * @messages: (array length=num_messages) (nullable): a pointer to an
4701 * array of #GSocketControlMessages, or %NULL.
4702 * @num_messages: number of elements in @messages, or -1.
4703 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
4704 * contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
4705 * @cancellable: (nullable): a %GCancellable or %NULL
4706 * @error: #GError for error reporting, or %NULL to ignore.
4708 * Send data to @address on @socket. For sending multiple messages see
4709 * g_socket_send_messages(); for easier use, see
4710 * g_socket_send() and g_socket_send_to().
4712 * If @address is %NULL then the message is sent to the default receiver
4713 * (set by g_socket_connect()).
4715 * @vectors must point to an array of #GOutputVector structs and
4716 * @num_vectors must be the length of this array. (If @num_vectors is -1,
4717 * then @vectors is assumed to be terminated by a #GOutputVector with a
4718 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
4719 * that the sent data will be gathered from. Using multiple
4720 * #GOutputVectors is more memory-efficient than manually copying
4721 * data from multiple sources into a single buffer, and more
4722 * network-efficient than making multiple calls to g_socket_send().
4724 * @messages, if non-%NULL, is taken to point to an array of @num_messages
4725 * #GSocketControlMessage instances. These correspond to the control
4726 * messages to be sent on the socket.
4727 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
4730 * @flags modify how the message is sent. The commonly available arguments
4731 * for this are available in the #GSocketMsgFlags enum, but the
4732 * values there are the same as the system values, and the flags
4733 * are passed in as-is, so you can pass in system-specific flags too.
4735 * If the socket is in blocking mode the call will block until there is
4736 * space for the data in the socket queue. If there is no space available
4737 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4738 * will be returned. To be notified when space is available, wait for the
4739 * %G_IO_OUT condition. Note though that you may still receive
4740 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4741 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4742 * very common due to the way the underlying APIs work.)
4744 * On error -1 is returned and @error is set accordingly.
4746 * Returns: Number of bytes written (which may be less than @size), or -1
4752 g_socket_send_message (GSocket *socket,
4753 GSocketAddress *address,
4754 GOutputVector *vectors,
4756 GSocketControlMessage **messages,
4759 GCancellable *cancellable,
4762 GPollableReturn res;
4763 gsize bytes_written = 0;
4765 res = g_socket_send_message_with_timeout (socket, address,
4766 vectors, num_vectors,
4767 messages, num_messages, flags,
4768 socket->priv->blocking ? -1 : 0,
4770 cancellable, error);
4772 if (res == G_POLLABLE_RETURN_WOULD_BLOCK)
4775 socket_set_error_lazy (error, EWOULDBLOCK, _("Error sending message: %s"));
4777 socket_set_error_lazy (error, WSAEWOULDBLOCK, _("Error sending message: %s"));
4781 return res == G_POLLABLE_RETURN_OK ? bytes_written : -1;
4785 * g_socket_send_message_with_timeout:
4786 * @socket: a #GSocket
4787 * @address: (nullable): a #GSocketAddress, or %NULL
4788 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4789 * @num_vectors: the number of elements in @vectors, or -1
4790 * @messages: (array length=num_messages) (nullable): a pointer to an
4791 * array of #GSocketControlMessages, or %NULL.
4792 * @num_messages: number of elements in @messages, or -1.
4793 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
4794 * contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
4795 * @timeout_us: the maximum time (in microseconds) to wait, or -1
4796 * @bytes_written: (out) (optional): location to store the number of bytes that were written to the socket
4797 * @cancellable: (nullable): a %GCancellable or %NULL
4798 * @error: #GError for error reporting, or %NULL to ignore.
4800 * This behaves exactly the same as g_socket_send_message(), except that
4801 * the choice of timeout behavior is determined by the @timeout_us argument
4802 * rather than by @socket's properties.
4804 * On error %G_POLLABLE_RETURN_FAILED is returned and @error is set accordingly, or
4805 * if the socket is currently not writable %G_POLLABLE_RETURN_WOULD_BLOCK is
4806 * returned. @bytes_written will contain 0 in both cases.
4808 * Returns: %G_POLLABLE_RETURN_OK if all data was successfully written,
4809 * %G_POLLABLE_RETURN_WOULD_BLOCK if the socket is currently not writable, or
4810 * %G_POLLABLE_RETURN_FAILED if an error happened and @error is set.
4815 g_socket_send_message_with_timeout (GSocket *socket,
4816 GSocketAddress *address,
4817 const GOutputVector *vectors,
4819 GSocketControlMessage **messages,
4823 gsize *bytes_written,
4824 GCancellable *cancellable,
4827 GOutputVector one_vector;
4834 g_return_val_if_fail (G_IS_SOCKET (socket), G_POLLABLE_RETURN_FAILED);
4835 g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), G_POLLABLE_RETURN_FAILED);
4836 g_return_val_if_fail (num_vectors == 0 || vectors != NULL, G_POLLABLE_RETURN_FAILED);
4837 g_return_val_if_fail (num_messages == 0 || messages != NULL, G_POLLABLE_RETURN_FAILED);
4838 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), G_POLLABLE_RETURN_FAILED);
4839 g_return_val_if_fail (error == NULL || *error == NULL, G_POLLABLE_RETURN_FAILED);
4841 start_time = g_get_monotonic_time ();
4843 if (!check_socket (socket, error))
4844 return G_POLLABLE_RETURN_FAILED;
4846 if (!check_timeout (socket, error))
4847 return G_POLLABLE_RETURN_FAILED;
4849 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4850 return G_POLLABLE_RETURN_FAILED;
4852 if (num_vectors == -1)
4854 for (num_vectors = 0;
4855 vectors[num_vectors].buffer != NULL;
4860 if (num_messages == -1)
4862 for (num_messages = 0;
4863 messages != NULL && messages[num_messages] != NULL;
4868 if (num_vectors == 0)
4872 one_vector.buffer = &zero;
4873 one_vector.size = 1;
4875 vectors = &one_vector;
4880 GOutputMessage output_message;
4883 GError *child_error = NULL;
4885 output_message.address = address;
4886 output_message.vectors = (GOutputVector *) vectors;
4887 output_message.num_vectors = num_vectors;
4888 output_message.bytes_sent = 0;
4889 output_message.control_messages = messages;
4890 output_message.num_control_messages = num_messages;
4892 output_message_to_msghdr (&output_message, NULL, &msg, NULL, &child_error);
4894 if (child_error != NULL)
4896 g_propagate_error (error, child_error);
4897 return G_POLLABLE_RETURN_FAILED;
4902 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4905 int errsv = get_socket_errno ();
4910 if (errsv == EWOULDBLOCK || errsv == EAGAIN)
4912 if (timeout_us != 0)
4914 if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
4915 cancellable, error))
4916 return G_POLLABLE_RETURN_FAILED;
4921 return G_POLLABLE_RETURN_WOULD_BLOCK;
4924 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4925 return G_POLLABLE_RETURN_FAILED;
4931 *bytes_written = result;
4933 return G_POLLABLE_RETURN_OK;
4937 struct sockaddr_storage addr;
4944 /* Win32 doesn't support control messages.
4945 Actually this is possible for raw and datagram sockets
4946 via WSASendMessage on Vista or later, but that doesn't
4948 if (num_messages != 0)
4950 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
4951 _("GSocketControlMessage not supported on Windows"));
4952 return G_POLLABLE_RETURN_FAILED;
4956 bufs = g_newa (WSABUF, num_vectors);
4957 for (i = 0; i < num_vectors; i++)
4959 bufs[i].buf = (char *)vectors[i].buffer;
4960 bufs[i].len = (gulong)vectors[i].size;
4964 addrlen = 0; /* Avoid warning */
4967 addrlen = g_socket_address_get_native_size (address);
4968 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
4969 return G_POLLABLE_RETURN_FAILED;
4975 result = WSASendTo (socket->priv->fd,
4978 (const struct sockaddr *)&addr, addrlen,
4981 result = WSASend (socket->priv->fd,
4988 int errsv = get_socket_errno ();
4990 if (errsv == WSAEINTR)
4993 if (errsv == WSAEWOULDBLOCK)
4995 win32_unset_event_mask (socket, FD_WRITE);
4997 if (timeout_us != 0)
4999 if (!block_on_timeout (socket, G_IO_OUT, timeout_us,
5000 start_time, cancellable, error))
5001 return G_POLLABLE_RETURN_FAILED;
5006 return G_POLLABLE_RETURN_WOULD_BLOCK;
5009 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5010 return G_POLLABLE_RETURN_FAILED;
5016 *bytes_written = bytes_sent;
5017 return G_POLLABLE_RETURN_OK;
5023 * g_socket_send_messages:
5024 * @socket: a #GSocket
5025 * @messages: (array length=num_messages): an array of #GOutputMessage structs
5026 * @num_messages: the number of elements in @messages
5027 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
5028 * contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5029 * @cancellable: (nullable): a %GCancellable or %NULL
5030 * @error: #GError for error reporting, or %NULL to ignore.
5032 * Send multiple data messages from @socket in one go. This is the most
5033 * complicated and fully-featured version of this call. For easier use, see
5034 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
5036 * @messages must point to an array of #GOutputMessage structs and
5037 * @num_messages must be the length of this array. Each #GOutputMessage
5038 * contains an address to send the data to, and a pointer to an array of
5039 * #GOutputVector structs to describe the buffers that the data to be sent
5040 * for each message will be gathered from. Using multiple #GOutputVectors is
5041 * more memory-efficient than manually copying data from multiple sources
5042 * into a single buffer, and more network-efficient than making multiple
5043 * calls to g_socket_send(). Sending multiple messages in one go avoids the
5044 * overhead of making a lot of syscalls in scenarios where a lot of data
5045 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
5046 * or where the same data needs to be sent to multiple recipients.
5048 * @flags modify how the message is sent. The commonly available arguments
5049 * for this are available in the #GSocketMsgFlags enum, but the
5050 * values there are the same as the system values, and the flags
5051 * are passed in as-is, so you can pass in system-specific flags too.
5053 * If the socket is in blocking mode the call will block until there is
5054 * space for all the data in the socket queue. If there is no space available
5055 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
5056 * will be returned if no data was written at all, otherwise the number of
5057 * messages sent will be returned. To be notified when space is available,
5058 * wait for the %G_IO_OUT condition. Note though that you may still receive
5059 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
5060 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
5061 * very common due to the way the underlying APIs work.)
5063 * On error -1 is returned and @error is set accordingly. An error will only
5064 * be returned if zero messages could be sent; otherwise the number of messages
5065 * successfully sent before the error will be returned.
5067 * Returns: number of messages sent, or -1 on error. Note that the number of
5068 * messages sent may be smaller than @num_messages if the socket is
5069 * non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
5070 * in which case the caller may re-try to send the remaining messages.
5075 g_socket_send_messages (GSocket *socket,
5076 GOutputMessage *messages,
5079 GCancellable *cancellable,
5082 return g_socket_send_messages_with_timeout (socket, messages, num_messages,
5084 socket->priv->blocking ? -1 : 0,
5085 cancellable, error);
5089 g_socket_send_messages_with_timeout (GSocket *socket,
5090 GOutputMessage *messages,
5094 GCancellable *cancellable,
5099 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5100 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5101 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
5102 g_return_val_if_fail (error == NULL || *error == NULL, -1);
5104 start_time = g_get_monotonic_time ();
5106 if (!check_socket (socket, error))
5109 if (!check_timeout (socket, error))
5112 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5115 if (num_messages == 0)
5118 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
5120 struct mmsghdr *msgvec;
5123 /* Clamp the number of vectors if more given than we can write in one go.
5124 * The caller has to handle short writes anyway.
5126 if (num_messages > G_IOV_MAX)
5127 num_messages = G_IOV_MAX;
5129 msgvec = g_newa (struct mmsghdr, num_messages);
5131 for (i = 0; i < num_messages; ++i)
5133 GOutputMessage *msg = &messages[i];
5134 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5135 GError *child_error = NULL;
5137 msgvec[i].msg_len = 0;
5139 output_message_to_msghdr (msg, (i > 0) ? &messages[i - 1] : NULL,
5140 msg_hdr, (i > 0) ? &msgvec[i - 1].msg_hdr : NULL,
5143 if (child_error != NULL)
5145 g_propagate_error (error, child_error);
5150 for (num_sent = 0; num_sent < num_messages;)
5154 ret = sendmmsg (socket->priv->fd, msgvec + num_sent, num_messages - num_sent,
5155 flags | G_SOCKET_DEFAULT_SEND_FLAGS);
5159 int errsv = get_socket_errno ();
5164 if (timeout_us != 0 &&
5165 (errsv == EWOULDBLOCK ||
5168 if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
5169 cancellable, error))
5173 g_clear_error (error);
5183 /* If any messages were successfully sent, do not error. */
5187 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5195 for (i = 0; i < num_sent; ++i)
5196 messages[i].bytes_sent = msgvec[i].msg_len;
5204 gint64 wait_timeout;
5206 wait_timeout = timeout_us;
5208 for (i = 0; i < num_messages; ++i)
5210 GOutputMessage *msg = &messages[i];
5211 GError *msg_error = NULL;
5212 GPollableReturn pollable_result;
5213 gsize bytes_written = 0;
5215 pollable_result = g_socket_send_message_with_timeout (socket, msg->address,
5218 msg->control_messages,
5219 msg->num_control_messages,
5220 flags, wait_timeout,
5222 cancellable, &msg_error);
5224 if (pollable_result == G_POLLABLE_RETURN_WOULD_BLOCK)
5227 socket_set_error_lazy (&msg_error, EWOULDBLOCK, _("Error sending message: %s"));
5229 socket_set_error_lazy (&msg_error, WSAEWOULDBLOCK, _("Error sending message: %s"));
5233 result = pollable_result == G_POLLABLE_RETURN_OK ? bytes_written : -1;
5235 /* check if we've timed out or how much time to wait at most */
5238 gint64 elapsed = g_get_monotonic_time () - start_time;
5239 wait_timeout = MAX (timeout_us - elapsed, 1);
5244 /* if we couldn't send all messages, just return how many we did
5245 * manage to send, provided we managed to send at least one */
5248 g_error_free (msg_error);
5253 g_propagate_error (error, msg_error);
5258 msg->bytes_sent = result;
5266 static GSocketAddress *
5267 cache_recv_address (GSocket *socket, struct sockaddr *native, size_t native_len)
5269 GSocketAddress *saddr;
5271 guint64 oldest_time = G_MAXUINT64;
5272 gint oldest_index = 0;
5274 if (native_len == 0)
5278 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
5280 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
5281 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
5282 gsize tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
5287 if (tmp_native_len != native_len)
5290 if (memcmp (tmp_native, native, native_len) == 0)
5292 saddr = g_object_ref (tmp);
5293 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
5297 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
5299 oldest_time = socket->priv->recv_addr_cache[i].last_used;
5304 saddr = g_socket_address_new_from_native (native, native_len);
5306 if (socket->priv->recv_addr_cache[oldest_index].addr)
5308 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
5309 g_free (socket->priv->recv_addr_cache[oldest_index].native);
5312 socket->priv->recv_addr_cache[oldest_index].native = g_memdup2 (native, native_len);
5313 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
5314 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
5315 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
5321 g_socket_receive_message_with_timeout (GSocket *socket,
5322 GSocketAddress **address,
5323 GInputVector *vectors,
5325 GSocketControlMessage ***messages,
5329 GCancellable *cancellable,
5332 GInputVector one_vector;
5336 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5338 start_time = g_get_monotonic_time ();
5340 if (!check_socket (socket, error))
5343 if (!check_timeout (socket, error))
5346 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5349 if (num_vectors == -1)
5351 for (num_vectors = 0;
5352 vectors[num_vectors].buffer != NULL;
5357 if (num_vectors == 0)
5359 one_vector.buffer = &one_byte;
5360 one_vector.size = 1;
5362 vectors = &one_vector;
5367 GInputMessage input_message;
5371 input_message.address = address;
5372 input_message.vectors = vectors;
5373 input_message.num_vectors = num_vectors;
5374 input_message.bytes_received = 0;
5375 input_message.flags = (flags != NULL) ? *flags : 0;
5376 input_message.control_messages = messages;
5377 input_message.num_control_messages = (guint *) num_messages;
5379 /* We always set the close-on-exec flag so we don't leak file
5380 * descriptors into child processes. Note that gunixfdmessage.c
5381 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5383 #ifdef MSG_CMSG_CLOEXEC
5384 input_message.flags |= MSG_CMSG_CLOEXEC;
5387 input_message_to_msghdr (&input_message, &msg);
5392 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5393 #ifdef MSG_CMSG_CLOEXEC
5394 if (result < 0 && get_socket_errno () == EINVAL)
5396 /* We must be running on an old kernel. Call without the flag. */
5397 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
5398 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5404 int errsv = get_socket_errno ();
5409 if (timeout_us != 0 &&
5410 (errsv == EWOULDBLOCK ||
5413 if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
5414 cancellable, error))
5420 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5426 input_message_from_msghdr (&msg, &input_message, socket);
5429 *flags = input_message.flags;
5435 struct sockaddr_storage addr;
5437 DWORD bytes_received;
5444 bufs = g_newa (WSABUF, num_vectors);
5445 for (i = 0; i < num_vectors; i++)
5447 bufs[i].buf = (char *)vectors[i].buffer;
5448 bufs[i].len = (gulong)vectors[i].size;
5460 /* addrlen has to be of type int because that’s how WSARecvFrom() is defined */
5461 G_STATIC_ASSERT (sizeof addr <= G_MAXINT);
5463 addrlen = sizeof addr;
5465 result = WSARecvFrom (socket->priv->fd,
5467 &bytes_received, &win_flags,
5468 (struct sockaddr *)&addr, &addrlen,
5471 result = WSARecv (socket->priv->fd,
5473 &bytes_received, &win_flags,
5477 int errsv = get_socket_errno ();
5479 if (errsv == WSAEINTR)
5482 win32_unset_event_mask (socket, FD_READ);
5484 if (errsv == WSAEWOULDBLOCK)
5486 if (timeout_us != 0)
5488 if (!block_on_timeout (socket, G_IO_IN, timeout_us,
5489 start_time, cancellable, error))
5496 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5499 win32_unset_event_mask (socket, FD_READ);
5503 /* decode address */
5504 if (address != NULL)
5506 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
5509 /* capture the flags */
5513 if (messages != NULL)
5515 if (num_messages != NULL)
5518 return bytes_received;
5524 * g_socket_receive_messages:
5525 * @socket: a #GSocket
5526 * @messages: (array length=num_messages): an array of #GInputMessage structs
5527 * @num_messages: the number of elements in @messages
5528 * @flags: an int containing #GSocketMsgFlags flags for the overall operation,
5529 * which may additionally contain
5530 * [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5531 * @cancellable: (nullable): a %GCancellable or %NULL
5532 * @error: #GError for error reporting, or %NULL to ignore
5534 * Receive multiple data messages from @socket in one go. This is the most
5535 * complicated and fully-featured version of this call. For easier use, see
5536 * g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
5538 * @messages must point to an array of #GInputMessage structs and
5539 * @num_messages must be the length of this array. Each #GInputMessage
5540 * contains a pointer to an array of #GInputVector structs describing the
5541 * buffers that the data received in each message will be written to. Using
5542 * multiple #GInputVectors is more memory-efficient than manually copying data
5543 * out of a single buffer to multiple sources, and more system-call-efficient
5544 * than making multiple calls to g_socket_receive(), such as in scenarios where
5545 * a lot of data packets need to be received (e.g. high-bandwidth video
5546 * streaming over RTP/UDP).
5548 * @flags modify how all messages are received. The commonly available
5549 * arguments for this are available in the #GSocketMsgFlags enum, but the
5550 * values there are the same as the system values, and the flags
5551 * are passed in as-is, so you can pass in system-specific flags too. These
5552 * flags affect the overall receive operation. Flags affecting individual
5553 * messages are returned in #GInputMessage.flags.
5555 * The other members of #GInputMessage are treated as described in its
5558 * If #GSocket:blocking is %TRUE the call will block until @num_messages have
5559 * been received, or the end of the stream is reached.
5561 * If #GSocket:blocking is %FALSE the call will return up to @num_messages
5562 * without blocking, or %G_IO_ERROR_WOULD_BLOCK if no messages are queued in the
5563 * operating system to be received.
5565 * In blocking mode, if #GSocket:timeout is positive and is reached before any
5566 * messages are received, %G_IO_ERROR_TIMED_OUT is returned, otherwise up to
5567 * @num_messages are returned. (Note: This is effectively the
5568 * behaviour of `MSG_WAITFORONE` with recvmmsg().)
5570 * To be notified when messages are available, wait for the
5571 * %G_IO_IN condition. Note though that you may still receive
5572 * %G_IO_ERROR_WOULD_BLOCK from g_socket_receive_messages() even if you were
5573 * previously notified of a %G_IO_IN condition.
5575 * If the remote peer closes the connection, any messages queued in the
5576 * operating system will be returned, and subsequent calls to
5577 * g_socket_receive_messages() will return 0 (with no error set).
5579 * On error -1 is returned and @error is set accordingly. An error will only
5580 * be returned if zero messages could be received; otherwise the number of
5581 * messages successfully received before the error will be returned.
5583 * Returns: number of messages received, or -1 on error. Note that the number
5584 * of messages received may be smaller than @num_messages if in non-blocking
5585 * mode, if the peer closed the connection, or if @num_messages
5586 * was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
5587 * to receive the remaining messages.
5592 g_socket_receive_messages (GSocket *socket,
5593 GInputMessage *messages,
5596 GCancellable *cancellable,
5599 if (!check_socket (socket, error) ||
5600 !check_timeout (socket, error))
5603 return g_socket_receive_messages_with_timeout (socket, messages, num_messages,
5605 socket->priv->blocking ? -1 : 0,
5606 cancellable, error);
5610 g_socket_receive_messages_with_timeout (GSocket *socket,
5611 GInputMessage *messages,
5615 GCancellable *cancellable,
5620 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5621 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5622 g_return_val_if_fail (cancellable == NULL ||
5623 G_IS_CANCELLABLE (cancellable), -1);
5624 g_return_val_if_fail (error == NULL || *error == NULL, -1);
5626 start_time = g_get_monotonic_time ();
5628 if (!check_socket (socket, error))
5631 if (!check_timeout (socket, error))
5634 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5637 if (num_messages == 0)
5640 #if !defined (G_OS_WIN32) && defined (HAVE_RECVMMSG)
5642 struct mmsghdr *msgvec;
5643 guint i, num_received;
5645 /* Clamp the number of vectors if more given than we can write in one go.
5646 * The caller has to handle short writes anyway.
5648 if (num_messages > G_IOV_MAX)
5649 num_messages = G_IOV_MAX;
5651 msgvec = g_newa (struct mmsghdr, num_messages);
5653 for (i = 0; i < num_messages; ++i)
5655 GInputMessage *msg = &messages[i];
5656 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5658 input_message_to_msghdr (msg, msg_hdr);
5659 msgvec[i].msg_len = 0;
5662 /* We always set the close-on-exec flag so we don't leak file
5663 * descriptors into child processes. Note that gunixfdmessage.c
5664 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5666 #ifdef MSG_CMSG_CLOEXEC
5667 flags |= MSG_CMSG_CLOEXEC;
5670 for (num_received = 0; num_received < num_messages;)
5674 /* We operate in non-blocking mode and handle the timeout ourselves. */
5675 ret = recvmmsg (socket->priv->fd,
5676 msgvec + num_received,
5677 num_messages - num_received,
5678 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5679 #ifdef MSG_CMSG_CLOEXEC
5680 if (ret < 0 && get_socket_errno () == EINVAL)
5682 /* We must be running on an old kernel. Call without the flag. */
5683 flags &= ~(MSG_CMSG_CLOEXEC);
5684 ret = recvmmsg (socket->priv->fd,
5685 msgvec + num_received,
5686 num_messages - num_received,
5687 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5693 int errsv = get_socket_errno ();
5698 if (timeout_us != 0 &&
5699 (errsv == EWOULDBLOCK ||
5702 if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
5703 cancellable, error))
5705 if (num_received > 0)
5707 g_clear_error (error);
5717 /* If any messages were successfully received, do not error. */
5718 if (num_received > 0)
5721 socket_set_error_lazy (error, errsv,
5722 _("Error receiving message: %s"));
5732 num_received += ret;
5735 for (i = 0; i < num_received; ++i)
5737 input_message_from_msghdr (&msgvec[i].msg_hdr, &messages[i], socket);
5738 messages[i].bytes_received = msgvec[i].msg_len;
5741 return num_received;
5746 gint64 wait_timeout;
5748 wait_timeout = timeout_us;
5750 for (i = 0; i < num_messages; i++)
5752 GInputMessage *msg = &messages[i];
5754 GError *msg_error = NULL;
5756 msg->flags = flags; /* in-out parameter */
5758 len = g_socket_receive_message_with_timeout (socket,
5762 msg->control_messages,
5763 (gint *) msg->num_control_messages,
5769 /* check if we've timed out or how much time to wait at most */
5772 gint64 elapsed = g_get_monotonic_time () - start_time;
5773 wait_timeout = MAX (timeout_us - elapsed, 1);
5777 msg->bytes_received = len;
5780 (g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK) ||
5781 g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)))
5783 g_clear_error (&msg_error);
5787 if (msg_error != NULL)
5789 g_propagate_error (error, msg_error);
5803 * g_socket_receive_message:
5804 * @socket: a #GSocket
5805 * @address: (out) (optional): a pointer to a #GSocketAddress
5807 * @vectors: (array length=num_vectors): an array of #GInputVector structs
5808 * @num_vectors: the number of elements in @vectors, or -1
5809 * @messages: (array length=num_messages) (out) (optional) (nullable): a pointer
5810 * which may be filled with an array of #GSocketControlMessages, or %NULL
5811 * @num_messages: (out): a pointer which will be filled with the number of
5812 * elements in @messages, or %NULL
5813 * @flags: (inout): a pointer to an int containing #GSocketMsgFlags flags,
5814 * which may additionally contain
5815 * [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5816 * @cancellable: a %GCancellable or %NULL
5817 * @error: a #GError pointer, or %NULL
5819 * Receive data from a socket. For receiving multiple messages, see
5820 * g_socket_receive_messages(); for easier use, see
5821 * g_socket_receive() and g_socket_receive_from().
5823 * If @address is non-%NULL then @address will be set equal to the
5824 * source address of the received packet.
5825 * @address is owned by the caller.
5827 * @vector must point to an array of #GInputVector structs and
5828 * @num_vectors must be the length of this array. These structs
5829 * describe the buffers that received data will be scattered into.
5830 * If @num_vectors is -1, then @vectors is assumed to be terminated
5831 * by a #GInputVector with a %NULL buffer pointer.
5833 * As a special case, if @num_vectors is 0 (in which case, @vectors
5834 * may of course be %NULL), then a single byte is received and
5835 * discarded. This is to facilitate the common practice of sending a
5836 * single '\0' byte for the purposes of transferring ancillary data.
5838 * @messages, if non-%NULL, will be set to point to a newly-allocated
5839 * array of #GSocketControlMessage instances or %NULL if no such
5840 * messages was received. These correspond to the control messages
5841 * received from the kernel, one #GSocketControlMessage per message
5842 * from the kernel. This array is %NULL-terminated and must be freed
5843 * by the caller using g_free() after calling g_object_unref() on each
5844 * element. If @messages is %NULL, any control messages received will
5847 * @num_messages, if non-%NULL, will be set to the number of control
5848 * messages received.
5850 * If both @messages and @num_messages are non-%NULL, then
5851 * @num_messages gives the number of #GSocketControlMessage instances
5852 * in @messages (ie: not including the %NULL terminator).
5854 * @flags is an in/out parameter. The commonly available arguments
5855 * for this are available in the #GSocketMsgFlags enum, but the
5856 * values there are the same as the system values, and the flags
5857 * are passed in as-is, so you can pass in system-specific flags too
5858 * (and g_socket_receive_message() may pass system-specific flags out).
5859 * Flags passed in to the parameter affect the receive operation; flags returned
5860 * out of it are relevant to the specific returned message.
5862 * As with g_socket_receive(), data may be discarded if @socket is
5863 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
5864 * provide enough buffer space to read a complete message. You can pass
5865 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
5866 * removing it from the receive queue, but there is no portable way to find
5867 * out the length of the message other than by reading it into a
5868 * sufficiently-large buffer.
5870 * If the socket is in blocking mode the call will block until there
5871 * is some data to receive, the connection is closed, or there is an
5872 * error. If there is no data available and the socket is in
5873 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
5874 * returned. To be notified when data is available, wait for the
5875 * %G_IO_IN condition.
5877 * On error -1 is returned and @error is set accordingly.
5879 * Returns: Number of bytes read, or 0 if the connection was closed by
5880 * the peer, or -1 on error
5885 g_socket_receive_message (GSocket *socket,
5886 GSocketAddress **address,
5887 GInputVector *vectors,
5889 GSocketControlMessage ***messages,
5892 GCancellable *cancellable,
5895 return g_socket_receive_message_with_timeout (socket, address, vectors,
5896 num_vectors, messages,
5897 num_messages, flags,
5898 socket->priv->blocking ? -1 : 0,
5899 cancellable, error);
5903 * g_socket_get_credentials:
5904 * @socket: a #GSocket.
5905 * @error: #GError for error reporting, or %NULL to ignore.
5907 * Returns the credentials of the foreign process connected to this
5908 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
5911 * If this operation isn't supported on the OS, the method fails with
5912 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
5913 * by reading the %SO_PEERCRED option on the underlying socket.
5915 * This method can be expected to be available on the following platforms:
5917 * - Linux since GLib 2.26
5918 * - OpenBSD since GLib 2.30
5919 * - Solaris, Illumos and OpenSolaris since GLib 2.40
5920 * - NetBSD since GLib 2.42
5921 * - macOS, tvOS, iOS since GLib 2.66
5923 * Other ways to obtain credentials from a foreign peer includes the
5924 * #GUnixCredentialsMessage type and
5925 * g_unix_connection_send_credentials() /
5926 * g_unix_connection_receive_credentials() functions.
5928 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
5929 * that must be freed with g_object_unref().
5934 g_socket_get_credentials (GSocket *socket,
5939 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
5940 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5942 if (!check_socket (socket, error))
5947 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
5951 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
5952 socklen_t optlen = sizeof (native_creds_buf);
5954 if (getsockopt (socket->priv->fd,
5960 ret = g_credentials_new ();
5961 g_credentials_set_native (ret,
5962 G_CREDENTIALS_NATIVE_TYPE,
5966 #elif G_CREDENTIALS_USE_APPLE_XUCRED
5969 socklen_t optlen = sizeof (cred);
5971 if (getsockopt (socket->priv->fd,
5977 if (cred.cr_version == XUCRED_VERSION)
5979 ret = g_credentials_new ();
5980 g_credentials_set_native (ret,
5981 G_CREDENTIALS_NATIVE_TYPE,
5988 G_IO_ERROR_NOT_SUPPORTED,
5989 /* No point in translating this! */
5990 "struct xucred cr_version %u != %u",
5991 cred.cr_version, XUCRED_VERSION);
5992 /* Reuse a translatable string we already have */
5993 g_prefix_error (error,
5994 _("Unable to read socket credentials: %s"),
6001 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
6003 struct unpcbid cred;
6004 socklen_t optlen = sizeof (cred);
6006 if (getsockopt (socket->priv->fd,
6012 ret = g_credentials_new ();
6013 g_credentials_set_native (ret,
6014 G_CREDENTIALS_NATIVE_TYPE,
6018 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
6020 ucred_t *ucred = NULL;
6022 if (getpeerucred (socket->priv->fd, &ucred) == 0)
6024 ret = g_credentials_new ();
6025 g_credentials_set_native (ret,
6026 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
6032 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
6037 int errsv = get_socket_errno ();
6041 socket_io_error_from_errno (errsv),
6042 _("Unable to read socket credentials: %s"),
6043 socket_strerror (errsv));
6048 g_set_error_literal (error,
6050 G_IO_ERROR_NOT_SUPPORTED,
6051 _("g_socket_get_credentials not implemented for this OS"));
6058 * g_socket_get_option:
6059 * @socket: a #GSocket
6060 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
6061 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
6062 * @value: (out): return location for the option value
6063 * @error: #GError for error reporting, or %NULL to ignore.
6065 * Gets the value of an integer-valued option on @socket, as with
6066 * getsockopt(). (If you need to fetch a non-integer-valued option,
6067 * you will need to call getsockopt() directly.)
6069 * The [<gio/gnetworking.h>][gio-gnetworking.h]
6070 * header pulls in system headers that will define most of the
6071 * standard/portable socket options. For unusual socket protocols or
6072 * platform-dependent options, you may need to include additional
6075 * Note that even for socket options that are a single byte in size,
6076 * @value is still a pointer to a #gint variable, not a #guchar;
6077 * g_socket_get_option() will handle the conversion internally.
6079 * Returns: success or failure. On failure, @error will be set, and
6080 * the system error value (`errno` or WSAGetLastError()) will still
6081 * be set to the result of the getsockopt() call.
6086 g_socket_get_option (GSocket *socket,
6094 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
6096 /* g_socket_get_option() is called during socket init, so skip the init checks
6097 * in check_socket() */
6098 if (socket->priv->inited && !check_socket (socket, error))
6102 size = sizeof (gint);
6103 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
6105 int errsv = get_socket_errno ();
6107 g_set_error_literal (error,
6109 socket_io_error_from_errno (errsv),
6110 socket_strerror (errsv));
6112 /* Reset errno in case the caller wants to look at it */
6118 #if G_BYTE_ORDER == G_BIG_ENDIAN
6119 /* If the returned value is smaller than an int then we need to
6120 * slide it over into the low-order bytes of *value.
6122 if (size != sizeof (gint))
6123 *value = *value >> (8 * (sizeof (gint) - size));
6130 * g_socket_set_option:
6131 * @socket: a #GSocket
6132 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
6133 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
6134 * @value: the value to set the option to
6135 * @error: #GError for error reporting, or %NULL to ignore.
6137 * Sets the value of an integer-valued option on @socket, as with
6138 * setsockopt(). (If you need to set a non-integer-valued option,
6139 * you will need to call setsockopt() directly.)
6141 * The [<gio/gnetworking.h>][gio-gnetworking.h]
6142 * header pulls in system headers that will define most of the
6143 * standard/portable socket options. For unusual socket protocols or
6144 * platform-dependent options, you may need to include additional
6147 * Returns: success or failure. On failure, @error will be set, and
6148 * the system error value (`errno` or WSAGetLastError()) will still
6149 * be set to the result of the setsockopt() call.
6154 g_socket_set_option (GSocket *socket,
6162 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
6164 if (!check_socket (socket, error))
6167 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
6170 #if !defined (__linux__) && !defined (G_OS_WIN32)
6171 /* Linux and Windows let you set a single-byte value from an int,
6172 * but most other platforms don't.
6174 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
6176 #if G_BYTE_ORDER == G_BIG_ENDIAN
6177 value = value << (8 * (sizeof (gint) - 1));
6179 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
6184 errsv = get_socket_errno ();
6186 g_set_error_literal (error,
6188 socket_io_error_from_errno (errsv),
6189 socket_strerror (errsv));