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 * SPDX-License-Identifier: LGPL-2.1-or-later
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General
21 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
23 * Authors: Christian Kellner <gicmo@gnome.org>
24 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
25 * Ryan Lortie <desrt@desrt.ca>
26 * Alexander Larsson <alexl@redhat.com>
27 * Philip Withnall <philip.withnall@collabora.co.uk>
35 #include "glib-unix.h"
46 # include <sys/ioctl.h>
49 #ifdef HAVE_SIOCGIFADDR
53 #ifdef HAVE_SYS_FILIO_H
54 # include <sys/filio.h>
61 #define GOBJECT_COMPILATION
62 #include "gobject/gtype-private.h" /* For _PRELUDE type define */
63 #undef GOBJECT_COMPILATION
64 #include "gcancellable.h"
65 #include "gdatagrambased.h"
66 #include "gioenumtypes.h"
67 #include "ginetaddress.h"
68 #include "ginetsocketaddress.h"
69 #include "ginitable.h"
73 #include "gnetworkingprivate.h"
74 #include "gsocketaddress.h"
75 #include "gsocketcontrolmessage.h"
76 #include "gcredentials.h"
77 #include "gcredentialsprivate.h"
79 #include "gioprivate.h"
82 #include "giowin32-afunix.h"
87 * @short_description: Low-level socket object
89 * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
91 * A #GSocket is a low-level networking primitive. It is a more or less
92 * direct mapping of the BSD socket API in a portable GObject based API.
93 * It supports both the UNIX socket implementations and winsock2 on Windows.
95 * #GSocket is the platform independent base upon which the higher level
96 * network primitives are based. Applications are not typically meant to
97 * use it directly, but rather through classes like #GSocketClient,
98 * #GSocketService and #GSocketConnection. However there may be cases where
99 * direct use of #GSocket is useful.
101 * #GSocket implements the #GInitable interface, so if it is manually constructed
102 * by e.g. g_object_new() you must call g_initable_init() and check the
103 * results before using the object. This is done automatically in
104 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
107 * Sockets operate in two general modes, blocking or non-blocking. When
108 * in blocking mode all operations (which don’t take an explicit blocking
109 * parameter) block until the requested operation
110 * is finished or there is an error. In non-blocking mode all calls that
111 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
112 * To know when a call would successfully run you can call g_socket_condition_check(),
113 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
114 * attach it to a #GMainContext to get callbacks when I/O is possible.
115 * Note that all sockets are always set to non blocking mode in the system, and
116 * blocking mode is emulated in GSocket.
118 * When working in non-blocking mode applications should always be able to
119 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
120 * function said that I/O was possible. This can easily happen in case
121 * of a race condition in the application, but it can also happen for other
122 * reasons. For instance, on Windows a socket is always seen as writable
123 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
125 * #GSockets can be either connection oriented or datagram based.
126 * For connection oriented types you must first establish a connection by
127 * either connecting to an address or accepting a connection from another
128 * address. For connectionless socket types the target/source address is
129 * specified or received in each I/O operation.
131 * All socket file descriptors are set to be close-on-exec.
133 * Note that creating a #GSocket causes the signal %SIGPIPE to be
134 * ignored for the remainder of the program. If you are writing a
135 * command-line utility that uses #GSocket, you may need to take into
136 * account the fact that your program will not automatically be killed
137 * if it tries to write to %stdout after it has been closed.
139 * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
140 * a #GSocket concurrently from multiple threads, you must implement your own
146 static void g_socket_initable_iface_init (GInitableIface *iface);
147 static gboolean g_socket_initable_init (GInitable *initable,
148 GCancellable *cancellable,
151 static void g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface);
152 static gint g_socket_datagram_based_receive_messages (GDatagramBased *self,
153 GInputMessage *messages,
157 GCancellable *cancellable,
159 static gint g_socket_datagram_based_send_messages (GDatagramBased *self,
160 GOutputMessage *messages,
164 GCancellable *cancellable,
166 static GSource *g_socket_datagram_based_create_source (GDatagramBased *self,
167 GIOCondition condition,
168 GCancellable *cancellable);
169 static GIOCondition g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
170 GIOCondition condition);
171 static gboolean g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
172 GIOCondition condition,
174 GCancellable *cancellable,
177 static GSocketAddress *
178 cache_recv_address (GSocket *socket, struct sockaddr *native, size_t native_len);
181 g_socket_receive_message_with_timeout (GSocket *socket,
182 GSocketAddress **address,
183 GInputVector *vectors,
185 GSocketControlMessage ***messages,
189 GCancellable *cancellable,
192 g_socket_receive_messages_with_timeout (GSocket *socket,
193 GInputMessage *messages,
197 GCancellable *cancellable,
200 g_socket_send_messages_with_timeout (GSocket *socket,
201 GOutputMessage *messages,
205 GCancellable *cancellable,
223 PROP_MULTICAST_LOOPBACK,
227 /* Size of the receiver cache for g_socket_receive_from() */
228 #define RECV_ADDR_CACHE_SIZE 8
230 struct _GSocketPrivate
232 GSocketFamily family;
234 GSocketProtocol protocol;
238 GError *construct_error;
239 GSocketAddress *remote_address;
244 guint connected_read : 1;
245 guint connected_write : 1;
248 guint connect_pending : 1;
252 DWORD waiting_result;
256 GList *requested_conditions; /* list of requested GIOCondition * */
257 GMutex win32_source_lock;
258 GCond win32_source_cond;
262 GSocketAddress *addr;
263 struct sockaddr *native;
266 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
269 _G_DEFINE_TYPE_EXTENDED_WITH_PRELUDE (GSocket, g_socket, G_TYPE_OBJECT, 0,
270 /* Need a prelude for https://bugzilla.gnome.org/show_bug.cgi?id=674885 */
271 g_type_ensure (G_TYPE_SOCKET_FAMILY);
272 g_type_ensure (G_TYPE_SOCKET_TYPE);
273 g_type_ensure (G_TYPE_SOCKET_PROTOCOL);
274 g_type_ensure (G_TYPE_SOCKET_ADDRESS);
275 /* And networking init is appropriate for the prelude */
276 g_networking_init ();
277 , /* And now the regular type init code */
278 G_ADD_PRIVATE (GSocket)
279 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
280 g_socket_initable_iface_init);
281 G_IMPLEMENT_INTERFACE (G_TYPE_DATAGRAM_BASED,
282 g_socket_datagram_based_iface_init));
285 get_socket_errno (void)
290 return WSAGetLastError ();
295 socket_io_error_from_errno (int err)
298 return g_io_error_from_win32_error (err);
300 return g_io_error_from_errno (err);
305 socket_strerror (int err)
308 return g_strerror (err);
313 msg = g_win32_error_message (err);
315 msg_ret = g_intern_string (msg);
322 /* Wrapper around g_set_error() to avoid doing excess work */
323 #define socket_set_error_lazy(err, errsv, fmt) \
325 GError **__err = (err); \
326 int __errsv = (errsv); \
330 int __code = socket_io_error_from_errno (__errsv); \
331 const char *__strerr = socket_strerror (__errsv); \
333 if (__code == G_IO_ERROR_WOULD_BLOCK) \
334 g_set_error_literal (__err, G_IO_ERROR, __code, __strerr); \
336 g_set_error (__err, G_IO_ERROR, __code, fmt, __strerr); \
341 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
343 _win32_unset_event_mask (GSocket *socket, int mask)
345 g_mutex_lock (&socket->priv->win32_source_lock);
346 socket->priv->current_events &= ~mask;
347 socket->priv->current_errors &= ~mask;
348 g_mutex_unlock (&socket->priv->win32_source_lock);
351 #define win32_unset_event_mask(_socket, _mask)
354 /* Windows has broken prototypes... */
356 #define getsockopt(sockfd, level, optname, optval, optlen) \
357 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
358 #define setsockopt(sockfd, level, optname, optval, optlen) \
359 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
360 #define getsockname(sockfd, addr, addrlen) \
361 getsockname (sockfd, addr, (int *)addrlen)
362 #define getpeername(sockfd, addr, addrlen) \
363 getpeername (sockfd, addr, (int *)addrlen)
364 #define recv(sockfd, buf, len, flags) \
365 recv (sockfd, (gpointer)buf, len, flags)
369 address_to_string (GSocketAddress *address)
371 GString *ret = g_string_new ("");
373 if (G_IS_INET_SOCKET_ADDRESS (address))
375 GInetSocketAddress *isa = G_INET_SOCKET_ADDRESS (address);
376 GInetAddress *ia = g_inet_socket_address_get_address (isa);
377 GSocketFamily family = g_inet_address_get_family (ia);
380 /* Represent IPv6 addresses in URL style:
381 * ::1 port 12345 -> [::1]:12345 */
382 if (family == G_SOCKET_FAMILY_IPV6)
383 g_string_append_c (ret, '[');
385 tmp = g_inet_address_to_string (ia);
386 g_string_append (ret, tmp);
389 if (family == G_SOCKET_FAMILY_IPV6)
391 guint32 scope = g_inet_socket_address_get_scope_id (isa);
394 g_string_append_printf (ret, "%%%u", scope);
396 g_string_append_c (ret, ']');
399 g_string_append_c (ret, ':');
401 g_string_append_printf (ret, "%u", g_inet_socket_address_get_port (isa));
405 /* For unknown address types, just show the type */
406 g_string_append_printf (ret, "(%s)", G_OBJECT_TYPE_NAME (address));
409 return g_string_free (ret, FALSE);
413 check_socket (GSocket *socket,
416 if (!socket->priv->inited)
418 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
419 _("Invalid socket, not initialized"));
423 if (socket->priv->construct_error)
425 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
426 _("Invalid socket, initialization failed due to: %s"),
427 socket->priv->construct_error->message);
431 if (socket->priv->closed)
433 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
434 _("Socket is already closed"));
442 check_timeout (GSocket *socket,
445 if (socket->priv->timed_out)
447 socket->priv->timed_out = FALSE;
448 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
449 _("Socket I/O timed out"));
457 g_socket_details_from_fd (GSocket *socket)
460 struct sockaddr_storage storage;
468 memset (&address, 0, sizeof (address));
470 fd = socket->priv->fd;
471 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
473 errsv = get_socket_errno ();
480 socket->priv->type = G_SOCKET_TYPE_STREAM;
484 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
488 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
492 socket->priv->type = G_SOCKET_TYPE_INVALID;
496 addrlen = sizeof address;
497 if (getsockname (fd, &address.sa, &addrlen) != 0)
499 errsv = get_socket_errno ();
505 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
506 (socklen_t) sizeof address.storage.ss_family <= addrlen);
507 family = address.storage.ss_family;
511 /* On Solaris, this happens if the socket is not yet connected.
512 * But we can use SO_DOMAIN as a workaround there.
515 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
517 errsv = get_socket_errno ();
521 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
529 case G_SOCKET_FAMILY_IPV4:
530 case G_SOCKET_FAMILY_IPV6:
531 socket->priv->family = address.storage.ss_family;
532 switch (socket->priv->type)
534 case G_SOCKET_TYPE_STREAM:
535 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
538 case G_SOCKET_TYPE_DATAGRAM:
539 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
542 case G_SOCKET_TYPE_SEQPACKET:
543 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
551 case G_SOCKET_FAMILY_UNIX:
552 socket->priv->family = G_SOCKET_FAMILY_UNIX;
553 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
557 socket->priv->family = G_SOCKET_FAMILY_INVALID;
561 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
563 addrlen = sizeof address;
564 if (getpeername (fd, &address.sa, &addrlen) >= 0)
566 socket->priv->connected_read = TRUE;
567 socket->priv->connected_write = TRUE;
571 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
573 socket->priv->keepalive = !!value;
577 /* Can't read, maybe not supported, assume FALSE */
578 socket->priv->keepalive = FALSE;
584 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
585 socket_io_error_from_errno (errsv),
586 _("creating GSocket from fd: %s"),
587 socket_strerror (errsv));
591 socket_set_nonblock (int fd)
594 GError *error = NULL;
599 /* Always use native nonblocking sockets, as Windows sets sockets to
600 * nonblocking automatically in certain operations. This way we make
601 * things work the same on all platforms.
604 if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
606 g_warning ("Error setting socket to nonblocking mode: %s", error->message);
607 g_clear_error (&error);
612 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
614 int errsv = get_socket_errno ();
615 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
620 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c.
621 * It always sets SOCK_CLOEXEC | SOCK_NONBLOCK. */
623 g_socket (gint domain,
630 #if defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
631 fd = socket (domain, type | SOCK_CLOEXEC | SOCK_NONBLOCK, protocol);
636 /* It's possible that libc has SOCK_CLOEXEC and/or SOCK_NONBLOCK but the kernel does not */
637 if (fd < 0 && (errsv == EINVAL || errsv == EPROTOTYPE))
639 fd = socket (domain, type, protocol);
643 errsv = get_socket_errno ();
645 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
646 _("Unable to create socket: %s"), socket_strerror (errsv));
655 /* We always want to set close-on-exec to protect users. If you
656 need to so some weird inheritance to exec you can re-enable this
657 using lower level hacks with g_socket_get_fd(). */
658 flags = fcntl (fd, F_GETFD, 0);
660 (flags & FD_CLOEXEC) == 0)
663 (void) fcntl (fd, F_SETFD, flags);
667 if ((domain == AF_INET || domain == AF_INET6) && type == SOCK_DGRAM)
669 BOOL new_behavior = FALSE;
670 DWORD bytes_returned = 0;
672 /* Disable connection reset error on ICMP port unreachable. */
673 WSAIoctl (fd, SIO_UDP_CONNRESET, &new_behavior, sizeof (new_behavior),
674 NULL, 0, &bytes_returned, NULL, NULL);
678 /* Ensure the socket is non-blocking. */
679 socket_set_nonblock (fd);
684 /* Returned socket has SOCK_CLOEXEC | SOCK_NONBLOCK set. */
686 g_socket_create_socket (GSocketFamily family,
695 case G_SOCKET_TYPE_STREAM:
696 native_type = SOCK_STREAM;
699 case G_SOCKET_TYPE_DATAGRAM:
700 native_type = SOCK_DGRAM;
703 case G_SOCKET_TYPE_SEQPACKET:
704 native_type = SOCK_SEQPACKET;
708 g_assert_not_reached ();
713 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
714 _("Unable to create socket: %s"), _("Unknown family was specified"));
720 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
721 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
725 return g_socket (family, native_type, protocol, error);
729 g_socket_constructed (GObject *object)
731 GSocket *socket = G_SOCKET (object);
733 if (socket->priv->fd >= 0)
735 /* create socket->priv info from the fd and ensure it’s non-blocking */
736 g_socket_details_from_fd (socket);
737 socket_set_nonblock (socket->priv->fd);
741 /* create the fd from socket->priv info; this sets it non-blocking by construction */
742 socket->priv->fd = g_socket_create_socket (socket->priv->family,
744 socket->priv->protocol,
745 &socket->priv->construct_error);
748 if (socket->priv->fd != -1)
751 /* See note about SIGPIPE below. */
752 g_socket_set_option (socket, SOL_SOCKET, SO_NOSIGPIPE, TRUE, NULL);
758 g_socket_get_property (GObject *object,
763 GSocket *socket = G_SOCKET (object);
764 GSocketAddress *address;
769 g_value_set_enum (value, socket->priv->family);
773 g_value_set_enum (value, socket->priv->type);
777 g_value_set_enum (value, socket->priv->protocol);
781 g_value_set_int (value, socket->priv->fd);
785 g_value_set_boolean (value, socket->priv->blocking);
788 case PROP_LISTEN_BACKLOG:
789 g_value_set_int (value, socket->priv->listen_backlog);
793 g_value_set_boolean (value, socket->priv->keepalive);
796 case PROP_LOCAL_ADDRESS:
797 address = g_socket_get_local_address (socket, NULL);
798 g_value_take_object (value, address);
801 case PROP_REMOTE_ADDRESS:
802 address = g_socket_get_remote_address (socket, NULL);
803 g_value_take_object (value, address);
807 g_value_set_uint (value, socket->priv->timeout);
811 g_value_set_uint (value, g_socket_get_ttl (socket));
815 g_value_set_boolean (value, g_socket_get_broadcast (socket));
818 case PROP_MULTICAST_LOOPBACK:
819 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
822 case PROP_MULTICAST_TTL:
823 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
827 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
832 g_socket_set_property (GObject *object,
837 GSocket *socket = G_SOCKET (object);
842 socket->priv->family = g_value_get_enum (value);
846 socket->priv->type = g_value_get_enum (value);
850 socket->priv->protocol = g_value_get_enum (value);
854 socket->priv->fd = g_value_get_int (value);
858 g_socket_set_blocking (socket, g_value_get_boolean (value));
861 case PROP_LISTEN_BACKLOG:
862 g_socket_set_listen_backlog (socket, g_value_get_int (value));
866 g_socket_set_keepalive (socket, g_value_get_boolean (value));
870 g_socket_set_timeout (socket, g_value_get_uint (value));
874 g_socket_set_ttl (socket, g_value_get_uint (value));
878 g_socket_set_broadcast (socket, g_value_get_boolean (value));
881 case PROP_MULTICAST_LOOPBACK:
882 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
885 case PROP_MULTICAST_TTL:
886 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
890 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
895 g_socket_finalize (GObject *object)
897 GSocket *socket = G_SOCKET (object);
900 g_clear_error (&socket->priv->construct_error);
902 if (socket->priv->fd != -1 &&
903 !socket->priv->closed)
904 g_socket_close (socket, NULL);
906 if (socket->priv->remote_address)
907 g_object_unref (socket->priv->remote_address);
910 if (socket->priv->event != WSA_INVALID_EVENT)
912 WSACloseEvent (socket->priv->event);
913 socket->priv->event = WSA_INVALID_EVENT;
916 g_assert (socket->priv->requested_conditions == NULL);
917 g_mutex_clear (&socket->priv->win32_source_lock);
918 g_cond_clear (&socket->priv->win32_source_cond);
921 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
923 if (socket->priv->recv_addr_cache[i].addr)
925 g_object_unref (socket->priv->recv_addr_cache[i].addr);
926 g_free (socket->priv->recv_addr_cache[i].native);
930 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
931 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
935 g_socket_class_init (GSocketClass *klass)
937 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
940 /* There is no portable, thread-safe way to avoid having the process
941 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
942 * forced to simply ignore the signal process-wide.
944 * Even if we ignore it though, gdb will still stop if the app
945 * receives a SIGPIPE, which can be confusing and annoying. So when
946 * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
947 * prevent the signal from occurring at all.
949 signal (SIGPIPE, SIG_IGN);
952 gobject_class->finalize = g_socket_finalize;
953 gobject_class->constructed = g_socket_constructed;
954 gobject_class->set_property = g_socket_set_property;
955 gobject_class->get_property = g_socket_get_property;
957 g_object_class_install_property (gobject_class, PROP_FAMILY,
958 g_param_spec_enum ("family",
960 P_("The sockets address family"),
961 G_TYPE_SOCKET_FAMILY,
962 G_SOCKET_FAMILY_INVALID,
963 G_PARAM_CONSTRUCT_ONLY |
965 G_PARAM_STATIC_STRINGS));
967 g_object_class_install_property (gobject_class, PROP_TYPE,
968 g_param_spec_enum ("type",
970 P_("The sockets type"),
972 G_SOCKET_TYPE_STREAM,
973 G_PARAM_CONSTRUCT_ONLY |
975 G_PARAM_STATIC_STRINGS));
977 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
978 g_param_spec_enum ("protocol",
979 P_("Socket protocol"),
980 P_("The id of the protocol to use, or -1 for unknown"),
981 G_TYPE_SOCKET_PROTOCOL,
982 G_SOCKET_PROTOCOL_UNKNOWN,
983 G_PARAM_CONSTRUCT_ONLY |
985 G_PARAM_STATIC_STRINGS));
987 g_object_class_install_property (gobject_class, PROP_FD,
988 g_param_spec_int ("fd",
989 P_("File descriptor"),
990 P_("The sockets file descriptor"),
994 G_PARAM_CONSTRUCT_ONLY |
996 G_PARAM_STATIC_STRINGS));
998 g_object_class_install_property (gobject_class, PROP_BLOCKING,
999 g_param_spec_boolean ("blocking",
1001 P_("Whether or not I/O on this socket is blocking"),
1004 G_PARAM_STATIC_STRINGS));
1006 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
1007 g_param_spec_int ("listen-backlog",
1008 P_("Listen backlog"),
1009 P_("Outstanding connections in the listen queue"),
1014 G_PARAM_STATIC_STRINGS));
1016 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
1017 g_param_spec_boolean ("keepalive",
1018 P_("Keep connection alive"),
1019 P_("Keep connection alive by sending periodic pings"),
1022 G_PARAM_STATIC_STRINGS));
1024 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
1025 g_param_spec_object ("local-address",
1026 P_("Local address"),
1027 P_("The local address the socket is bound to"),
1028 G_TYPE_SOCKET_ADDRESS,
1030 G_PARAM_STATIC_STRINGS));
1032 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
1033 g_param_spec_object ("remote-address",
1034 P_("Remote address"),
1035 P_("The remote address the socket is connected to"),
1036 G_TYPE_SOCKET_ADDRESS,
1038 G_PARAM_STATIC_STRINGS));
1043 * The timeout in seconds on socket I/O
1047 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
1048 g_param_spec_uint ("timeout",
1050 P_("The timeout in seconds on socket I/O"),
1055 G_PARAM_STATIC_STRINGS));
1058 * GSocket:broadcast:
1060 * Whether the socket should allow sending to broadcast addresses.
1064 g_object_class_install_property (gobject_class, PROP_BROADCAST,
1065 g_param_spec_boolean ("broadcast",
1067 P_("Whether to allow sending to broadcast addresses"),
1070 G_PARAM_STATIC_STRINGS));
1075 * Time-to-live for outgoing unicast packets
1079 g_object_class_install_property (gobject_class, PROP_TTL,
1080 g_param_spec_uint ("ttl",
1082 P_("Time-to-live of outgoing unicast packets"),
1085 G_PARAM_STATIC_STRINGS));
1088 * GSocket:multicast-loopback:
1090 * Whether outgoing multicast packets loop back to the local host.
1094 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
1095 g_param_spec_boolean ("multicast-loopback",
1096 P_("Multicast loopback"),
1097 P_("Whether outgoing multicast packets loop back to the local host"),
1100 G_PARAM_STATIC_STRINGS));
1103 * GSocket:multicast-ttl:
1105 * Time-to-live out outgoing multicast packets
1109 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
1110 g_param_spec_uint ("multicast-ttl",
1111 P_("Multicast TTL"),
1112 P_("Time-to-live of outgoing multicast packets"),
1115 G_PARAM_STATIC_STRINGS));
1119 g_socket_initable_iface_init (GInitableIface *iface)
1121 iface->init = g_socket_initable_init;
1125 g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface)
1127 iface->receive_messages = g_socket_datagram_based_receive_messages;
1128 iface->send_messages = g_socket_datagram_based_send_messages;
1129 iface->create_source = g_socket_datagram_based_create_source;
1130 iface->condition_check = g_socket_datagram_based_condition_check;
1131 iface->condition_wait = g_socket_datagram_based_condition_wait;
1135 g_socket_init (GSocket *socket)
1137 socket->priv = g_socket_get_instance_private (socket);
1139 socket->priv->fd = -1;
1140 socket->priv->blocking = TRUE;
1141 socket->priv->listen_backlog = 10;
1142 socket->priv->construct_error = NULL;
1144 socket->priv->event = WSA_INVALID_EVENT;
1145 g_mutex_init (&socket->priv->win32_source_lock);
1146 g_cond_init (&socket->priv->win32_source_cond);
1151 g_socket_initable_init (GInitable *initable,
1152 GCancellable *cancellable,
1157 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
1159 socket = G_SOCKET (initable);
1161 if (cancellable != NULL)
1163 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1164 _("Cancellable initialization not supported"));
1168 socket->priv->inited = TRUE;
1170 if (socket->priv->construct_error)
1173 *error = g_error_copy (socket->priv->construct_error);
1182 check_datagram_based (GDatagramBased *self,
1185 switch (g_socket_get_socket_type (G_SOCKET (self)))
1187 case G_SOCKET_TYPE_INVALID:
1188 case G_SOCKET_TYPE_STREAM:
1189 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1190 _("Cannot use datagram operations on a non-datagram "
1193 case G_SOCKET_TYPE_DATAGRAM:
1194 case G_SOCKET_TYPE_SEQPACKET:
1199 /* Due to us sharing #GSocketSource with the #GSocket implementation, it is
1200 * pretty tricky to split out #GSocket:timeout so that it does not affect
1201 * #GDatagramBased operations (but still affects #GSocket operations). It is
1202 * not worth that effort — just disallow it and require the user to specify
1203 * timeouts on a per-operation basis. */
1204 if (g_socket_get_timeout (G_SOCKET (self)) != 0)
1206 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1207 _("Cannot use datagram operations on a socket with a "
1216 g_socket_datagram_based_receive_messages (GDatagramBased *self,
1217 GInputMessage *messages,
1221 GCancellable *cancellable,
1224 if (!check_datagram_based (self, error))
1227 return g_socket_receive_messages_with_timeout (G_SOCKET (self), messages,
1228 num_messages, flags, timeout_us,
1229 cancellable, error);
1233 g_socket_datagram_based_send_messages (GDatagramBased *self,
1234 GOutputMessage *messages,
1238 GCancellable *cancellable,
1241 if (!check_datagram_based (self, error))
1244 return g_socket_send_messages_with_timeout (G_SOCKET (self), messages,
1245 num_messages, flags, timeout_us,
1246 cancellable, error);
1250 g_socket_datagram_based_create_source (GDatagramBased *self,
1251 GIOCondition condition,
1252 GCancellable *cancellable)
1254 if (!check_datagram_based (self, NULL))
1257 return g_socket_create_source (G_SOCKET (self), condition, cancellable);
1261 g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
1262 GIOCondition condition)
1264 if (!check_datagram_based (datagram_based, NULL))
1267 return g_socket_condition_check (G_SOCKET (datagram_based), condition);
1271 g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
1272 GIOCondition condition,
1274 GCancellable *cancellable,
1277 if (!check_datagram_based (datagram_based, error))
1280 return g_socket_condition_timed_wait (G_SOCKET (datagram_based), condition,
1281 timeout_us, cancellable, error);
1286 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1287 * @type: the socket type to use.
1288 * @protocol: the id of the protocol to use, or 0 for default.
1289 * @error: #GError for error reporting, or %NULL to ignore.
1291 * Creates a new #GSocket with the defined family, type and protocol.
1292 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1293 * for the family and type is used.
1295 * The @protocol is a family and type specific int that specifies what
1296 * kind of protocol to use. #GSocketProtocol lists several common ones.
1297 * Many families only support one protocol, and use 0 for this, others
1298 * support several and using 0 means to use the default protocol for
1299 * the family and type.
1301 * The protocol id is passed directly to the operating
1302 * system, so you can use protocols not listed in #GSocketProtocol if you
1303 * know the protocol number used for it.
1305 * Returns: a #GSocket or %NULL on error.
1306 * Free the returned object with g_object_unref().
1311 g_socket_new (GSocketFamily family,
1313 GSocketProtocol protocol,
1316 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1320 "protocol", protocol,
1325 * g_socket_new_from_fd:
1326 * @fd: a native socket file descriptor.
1327 * @error: #GError for error reporting, or %NULL to ignore.
1329 * Creates a new #GSocket from a native file descriptor
1330 * or winsock SOCKET handle.
1332 * This reads all the settings from the file descriptor so that
1333 * all properties should work. Note that the file descriptor
1334 * will be set to non-blocking mode, independent on the blocking
1335 * mode of the #GSocket.
1337 * On success, the returned #GSocket takes ownership of @fd. On failure, the
1338 * caller must close @fd themselves.
1340 * Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
1341 * descriptor. Instead, a GError will be set with code %G_IO_ERROR_FAILED
1343 * Returns: a #GSocket or %NULL on error.
1344 * Free the returned object with g_object_unref().
1349 g_socket_new_from_fd (gint fd,
1352 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1359 * g_socket_set_blocking:
1360 * @socket: a #GSocket.
1361 * @blocking: Whether to use blocking I/O or not.
1363 * Sets the blocking mode of the socket. In blocking mode
1364 * all operations (which don’t take an explicit blocking parameter) block until
1365 * they succeed or there is an error. In
1366 * non-blocking mode all functions return results immediately or
1367 * with a %G_IO_ERROR_WOULD_BLOCK error.
1369 * All sockets are created in blocking mode. However, note that the
1370 * platform level socket is always non-blocking, and blocking mode
1371 * is a GSocket level feature.
1376 g_socket_set_blocking (GSocket *socket,
1379 g_return_if_fail (G_IS_SOCKET (socket));
1381 blocking = !!blocking;
1383 if (socket->priv->blocking == blocking)
1386 socket->priv->blocking = blocking;
1387 g_object_notify (G_OBJECT (socket), "blocking");
1391 * g_socket_get_blocking:
1392 * @socket: a #GSocket.
1394 * Gets the blocking mode of the socket. For details on blocking I/O,
1395 * see g_socket_set_blocking().
1397 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1402 g_socket_get_blocking (GSocket *socket)
1404 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1406 return socket->priv->blocking;
1410 * g_socket_set_keepalive:
1411 * @socket: a #GSocket.
1412 * @keepalive: Value for the keepalive flag
1414 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1415 * this flag is set on a socket, the system will attempt to verify that the
1416 * remote socket endpoint is still present if a sufficiently long period of
1417 * time passes with no data being exchanged. If the system is unable to
1418 * verify the presence of the remote endpoint, it will automatically close
1421 * This option is only functional on certain kinds of sockets. (Notably,
1422 * %G_SOCKET_PROTOCOL_TCP sockets.)
1424 * The exact time between pings is system- and protocol-dependent, but will
1425 * normally be at least two hours. Most commonly, you would set this flag
1426 * on a server socket if you want to allow clients to remain idle for long
1427 * periods of time, but also want to ensure that connections are eventually
1428 * garbage-collected if clients crash or become unreachable.
1433 g_socket_set_keepalive (GSocket *socket,
1436 GError *error = NULL;
1438 g_return_if_fail (G_IS_SOCKET (socket));
1440 keepalive = !!keepalive;
1441 if (socket->priv->keepalive == keepalive)
1444 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1447 g_warning ("error setting keepalive: %s", error->message);
1448 g_error_free (error);
1452 socket->priv->keepalive = keepalive;
1453 g_object_notify (G_OBJECT (socket), "keepalive");
1457 * g_socket_get_keepalive:
1458 * @socket: a #GSocket.
1460 * Gets the keepalive mode of the socket. For details on this,
1461 * see g_socket_set_keepalive().
1463 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1468 g_socket_get_keepalive (GSocket *socket)
1470 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1472 return socket->priv->keepalive;
1476 * g_socket_get_listen_backlog:
1477 * @socket: a #GSocket.
1479 * Gets the listen backlog setting of the socket. For details on this,
1480 * see g_socket_set_listen_backlog().
1482 * Returns: the maximum number of pending connections.
1487 g_socket_get_listen_backlog (GSocket *socket)
1489 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1491 return socket->priv->listen_backlog;
1495 * g_socket_set_listen_backlog:
1496 * @socket: a #GSocket.
1497 * @backlog: the maximum number of pending connections.
1499 * Sets the maximum number of outstanding connections allowed
1500 * when listening on this socket. If more clients than this are
1501 * connecting to the socket and the application is not handling them
1502 * on time then the new connections will be refused.
1504 * Note that this must be called before g_socket_listen() and has no
1505 * effect if called after that.
1510 g_socket_set_listen_backlog (GSocket *socket,
1513 g_return_if_fail (G_IS_SOCKET (socket));
1514 g_return_if_fail (!socket->priv->listening);
1516 if (backlog != socket->priv->listen_backlog)
1518 socket->priv->listen_backlog = backlog;
1519 g_object_notify (G_OBJECT (socket), "listen-backlog");
1524 * g_socket_get_timeout:
1525 * @socket: a #GSocket.
1527 * Gets the timeout setting of the socket. For details on this, see
1528 * g_socket_set_timeout().
1530 * Returns: the timeout in seconds
1535 g_socket_get_timeout (GSocket *socket)
1537 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1539 return socket->priv->timeout;
1543 * g_socket_set_timeout:
1544 * @socket: a #GSocket.
1545 * @timeout: the timeout for @socket, in seconds, or 0 for none
1547 * Sets the time in seconds after which I/O operations on @socket will
1548 * time out if they have not yet completed.
1550 * On a blocking socket, this means that any blocking #GSocket
1551 * operation will time out after @timeout seconds of inactivity,
1552 * returning %G_IO_ERROR_TIMED_OUT.
1554 * On a non-blocking socket, calls to g_socket_condition_wait() will
1555 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1556 * created with g_socket_create_source() will trigger after
1557 * @timeout seconds of inactivity, with the requested condition
1558 * set, at which point calling g_socket_receive(), g_socket_send(),
1559 * g_socket_check_connect_result(), etc, will fail with
1560 * %G_IO_ERROR_TIMED_OUT.
1562 * If @timeout is 0 (the default), operations will never time out
1565 * Note that if an I/O operation is interrupted by a signal, this may
1566 * cause the timeout to be reset.
1571 g_socket_set_timeout (GSocket *socket,
1574 g_return_if_fail (G_IS_SOCKET (socket));
1576 if (timeout != socket->priv->timeout)
1578 socket->priv->timeout = timeout;
1579 g_object_notify (G_OBJECT (socket), "timeout");
1585 * @socket: a #GSocket.
1587 * Gets the unicast time-to-live setting on @socket; see
1588 * g_socket_set_ttl() for more details.
1590 * Returns: the time-to-live setting on @socket
1595 g_socket_get_ttl (GSocket *socket)
1597 GError *error = NULL;
1600 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1602 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1604 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1607 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1609 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1613 g_return_val_if_reached (0);
1617 g_warning ("error getting unicast ttl: %s", error->message);
1618 g_error_free (error);
1627 * @socket: a #GSocket.
1628 * @ttl: the time-to-live value for all unicast packets on @socket
1630 * Sets the time-to-live for outgoing unicast packets on @socket.
1631 * By default the platform-specific default value is used.
1636 g_socket_set_ttl (GSocket *socket,
1639 GError *error = NULL;
1641 g_return_if_fail (G_IS_SOCKET (socket));
1643 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1645 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1648 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1650 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1652 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1656 g_return_if_reached ();
1660 g_warning ("error setting unicast ttl: %s", error->message);
1661 g_error_free (error);
1665 g_object_notify (G_OBJECT (socket), "ttl");
1669 * g_socket_get_broadcast:
1670 * @socket: a #GSocket.
1672 * Gets the broadcast setting on @socket; if %TRUE,
1673 * it is possible to send packets to broadcast
1676 * Returns: the broadcast setting on @socket
1681 g_socket_get_broadcast (GSocket *socket)
1683 GError *error = NULL;
1686 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1688 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1691 g_warning ("error getting broadcast: %s", error->message);
1692 g_error_free (error);
1700 * g_socket_set_broadcast:
1701 * @socket: a #GSocket.
1702 * @broadcast: whether @socket should allow sending to broadcast
1705 * Sets whether @socket should allow sending to broadcast addresses.
1706 * This is %FALSE by default.
1711 g_socket_set_broadcast (GSocket *socket,
1714 GError *error = NULL;
1716 g_return_if_fail (G_IS_SOCKET (socket));
1718 broadcast = !!broadcast;
1720 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1723 g_warning ("error setting broadcast: %s", error->message);
1724 g_error_free (error);
1728 g_object_notify (G_OBJECT (socket), "broadcast");
1732 * g_socket_get_multicast_loopback:
1733 * @socket: a #GSocket.
1735 * Gets the multicast loopback setting on @socket; if %TRUE (the
1736 * default), outgoing multicast packets will be looped back to
1737 * multicast listeners on the same host.
1739 * Returns: the multicast loopback setting on @socket
1744 g_socket_get_multicast_loopback (GSocket *socket)
1746 GError *error = NULL;
1749 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1751 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1753 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1756 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1758 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1762 g_return_val_if_reached (FALSE);
1766 g_warning ("error getting multicast loopback: %s", error->message);
1767 g_error_free (error);
1775 * g_socket_set_multicast_loopback:
1776 * @socket: a #GSocket.
1777 * @loopback: whether @socket should receive messages sent to its
1778 * multicast groups from the local host
1780 * Sets whether outgoing multicast packets will be received by sockets
1781 * listening on that multicast address on the same host. This is %TRUE
1787 g_socket_set_multicast_loopback (GSocket *socket,
1790 GError *error = NULL;
1792 g_return_if_fail (G_IS_SOCKET (socket));
1794 loopback = !!loopback;
1796 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1798 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1801 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1803 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1805 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1809 g_return_if_reached ();
1813 g_warning ("error setting multicast loopback: %s", error->message);
1814 g_error_free (error);
1818 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1822 * g_socket_get_multicast_ttl:
1823 * @socket: a #GSocket.
1825 * Gets the multicast time-to-live setting on @socket; see
1826 * g_socket_set_multicast_ttl() for more details.
1828 * Returns: the multicast time-to-live setting on @socket
1833 g_socket_get_multicast_ttl (GSocket *socket)
1835 GError *error = NULL;
1838 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1840 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1842 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1845 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1847 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1851 g_return_val_if_reached (FALSE);
1855 g_warning ("error getting multicast ttl: %s", error->message);
1856 g_error_free (error);
1864 * g_socket_set_multicast_ttl:
1865 * @socket: a #GSocket.
1866 * @ttl: the time-to-live value for all multicast datagrams on @socket
1868 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1869 * By default, this is 1, meaning that multicast packets will not leave
1870 * the local network.
1875 g_socket_set_multicast_ttl (GSocket *socket,
1878 GError *error = NULL;
1880 g_return_if_fail (G_IS_SOCKET (socket));
1882 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1884 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1887 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1889 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1891 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1895 g_return_if_reached ();
1899 g_warning ("error setting multicast ttl: %s", error->message);
1900 g_error_free (error);
1904 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1908 * g_socket_get_family:
1909 * @socket: a #GSocket.
1911 * Gets the socket family of the socket.
1913 * Returns: a #GSocketFamily
1918 g_socket_get_family (GSocket *socket)
1920 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1922 return socket->priv->family;
1926 * g_socket_get_socket_type:
1927 * @socket: a #GSocket.
1929 * Gets the socket type of the socket.
1931 * Returns: a #GSocketType
1936 g_socket_get_socket_type (GSocket *socket)
1938 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1940 return socket->priv->type;
1944 * g_socket_get_protocol:
1945 * @socket: a #GSocket.
1947 * Gets the socket protocol id the socket was created with.
1948 * In case the protocol is unknown, -1 is returned.
1950 * Returns: a protocol id, or -1 if unknown
1955 g_socket_get_protocol (GSocket *socket)
1957 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1959 return socket->priv->protocol;
1964 * @socket: a #GSocket.
1966 * Returns the underlying OS socket object. On unix this
1967 * is a socket file descriptor, and on Windows this is
1968 * a Winsock2 SOCKET handle. This may be useful for
1969 * doing platform specific or otherwise unusual operations
1972 * Returns: the file descriptor of the socket.
1977 g_socket_get_fd (GSocket *socket)
1979 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1981 return socket->priv->fd;
1985 * g_socket_get_local_address:
1986 * @socket: a #GSocket.
1987 * @error: #GError for error reporting, or %NULL to ignore.
1989 * Try to get the local address of a bound socket. This is only
1990 * useful if the socket has been bound to a local address,
1991 * either explicitly or implicitly when connecting.
1993 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1994 * Free the returned object with g_object_unref().
1999 g_socket_get_local_address (GSocket *socket,
2003 struct sockaddr_storage storage;
2006 socklen_t len = sizeof (buffer);
2008 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2010 if (getsockname (socket->priv->fd, &buffer.sa, &len) < 0)
2012 int errsv = get_socket_errno ();
2013 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2014 _("could not get local address: %s"), socket_strerror (errsv));
2018 return g_socket_address_new_from_native (&buffer.storage, len);
2022 * g_socket_get_remote_address:
2023 * @socket: a #GSocket.
2024 * @error: #GError for error reporting, or %NULL to ignore.
2026 * Try to get the remote address of a connected socket. This is only
2027 * useful for connection oriented sockets that have been connected.
2029 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
2030 * Free the returned object with g_object_unref().
2035 g_socket_get_remote_address (GSocket *socket,
2039 struct sockaddr_storage storage;
2042 socklen_t len = sizeof (buffer);
2044 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2046 if (socket->priv->connect_pending)
2048 if (!g_socket_check_connect_result (socket, error))
2051 socket->priv->connect_pending = FALSE;
2054 if (!socket->priv->remote_address)
2056 if (getpeername (socket->priv->fd, &buffer.sa, &len) < 0)
2058 int errsv = get_socket_errno ();
2059 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2060 _("could not get remote address: %s"), socket_strerror (errsv));
2064 socket->priv->remote_address = g_socket_address_new_from_native (&buffer.storage, len);
2067 return g_object_ref (socket->priv->remote_address);
2071 * g_socket_is_connected:
2072 * @socket: a #GSocket.
2074 * Check whether the socket is connected. This is only useful for
2075 * connection-oriented sockets.
2077 * If using g_socket_shutdown(), this function will return %TRUE until the
2078 * socket has been shut down for reading and writing. If you do a non-blocking
2079 * connect, this function will not return %TRUE until after you call
2080 * g_socket_check_connect_result().
2082 * Returns: %TRUE if socket is connected, %FALSE otherwise.
2087 g_socket_is_connected (GSocket *socket)
2089 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2091 return (socket->priv->connected_read || socket->priv->connected_write);
2096 * @socket: a #GSocket.
2097 * @error: #GError for error reporting, or %NULL to ignore.
2099 * Marks the socket as a server socket, i.e. a socket that is used
2100 * to accept incoming requests using g_socket_accept().
2102 * Before calling this the socket must be bound to a local address using
2105 * To set the maximum amount of outstanding clients, use
2106 * g_socket_set_listen_backlog().
2108 * Returns: %TRUE on success, %FALSE on error.
2113 g_socket_listen (GSocket *socket,
2116 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2118 if (!check_socket (socket, error))
2121 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
2123 int errsv = get_socket_errno ();
2125 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2126 _("could not listen: %s"), socket_strerror (errsv));
2130 socket->priv->listening = TRUE;
2137 * @socket: a #GSocket.
2138 * @address: a #GSocketAddress specifying the local address.
2139 * @allow_reuse: whether to allow reusing this address
2140 * @error: #GError for error reporting, or %NULL to ignore.
2142 * When a socket is created it is attached to an address family, but it
2143 * doesn't have an address in this family. g_socket_bind() assigns the
2144 * address (sometimes called name) of the socket.
2146 * It is generally required to bind to a local address before you can
2147 * receive connections. (See g_socket_listen() and g_socket_accept() ).
2148 * In certain situations, you may also want to bind a socket that will be
2149 * used to initiate connections, though this is not normally required.
2151 * If @socket is a TCP socket, then @allow_reuse controls the setting
2152 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
2153 * server sockets (sockets that you will eventually call
2154 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
2155 * set this flag on a server socket may cause g_socket_bind() to return
2156 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
2157 * immediately restarted.)
2159 * If @socket is a UDP socket, then @allow_reuse determines whether or
2160 * not other UDP sockets can be bound to the same address at the same
2161 * time. In particular, you can have several UDP sockets bound to the
2162 * same address, and they will all receive all of the multicast and
2163 * broadcast packets sent to that address. (The behavior of unicast
2164 * UDP packets to an address with multiple listeners is not defined.)
2166 * Returns: %TRUE on success, %FALSE on error.
2171 g_socket_bind (GSocket *socket,
2172 GSocketAddress *address,
2173 gboolean reuse_address,
2177 struct sockaddr_storage storage;
2180 gboolean so_reuseaddr;
2182 gboolean so_reuseport;
2185 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2187 if (!check_socket (socket, error))
2190 if (!g_socket_address_to_native (address, &addr.storage, sizeof addr, error))
2193 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
2194 * sockets, but has nasty side effects we don't want for TCP
2197 * On other platforms, we set SO_REUSEPORT, if it exists, for
2198 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
2199 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
2200 * the desired semantics on UDP (as it does on Linux, although
2201 * Linux has SO_REUSEPORT too as of 3.9).
2205 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2207 so_reuseaddr = !!reuse_address;
2211 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2214 /* Ignore errors here, the only likely error is "not supported", and
2215 * this is a "best effort" thing mainly.
2217 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
2219 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
2222 if (bind (socket->priv->fd, &addr.sa,
2223 g_socket_address_get_native_size (address)) < 0)
2225 int errsv = get_socket_errno ();
2226 gchar *address_string = address_to_string (address);
2229 G_IO_ERROR, socket_io_error_from_errno (errsv),
2230 _("Error binding to address %s: %s"),
2231 address_string, socket_strerror (errsv));
2232 g_free (address_string);
2241 g_socket_w32_get_adapter_ipv4_addr (const gchar *name_or_ip)
2243 ULONG bufsize = 15000; /* MS-recommended initial bufsize */
2244 DWORD ret = ERROR_BUFFER_OVERFLOW;
2245 unsigned int malloc_iterations = 0;
2246 PIP_ADAPTER_ADDRESSES addr_buf = NULL, eth_adapter;
2247 wchar_t *wchar_name_or_ip = NULL;
2248 gulong ip_result = 0;
2249 NET_IFINDEX if_index;
2252 * For Windows OS only - return adapter IPv4 address in network byte order.
2254 * Input string can be either friendly name of adapter, IP address of adapter,
2255 * indextoname, or fullname of adapter.
2257 * 192.168.1.109 ===> IP address given directly,
2258 * convert directly with inet_addr() function
2259 * Wi-Fi ===> Adapter friendly name "Wi-Fi",
2260 * scan with GetAdapterAddresses and adapter->FriendlyName
2261 * ethernet_32774 ===> Adapter name as returned by if_indextoname
2262 * {33E8F5CD-BAEA-4214-BE13-B79AB8080CAB} ===> Adaptername,
2263 * as returned in GetAdapterAddresses and adapter->AdapterName
2266 /* Step 1: Check if string is an IP address: */
2267 if (inet_pton (AF_INET, name_or_ip, &ip_result) == 1)
2268 return ip_result; /* Success, IP address string was given directly */
2271 * Step 2: Check if name represents a valid Interface index (e.g. ethernet_75521)
2272 * function if_nametoindex will return >=1 if a valid index, or 0=no match
2273 * valid index will be used later in GetAdaptersAddress loop for lookup of adapter IP address
2275 if_index = if_nametoindex (name_or_ip);
2277 /* Step 3: Prepare wchar string for friendly name comparison */
2280 size_t if_name_len = strlen (name_or_ip);
2281 if (if_name_len >= MAX_ADAPTER_NAME_LENGTH + 4)
2283 /* Name-check only needed if index=0... */
2284 wchar_name_or_ip = (wchar_t *) g_try_malloc ((if_name_len + 1) * sizeof(wchar_t));
2285 if (wchar_name_or_ip)
2286 mbstowcs (wchar_name_or_ip, name_or_ip, if_name_len + 1);
2287 /* NOTE: Even if malloc fails here, some comparisons can still be done later... so no exit here! */
2291 * Step 4: Allocate memory and get adapter addresses.
2292 * Buffer allocation loop recommended by MS, since size can be dynamic
2293 * https://docs.microsoft.com/en-us/windows/desktop/api/iphlpapi/nf-iphlpapi-getadaptersaddresses
2295 #define MAX_ALLOC_ITERATIONS 3
2298 malloc_iterations++;
2299 addr_buf = (PIP_ADAPTER_ADDRESSES) g_try_realloc (addr_buf, bufsize);
2301 ret = GetAdaptersAddresses (AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, addr_buf, &bufsize);
2304 ret == ERROR_BUFFER_OVERFLOW &&
2305 malloc_iterations < MAX_ALLOC_ITERATIONS);
2306 #undef MAX_ALLOC_ITERATIONS
2308 if (addr_buf == 0 || ret != NO_ERROR)
2311 g_free (wchar_name_or_ip);
2315 /* Step 5: Loop through adapters and check match for index or name */
2316 for (eth_adapter = addr_buf; eth_adapter != NULL; eth_adapter = eth_adapter->Next)
2318 /* Check if match for interface index/name: */
2319 gboolean any_match = (if_index > 0) && (eth_adapter->IfIndex == if_index);
2321 /* Check if match for friendly name - but only if NO if_index! */
2322 if (!any_match && if_index == 0 && eth_adapter->FriendlyName &&
2323 eth_adapter->FriendlyName[0] != 0 && wchar_name_or_ip != NULL)
2324 any_match = (_wcsicmp (eth_adapter->FriendlyName, wchar_name_or_ip) == 0);
2326 /* Check if match for adapter low level name - but only if NO if_index: */
2327 if (!any_match && if_index == 0 && eth_adapter->AdapterName &&
2328 eth_adapter->AdapterName[0] != 0)
2329 any_match = (stricmp (eth_adapter->AdapterName, name_or_ip) == 0);
2333 /* We have match for this adapter, lets get its local unicast IP address! */
2334 PIP_ADAPTER_UNICAST_ADDRESS uni_addr;
2335 for (uni_addr = eth_adapter->FirstUnicastAddress;
2336 uni_addr != NULL; uni_addr = uni_addr->Next)
2338 if (uni_addr->Address.lpSockaddr->sa_family == AF_INET)
2340 ip_result = ((PSOCKADDR_IN) uni_addr->Address.lpSockaddr)->sin_addr.S_un.S_addr;
2341 break; /* finished, exit unicast addr loop */
2348 g_free (wchar_name_or_ip);
2355 g_socket_multicast_group_operation (GSocket *socket,
2356 GInetAddress *group,
2357 gboolean source_specific,
2359 gboolean join_group,
2362 const guint8 *native_addr;
2363 gint optname, result;
2365 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2366 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2367 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2369 if (!check_socket (socket, error))
2372 native_addr = g_inet_address_to_bytes (group);
2373 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2375 #ifdef HAVE_IP_MREQN
2376 struct ip_mreqn mc_req;
2378 struct ip_mreq mc_req;
2381 memset (&mc_req, 0, sizeof (mc_req));
2382 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2384 #ifdef HAVE_IP_MREQN
2386 mc_req.imr_ifindex = if_nametoindex (iface);
2388 mc_req.imr_ifindex = 0; /* Pick any. */
2389 #elif defined(G_OS_WIN32)
2391 mc_req.imr_interface.s_addr = g_socket_w32_get_adapter_ipv4_addr (iface);
2393 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2395 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2398 if (source_specific)
2400 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2401 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2403 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2405 _("Error joining multicast group: %s") :
2406 _("Error leaving multicast group: %s"),
2407 _("No support for source-specific multicast"));
2412 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2413 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2414 &mc_req, sizeof (mc_req));
2416 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2418 struct ipv6_mreq mc_req_ipv6;
2420 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2421 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2422 #ifdef HAVE_IF_NAMETOINDEX
2424 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2427 mc_req_ipv6.ipv6mr_interface = 0;
2429 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2430 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2431 &mc_req_ipv6, sizeof (mc_req_ipv6));
2434 g_return_val_if_reached (FALSE);
2438 int errsv = get_socket_errno ();
2440 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2442 _("Error joining multicast group: %s") :
2443 _("Error leaving multicast group: %s"),
2444 socket_strerror (errsv));
2452 * g_socket_join_multicast_group:
2453 * @socket: a #GSocket.
2454 * @group: a #GInetAddress specifying the group address to join.
2455 * @iface: (nullable): Name of the interface to use, or %NULL
2456 * @source_specific: %TRUE if source-specific multicast should be used
2457 * @error: #GError for error reporting, or %NULL to ignore.
2459 * Registers @socket to receive multicast messages sent to @group.
2460 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2461 * been bound to an appropriate interface and port with
2464 * If @iface is %NULL, the system will automatically pick an interface
2465 * to bind to based on @group.
2467 * If @source_specific is %TRUE, source-specific multicast as defined
2468 * in RFC 4604 is used. Note that on older platforms this may fail
2469 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2471 * To bind to a given source-specific multicast address, use
2472 * g_socket_join_multicast_group_ssm() instead.
2474 * Returns: %TRUE on success, %FALSE on error.
2479 g_socket_join_multicast_group (GSocket *socket,
2480 GInetAddress *group,
2481 gboolean source_specific,
2485 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2489 * g_socket_leave_multicast_group:
2490 * @socket: a #GSocket.
2491 * @group: a #GInetAddress specifying the group address to leave.
2492 * @iface: (nullable): Interface used
2493 * @source_specific: %TRUE if source-specific multicast was used
2494 * @error: #GError for error reporting, or %NULL to ignore.
2496 * Removes @socket from the multicast group defined by @group, @iface,
2497 * and @source_specific (which must all have the same values they had
2498 * when you joined the group).
2500 * @socket remains bound to its address and port, and can still receive
2501 * unicast messages after calling this.
2503 * To unbind to a given source-specific multicast address, use
2504 * g_socket_leave_multicast_group_ssm() instead.
2506 * Returns: %TRUE on success, %FALSE on error.
2511 g_socket_leave_multicast_group (GSocket *socket,
2512 GInetAddress *group,
2513 gboolean source_specific,
2517 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2521 g_socket_multicast_group_operation_ssm (GSocket *socket,
2522 GInetAddress *group,
2523 GInetAddress *source_specific,
2525 gboolean join_group,
2530 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2531 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2532 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2533 g_return_val_if_fail (iface == NULL || *iface != '\0', FALSE);
2534 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2536 if (!source_specific)
2538 return g_socket_multicast_group_operation (socket, group, FALSE, iface,
2542 if (!check_socket (socket, error))
2545 switch (g_inet_address_get_family (group))
2547 case G_SOCKET_FAMILY_INVALID:
2548 case G_SOCKET_FAMILY_UNIX:
2550 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2552 _("Error joining multicast group: %s") :
2553 _("Error leaving multicast group: %s"),
2554 _("Unsupported socket family"));
2559 case G_SOCKET_FAMILY_IPV4:
2561 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2563 #ifdef BROKEN_IP_MREQ_SOURCE_STRUCT
2564 #define S_ADDR_FIELD(src) src.imr_interface
2566 #define S_ADDR_FIELD(src) src.imr_interface.s_addr
2570 struct ip_mreq_source mc_req_src;
2572 if (g_inet_address_get_family (source_specific) !=
2573 G_SOCKET_FAMILY_IPV4)
2575 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2577 _("Error joining multicast group: %s") :
2578 _("Error leaving multicast group: %s"),
2579 _("source-specific not an IPv4 address"));
2583 memset (&mc_req_src, 0, sizeof (mc_req_src));
2585 /* By default use the default IPv4 multicast interface. */
2586 S_ADDR_FIELD(mc_req_src) = g_htonl (INADDR_ANY);
2590 #if defined(G_OS_WIN32)
2591 S_ADDR_FIELD(mc_req_src) = g_socket_w32_get_adapter_ipv4_addr (iface);
2592 #elif defined (HAVE_SIOCGIFADDR)
2595 struct sockaddr_in *iface_addr;
2596 size_t if_name_len = strlen (iface);
2598 memset (&ifr, 0, sizeof (ifr));
2600 if (if_name_len >= sizeof (ifr.ifr_name))
2602 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FILENAME_TOO_LONG,
2603 _("Interface name too long"));
2607 memcpy (ifr.ifr_name, iface, if_name_len);
2609 /* Get the IPv4 address of the given network interface name. */
2610 ret = ioctl (socket->priv->fd, SIOCGIFADDR, &ifr);
2615 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2616 _("Interface not found: %s"), g_strerror (errsv));
2620 iface_addr = (struct sockaddr_in *) &ifr.ifr_addr;
2621 S_ADDR_FIELD(mc_req_src) = iface_addr->sin_addr.s_addr;
2622 #endif /* defined(G_OS_WIN32) && defined (HAVE_IF_NAMETOINDEX) */
2625 g_assert (g_inet_address_get_native_size (group) == sizeof (mc_req_src.imr_multiaddr));
2626 memcpy (&mc_req_src.imr_multiaddr, g_inet_address_to_bytes (group),
2627 g_inet_address_get_native_size (group));
2629 g_assert (g_inet_address_get_native_size (source_specific) == sizeof (mc_req_src.imr_sourceaddr));
2630 memcpy (&mc_req_src.imr_sourceaddr,
2631 g_inet_address_to_bytes (source_specific),
2632 g_inet_address_get_native_size (source_specific));
2635 join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2636 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2637 &mc_req_src, sizeof (mc_req_src));
2642 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2644 _("Error joining multicast group: %s") :
2645 _("Error leaving multicast group: %s"),
2646 _("No support for IPv4 source-specific multicast"));
2648 #endif /* IP_ADD_SOURCE_MEMBERSHIP */
2652 case G_SOCKET_FAMILY_IPV6:
2654 #ifdef MCAST_JOIN_SOURCE_GROUP
2657 struct group_source_req mc_req_src;
2658 GSocketAddress *saddr_group, *saddr_source_specific;
2659 guint iface_index = 0;
2661 #if defined (HAVE_IF_NAMETOINDEX)
2664 iface_index = if_nametoindex (iface);
2665 if (iface_index == 0)
2669 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2670 _("Interface not found: %s"), g_strerror (errsv));
2674 #endif /* defined (HAVE_IF_NAMETOINDEX) */
2675 mc_req_src.gsr_interface = iface_index;
2677 saddr_group = g_inet_socket_address_new (group, 0);
2678 res = g_socket_address_to_native (saddr_group, &mc_req_src.gsr_group,
2679 sizeof (mc_req_src.gsr_group),
2681 g_object_unref (saddr_group);
2685 saddr_source_specific = g_inet_socket_address_new (source_specific, 0);
2686 res = g_socket_address_to_native (saddr_source_specific,
2687 &mc_req_src.gsr_source,
2688 sizeof (mc_req_src.gsr_source),
2690 g_object_unref (saddr_source_specific);
2696 join_group ? MCAST_JOIN_SOURCE_GROUP : MCAST_LEAVE_SOURCE_GROUP;
2697 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2698 &mc_req_src, sizeof (mc_req_src));
2700 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2702 _("Error joining multicast group: %s") :
2703 _("Error leaving multicast group: %s"),
2704 _("No support for IPv6 source-specific multicast"));
2706 #endif /* MCAST_JOIN_SOURCE_GROUP */
2711 g_return_val_if_reached (FALSE);
2716 int errsv = get_socket_errno ();
2718 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2720 _("Error joining multicast group: %s") :
2721 _("Error leaving multicast group: %s"),
2722 socket_strerror (errsv));
2730 * g_socket_join_multicast_group_ssm:
2731 * @socket: a #GSocket.
2732 * @group: a #GInetAddress specifying the group address to join.
2733 * @source_specific: (nullable): a #GInetAddress specifying the
2734 * source-specific multicast address or %NULL to ignore.
2735 * @iface: (nullable): Name of the interface to use, or %NULL
2736 * @error: #GError for error reporting, or %NULL to ignore.
2738 * Registers @socket to receive multicast messages sent to @group.
2739 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2740 * been bound to an appropriate interface and port with
2743 * If @iface is %NULL, the system will automatically pick an interface
2744 * to bind to based on @group.
2746 * If @source_specific is not %NULL, use source-specific multicast as
2747 * defined in RFC 4604. Note that on older platforms this may fail
2748 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2750 * Note that this function can be called multiple times for the same
2751 * @group with different @source_specific in order to receive multicast
2752 * packets from more than one source.
2754 * Returns: %TRUE on success, %FALSE on error.
2759 g_socket_join_multicast_group_ssm (GSocket *socket,
2760 GInetAddress *group,
2761 GInetAddress *source_specific,
2765 return g_socket_multicast_group_operation_ssm (socket, group,
2766 source_specific, iface, TRUE, error);
2770 * g_socket_leave_multicast_group_ssm:
2771 * @socket: a #GSocket.
2772 * @group: a #GInetAddress specifying the group address to leave.
2773 * @source_specific: (nullable): a #GInetAddress specifying the
2774 * source-specific multicast address or %NULL to ignore.
2775 * @iface: (nullable): Name of the interface to use, or %NULL
2776 * @error: #GError for error reporting, or %NULL to ignore.
2778 * Removes @socket from the multicast group defined by @group, @iface,
2779 * and @source_specific (which must all have the same values they had
2780 * when you joined the group).
2782 * @socket remains bound to its address and port, and can still receive
2783 * unicast messages after calling this.
2785 * Returns: %TRUE on success, %FALSE on error.
2790 g_socket_leave_multicast_group_ssm (GSocket *socket,
2791 GInetAddress *group,
2792 GInetAddress *source_specific,
2796 return g_socket_multicast_group_operation_ssm (socket, group,
2797 source_specific, iface, FALSE, error);
2801 * g_socket_speaks_ipv4:
2802 * @socket: a #GSocket
2804 * Checks if a socket is capable of speaking IPv4.
2806 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2807 * and under some combinations of circumstances IPv6 sockets are also
2808 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2811 * No other types of sockets are currently considered as being capable
2814 * Returns: %TRUE if this socket can be used with IPv4.
2819 g_socket_speaks_ipv4 (GSocket *socket)
2821 switch (socket->priv->family)
2823 case G_SOCKET_FAMILY_IPV4:
2826 case G_SOCKET_FAMILY_IPV6:
2827 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2831 if (!g_socket_get_option (socket,
2832 IPPROTO_IPV6, IPV6_V6ONLY,
2849 * @socket: a #GSocket.
2850 * @cancellable: (nullable): a %GCancellable or %NULL
2851 * @error: #GError for error reporting, or %NULL to ignore.
2853 * Accept incoming connections on a connection-based socket. This removes
2854 * the first outstanding connection request from the listening socket and
2855 * creates a #GSocket object for it.
2857 * The @socket must be bound to a local address with g_socket_bind() and
2858 * must be listening for incoming connections (g_socket_listen()).
2860 * If there are no outstanding connections then the operation will block
2861 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2862 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2864 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2865 * Free the returned object with g_object_unref().
2870 g_socket_accept (GSocket *socket,
2871 GCancellable *cancellable,
2875 gboolean try_accept4 = TRUE;
2877 GSocket *new_socket;
2880 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2882 if (!check_socket (socket, error))
2885 if (!check_timeout (socket, error))
2890 gboolean try_accept = TRUE;
2895 ret = accept4 (socket->priv->fd, NULL, 0, SOCK_CLOEXEC);
2896 if (ret < 0 && errno == ENOSYS)
2898 try_accept4 = FALSE;
2906 g_assert (try_accept4 || try_accept);
2909 ret = accept (socket->priv->fd, NULL, 0);
2913 int errsv = get_socket_errno ();
2918 #ifdef WSAEWOULDBLOCK
2919 if (errsv == WSAEWOULDBLOCK)
2921 if (errsv == EWOULDBLOCK ||
2925 win32_unset_event_mask (socket, FD_ACCEPT);
2927 if (socket->priv->blocking)
2929 if (!g_socket_condition_wait (socket,
2930 G_IO_IN, cancellable, error))
2937 socket_set_error_lazy (error, errsv, _("Error accepting connection: %s"));
2943 win32_unset_event_mask (socket, FD_ACCEPT);
2947 /* The socket inherits the accepting sockets event mask and even object,
2948 we need to remove that */
2949 WSAEventSelect (ret, NULL, 0);
2955 /* We always want to set close-on-exec to protect users. If you
2956 need to so some weird inheritance to exec you can re-enable this
2957 using lower level hacks with g_socket_get_fd(). */
2958 flags = fcntl (ret, F_GETFD, 0);
2960 (flags & FD_CLOEXEC) == 0)
2962 flags |= FD_CLOEXEC;
2963 fcntl (ret, F_SETFD, flags);
2968 new_socket = g_socket_new_from_fd (ret, error);
2969 if (new_socket == NULL)
2978 new_socket->priv->protocol = socket->priv->protocol;
2985 * @socket: a #GSocket.
2986 * @address: a #GSocketAddress specifying the remote address.
2987 * @cancellable: (nullable): a %GCancellable or %NULL
2988 * @error: #GError for error reporting, or %NULL to ignore.
2990 * Connect the socket to the specified remote address.
2992 * For connection oriented socket this generally means we attempt to make
2993 * a connection to the @address. For a connection-less socket it sets
2994 * the default address for g_socket_send() and discards all incoming datagrams
2995 * from other sources.
2997 * Generally connection oriented sockets can only connect once, but
2998 * connection-less sockets can connect multiple times to change the
3001 * If the connect call needs to do network I/O it will block, unless
3002 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
3003 * and the user can be notified of the connection finishing by waiting
3004 * for the G_IO_OUT condition. The result of the connection must then be
3005 * checked with g_socket_check_connect_result().
3007 * Returns: %TRUE if connected, %FALSE on error.
3012 g_socket_connect (GSocket *socket,
3013 GSocketAddress *address,
3014 GCancellable *cancellable,
3018 struct sockaddr_storage storage;
3022 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
3024 if (!check_socket (socket, error))
3027 if (!g_socket_address_to_native (address, &buffer.storage, sizeof buffer, error))
3030 if (socket->priv->remote_address)
3031 g_object_unref (socket->priv->remote_address);
3032 socket->priv->remote_address = g_object_ref (address);
3036 if (connect (socket->priv->fd, &buffer.sa,
3037 g_socket_address_get_native_size (address)) < 0)
3039 int errsv = get_socket_errno ();
3045 if (errsv == EINPROGRESS)
3047 if (errsv == WSAEWOULDBLOCK)
3050 win32_unset_event_mask (socket, FD_CONNECT);
3052 if (socket->priv->blocking)
3054 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
3056 if (g_socket_check_connect_result (socket, error))
3062 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
3063 _("Connection in progress"));
3064 socket->priv->connect_pending = TRUE;
3068 g_set_error_literal (error, G_IO_ERROR,
3069 socket_io_error_from_errno (errsv),
3070 socket_strerror (errsv));
3077 win32_unset_event_mask (socket, FD_CONNECT);
3079 socket->priv->connected_read = TRUE;
3080 socket->priv->connected_write = TRUE;
3086 * g_socket_check_connect_result:
3087 * @socket: a #GSocket
3088 * @error: #GError for error reporting, or %NULL to ignore.
3090 * Checks and resets the pending connect error for the socket.
3091 * This is used to check for errors when g_socket_connect() is
3092 * used in non-blocking mode.
3094 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
3099 g_socket_check_connect_result (GSocket *socket,
3104 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3106 if (!check_socket (socket, error))
3109 if (!check_timeout (socket, error))
3112 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
3114 g_prefix_error (error, _("Unable to get pending error: "));
3120 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
3121 socket_strerror (value));
3122 if (socket->priv->remote_address)
3124 g_object_unref (socket->priv->remote_address);
3125 socket->priv->remote_address = NULL;
3130 socket->priv->connected_read = TRUE;
3131 socket->priv->connected_write = TRUE;
3137 * g_socket_get_available_bytes:
3138 * @socket: a #GSocket
3140 * Get the amount of data pending in the OS input buffer, without blocking.
3142 * If @socket is a UDP or SCTP socket, this will return the size of
3143 * just the next packet, even if additional packets are buffered after
3146 * Note that on Windows, this function is rather inefficient in the
3147 * UDP case, and so if you know any plausible upper bound on the size
3148 * of the incoming packet, it is better to just do a
3149 * g_socket_receive() with a buffer of that size, rather than calling
3150 * g_socket_get_available_bytes() first and then doing a receive of
3151 * exactly the right size.
3153 * Returns: the number of bytes that can be read from the socket
3154 * without blocking or truncating, or -1 on error.
3159 g_socket_get_available_bytes (GSocket *socket)
3162 const gint bufsize = 64 * 1024;
3163 static guchar *buf = NULL;
3171 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3173 if (!check_socket (socket, NULL))
3177 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
3180 if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
3182 if (G_UNLIKELY (g_once_init_enter (&buf)))
3183 g_once_init_leave (&buf, g_malloc (bufsize));
3185 /* On datagram sockets, FIONREAD ioctl is not reliable because many
3186 * systems add internal header size to the reported size, making it
3187 * unusable for this function. */
3188 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
3189 if ((gint) avail == -1)
3191 int errsv = get_socket_errno ();
3193 if (errsv == WSAEWOULDBLOCK)
3195 if (errsv == EWOULDBLOCK || errsv == EAGAIN)
3203 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
3205 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
3214 /* Block on a timed wait for @condition until (@start_time + @timeout).
3215 * Return %G_IO_ERROR_TIMED_OUT if the timeout is reached; otherwise %TRUE.
3218 block_on_timeout (GSocket *socket,
3219 GIOCondition condition,
3222 GCancellable *cancellable,
3225 gint64 wait_timeout = -1;
3227 g_return_val_if_fail (timeout_us != 0, TRUE);
3229 /* check if we've timed out or how much time to wait at most */
3230 if (timeout_us >= 0)
3232 gint64 elapsed = g_get_monotonic_time () - start_time;
3234 if (elapsed >= timeout_us)
3236 g_set_error_literal (error,
3237 G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3238 _("Socket I/O timed out"));
3242 wait_timeout = timeout_us - elapsed;
3245 return g_socket_condition_timed_wait (socket, condition, wait_timeout,
3246 cancellable, error);
3250 g_socket_receive_with_timeout (GSocket *socket,
3254 GCancellable *cancellable,
3260 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3262 start_time = g_get_monotonic_time ();
3264 if (!check_socket (socket, error))
3267 if (!check_timeout (socket, error))
3270 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3275 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
3277 int errsv = get_socket_errno ();
3282 #ifdef WSAEWOULDBLOCK
3283 if (errsv == WSAEWOULDBLOCK)
3285 if (errsv == EWOULDBLOCK ||
3289 win32_unset_event_mask (socket, FD_READ);
3291 if (timeout_us != 0)
3293 if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
3294 cancellable, error))
3301 win32_unset_event_mask (socket, FD_READ);
3303 socket_set_error_lazy (error, errsv, _("Error receiving data: %s"));
3307 win32_unset_event_mask (socket, FD_READ);
3317 * @socket: a #GSocket
3318 * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3319 * a buffer to read data into (which should be at least @size bytes long).
3320 * @size: (in): the number of bytes you want to read from the socket
3321 * @cancellable: (nullable): a %GCancellable or %NULL
3322 * @error: #GError for error reporting, or %NULL to ignore.
3324 * Receive data (up to @size bytes) from a socket. This is mainly used by
3325 * connection-oriented sockets; it is identical to g_socket_receive_from()
3326 * with @address set to %NULL.
3328 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
3329 * g_socket_receive() will always read either 0 or 1 complete messages from
3330 * the socket. If the received message is too large to fit in @buffer, then
3331 * the data beyond @size bytes will be discarded, without any explicit
3332 * indication that this has occurred.
3334 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
3335 * number of bytes, up to @size. If more than @size bytes have been
3336 * received, the additional data will be returned in future calls to
3337 * g_socket_receive().
3339 * If the socket is in blocking mode the call will block until there
3340 * is some data to receive, the connection is closed, or there is an
3341 * error. If there is no data available and the socket is in
3342 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3343 * returned. To be notified when data is available, wait for the
3344 * %G_IO_IN condition.
3346 * On error -1 is returned and @error is set accordingly.
3348 * Returns: Number of bytes read, or 0 if the connection was closed by
3349 * the peer, or -1 on error
3354 g_socket_receive (GSocket *socket,
3357 GCancellable *cancellable,
3360 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3361 socket->priv->blocking ? -1 : 0,
3362 cancellable, error);
3366 * g_socket_receive_with_blocking:
3367 * @socket: a #GSocket
3368 * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3369 * a buffer to read data into (which should be at least @size bytes long).
3370 * @size: (in): the number of bytes you want to read from the socket
3371 * @blocking: whether to do blocking or non-blocking I/O
3372 * @cancellable: (nullable): a %GCancellable or %NULL
3373 * @error: #GError for error reporting, or %NULL to ignore.
3375 * This behaves exactly the same as g_socket_receive(), except that
3376 * the choice of blocking or non-blocking behavior is determined by
3377 * the @blocking argument rather than by @socket's properties.
3379 * Returns: Number of bytes read, or 0 if the connection was closed by
3380 * the peer, or -1 on error
3385 g_socket_receive_with_blocking (GSocket *socket,
3389 GCancellable *cancellable,
3392 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3393 blocking ? -1 : 0, cancellable, error);
3397 * g_socket_receive_from:
3398 * @socket: a #GSocket
3399 * @address: (out) (optional): a pointer to a #GSocketAddress
3401 * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3402 * a buffer to read data into (which should be at least @size bytes long).
3403 * @size: (in): the number of bytes you want to read from the socket
3404 * @cancellable: (nullable): a %GCancellable or %NULL
3405 * @error: #GError for error reporting, or %NULL to ignore.
3407 * Receive data (up to @size bytes) from a socket.
3409 * If @address is non-%NULL then @address will be set equal to the
3410 * source address of the received packet.
3411 * @address is owned by the caller.
3413 * See g_socket_receive() for additional information.
3415 * Returns: Number of bytes read, or 0 if the connection was closed by
3416 * the peer, or -1 on error
3421 g_socket_receive_from (GSocket *socket,
3422 GSocketAddress **address,
3425 GCancellable *cancellable,
3433 return g_socket_receive_message (socket,
3441 /* See the comment about SIGPIPE above. */
3443 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
3445 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
3449 g_socket_send_with_timeout (GSocket *socket,
3450 const guint8 *buffer,
3453 GCancellable *cancellable,
3459 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3461 start_time = g_get_monotonic_time ();
3463 if (!check_socket (socket, error))
3466 if (!check_timeout (socket, error))
3469 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3474 if ((ret = send (socket->priv->fd, (const char *)buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
3476 int errsv = get_socket_errno ();
3481 #ifdef WSAEWOULDBLOCK
3482 if (errsv == WSAEWOULDBLOCK)
3484 if (errsv == EWOULDBLOCK ||
3488 win32_unset_event_mask (socket, FD_WRITE);
3490 if (timeout_us != 0)
3492 if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
3493 cancellable, error))
3500 socket_set_error_lazy (error, errsv, _("Error sending data: %s"));
3511 * @socket: a #GSocket
3512 * @buffer: (array length=size) (element-type guint8): the buffer
3513 * containing the data to send.
3514 * @size: the number of bytes to send
3515 * @cancellable: (nullable): a %GCancellable or %NULL
3516 * @error: #GError for error reporting, or %NULL to ignore.
3518 * Tries to send @size bytes from @buffer on the socket. This is
3519 * mainly used by connection-oriented sockets; it is identical to
3520 * g_socket_send_to() with @address set to %NULL.
3522 * If the socket is in blocking mode the call will block until there is
3523 * space for the data in the socket queue. If there is no space available
3524 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3525 * will be returned. To be notified when space is available, wait for the
3526 * %G_IO_OUT condition. Note though that you may still receive
3527 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3528 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3529 * very common due to the way the underlying APIs work.)
3531 * On error -1 is returned and @error is set accordingly.
3533 * Returns: Number of bytes written (which may be less than @size), or -1
3539 g_socket_send (GSocket *socket,
3540 const gchar *buffer,
3542 GCancellable *cancellable,
3545 return g_socket_send_with_blocking (socket, buffer, size,
3546 socket->priv->blocking,
3547 cancellable, error);
3551 * g_socket_send_with_blocking:
3552 * @socket: a #GSocket
3553 * @buffer: (array length=size) (element-type guint8): the buffer
3554 * containing the data to send.
3555 * @size: the number of bytes to send
3556 * @blocking: whether to do blocking or non-blocking I/O
3557 * @cancellable: (nullable): a %GCancellable or %NULL
3558 * @error: #GError for error reporting, or %NULL to ignore.
3560 * This behaves exactly the same as g_socket_send(), except that
3561 * the choice of blocking or non-blocking behavior is determined by
3562 * the @blocking argument rather than by @socket's properties.
3564 * Returns: Number of bytes written (which may be less than @size), or -1
3570 g_socket_send_with_blocking (GSocket *socket,
3571 const gchar *buffer,
3574 GCancellable *cancellable,
3577 return g_socket_send_with_timeout (socket, (const guint8 *) buffer, size,
3578 blocking ? -1 : 0, cancellable, error);
3583 * @socket: a #GSocket
3584 * @address: (nullable): a #GSocketAddress, or %NULL
3585 * @buffer: (array length=size) (element-type guint8): the buffer
3586 * containing the data to send.
3587 * @size: the number of bytes to send
3588 * @cancellable: (nullable): a %GCancellable or %NULL
3589 * @error: #GError for error reporting, or %NULL to ignore.
3591 * Tries to send @size bytes from @buffer to @address. If @address is
3592 * %NULL then the message is sent to the default receiver (set by
3593 * g_socket_connect()).
3595 * See g_socket_send() for additional information.
3597 * Returns: Number of bytes written (which may be less than @size), or -1
3603 g_socket_send_to (GSocket *socket,
3604 GSocketAddress *address,
3605 const gchar *buffer,
3607 GCancellable *cancellable,
3615 return g_socket_send_message (socket,
3625 * g_socket_shutdown:
3626 * @socket: a #GSocket
3627 * @shutdown_read: whether to shut down the read side
3628 * @shutdown_write: whether to shut down the write side
3629 * @error: #GError for error reporting, or %NULL to ignore.
3631 * Shut down part or all of a full-duplex connection.
3633 * If @shutdown_read is %TRUE then the receiving side of the connection
3634 * is shut down, and further reading is disallowed.
3636 * If @shutdown_write is %TRUE then the sending side of the connection
3637 * is shut down, and further writing is disallowed.
3639 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
3641 * One example where it is useful to shut down only one side of a connection is
3642 * graceful disconnect for TCP connections where you close the sending side,
3643 * then wait for the other side to close the connection, thus ensuring that the
3644 * other side saw all sent data.
3646 * Returns: %TRUE on success, %FALSE on error
3651 g_socket_shutdown (GSocket *socket,
3652 gboolean shutdown_read,
3653 gboolean shutdown_write,
3658 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3660 if (!check_socket (socket, error))
3664 if (!shutdown_read && !shutdown_write)
3668 if (shutdown_read && shutdown_write)
3670 else if (shutdown_read)
3675 if (shutdown_read && shutdown_write)
3677 else if (shutdown_read)
3683 if (shutdown (socket->priv->fd, how) != 0)
3685 int errsv = get_socket_errno ();
3686 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
3687 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
3692 socket->priv->connected_read = FALSE;
3694 socket->priv->connected_write = FALSE;
3701 * @socket: a #GSocket
3702 * @error: #GError for error reporting, or %NULL to ignore.
3704 * Closes the socket, shutting down any active connection.
3706 * Closing a socket does not wait for all outstanding I/O operations
3707 * to finish, so the caller should not rely on them to be guaranteed
3708 * to complete even if the close returns with no error.
3710 * Once the socket is closed, all other operations will return
3711 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
3714 * Sockets will be automatically closed when the last reference
3715 * is dropped, but you might want to call this function to make sure
3716 * resources are released as early as possible.
3718 * Beware that due to the way that TCP works, it is possible for
3719 * recently-sent data to be lost if either you close a socket while the
3720 * %G_IO_IN condition is set, or else if the remote connection tries to
3721 * send something to you after you close the socket but before it has
3722 * finished reading all of the data you sent. There is no easy generic
3723 * way to avoid this problem; the easiest fix is to design the network
3724 * protocol such that the client will never send data "out of turn".
3725 * Another solution is for the server to half-close the connection by
3726 * calling g_socket_shutdown() with only the @shutdown_write flag set,
3727 * and then wait for the client to notice this and close its side of the
3728 * connection, after which the server can safely call g_socket_close().
3729 * (This is what #GTcpConnection does if you call
3730 * g_tcp_connection_set_graceful_disconnect(). But of course, this
3731 * only works if the client will close its connection after the server
3734 * Returns: %TRUE on success, %FALSE on error
3739 g_socket_close (GSocket *socket,
3744 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3746 if (socket->priv->closed)
3747 return TRUE; /* Multiple close not an error */
3749 if (!check_socket (socket, error))
3755 res = closesocket (socket->priv->fd);
3757 res = close (socket->priv->fd);
3761 int errsv = get_socket_errno ();
3766 g_set_error (error, G_IO_ERROR,
3767 socket_io_error_from_errno (errsv),
3768 _("Error closing socket: %s"),
3769 socket_strerror (errsv));
3775 socket->priv->fd = -1;
3776 socket->priv->connected_read = FALSE;
3777 socket->priv->connected_write = FALSE;
3778 socket->priv->closed = TRUE;
3779 if (socket->priv->remote_address)
3781 g_object_unref (socket->priv->remote_address);
3782 socket->priv->remote_address = NULL;
3789 * g_socket_is_closed:
3790 * @socket: a #GSocket
3792 * Checks whether a socket is closed.
3794 * Returns: %TRUE if socket is closed, %FALSE otherwise
3799 g_socket_is_closed (GSocket *socket)
3801 return socket->priv->closed;
3804 /* Broken source, used on errors */
3806 broken_dispatch (GSource *source,
3807 GSourceFunc callback,
3813 static GSourceFuncs broken_funcs =
3825 network_events_for_condition (GIOCondition condition)
3829 if (condition & G_IO_IN)
3830 event_mask |= (FD_READ | FD_ACCEPT);
3831 if (condition & G_IO_OUT)
3832 event_mask |= (FD_WRITE | FD_CONNECT);
3833 event_mask |= FD_CLOSE;
3839 ensure_event (GSocket *socket)
3841 if (socket->priv->event == WSA_INVALID_EVENT)
3842 socket->priv->event = WSACreateEvent();
3846 update_select_events (GSocket *socket)
3853 if (socket->priv->closed)
3856 ensure_event (socket);
3859 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3862 event_mask |= network_events_for_condition (*ptr);
3865 if (event_mask != socket->priv->selected_events)
3867 /* If no events selected, disable event so we can unset
3870 if (event_mask == 0)
3873 event = socket->priv->event;
3875 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3876 socket->priv->selected_events = event_mask;
3881 add_condition_watch (GSocket *socket,
3882 GIOCondition *condition)
3884 g_mutex_lock (&socket->priv->win32_source_lock);
3885 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3887 socket->priv->requested_conditions =
3888 g_list_prepend (socket->priv->requested_conditions, condition);
3890 update_select_events (socket);
3891 g_mutex_unlock (&socket->priv->win32_source_lock);
3895 remove_condition_watch (GSocket *socket,
3896 GIOCondition *condition)
3898 g_mutex_lock (&socket->priv->win32_source_lock);
3899 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3901 socket->priv->requested_conditions =
3902 g_list_remove (socket->priv->requested_conditions, condition);
3904 update_select_events (socket);
3905 g_mutex_unlock (&socket->priv->win32_source_lock);
3909 update_condition_unlocked (GSocket *socket)
3911 WSANETWORKEVENTS events;
3912 GIOCondition condition;
3914 if (!socket->priv->closed &&
3915 WSAEnumNetworkEvents (socket->priv->fd,
3916 socket->priv->event,
3919 socket->priv->current_events |= events.lNetworkEvents;
3920 if (events.lNetworkEvents & FD_WRITE &&
3921 events.iErrorCode[FD_WRITE_BIT] != 0)
3922 socket->priv->current_errors |= FD_WRITE;
3923 if (events.lNetworkEvents & FD_CONNECT &&
3924 events.iErrorCode[FD_CONNECT_BIT] != 0)
3925 socket->priv->current_errors |= FD_CONNECT;
3929 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3930 condition |= G_IO_IN;
3932 if (socket->priv->current_events & FD_CLOSE)
3934 int r, errsv = NO_ERROR, buffer;
3936 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3938 errsv = get_socket_errno ();
3941 (r < 0 && errsv == WSAENOTCONN))
3942 condition |= G_IO_IN;
3944 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3945 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3946 condition |= G_IO_HUP;
3948 condition |= G_IO_ERR;
3951 if (socket->priv->closed)
3952 condition |= G_IO_HUP;
3954 /* Never report both G_IO_OUT and HUP, these are
3955 mutually exclusive (can't write to a closed socket) */
3956 if ((condition & G_IO_HUP) == 0 &&
3957 socket->priv->current_events & FD_WRITE)
3959 if (socket->priv->current_errors & FD_WRITE)
3960 condition |= G_IO_ERR;
3962 condition |= G_IO_OUT;
3966 if (socket->priv->current_events & FD_CONNECT)
3968 if (socket->priv->current_errors & FD_CONNECT)
3969 condition |= (G_IO_HUP | G_IO_ERR);
3971 condition |= G_IO_OUT;
3979 update_condition (GSocket *socket)
3982 g_mutex_lock (&socket->priv->win32_source_lock);
3983 res = update_condition_unlocked (socket);
3984 g_mutex_unlock (&socket->priv->win32_source_lock);
3997 GIOCondition condition;
4001 socket_source_prepare (GSource *source,
4004 GSocketSource *socket_source = (GSocketSource *)source;
4007 if ((socket_source->pollfd.revents & G_IO_NVAL) != 0)
4010 if (g_socket_is_closed (socket_source->socket))
4012 g_source_remove_poll (source, &socket_source->pollfd);
4013 socket_source->pollfd.revents = G_IO_NVAL;
4017 return (update_condition (socket_source->socket) & socket_source->condition) != 0;
4019 return g_socket_is_closed (socket_source->socket) && socket_source->fd_tag != NULL;
4025 socket_source_check_win32 (GSource *source)
4029 return socket_source_prepare (source, &timeout);
4034 socket_source_dispatch (GSource *source,
4035 GSourceFunc callback,
4038 GSocketSourceFunc func = (GSocketSourceFunc)callback;
4039 GSocketSource *socket_source = (GSocketSource *)source;
4040 GSocket *socket = socket_source->socket;
4046 if ((socket_source->pollfd.revents & G_IO_NVAL) != 0)
4049 events = update_condition (socket_source->socket);
4051 if (g_socket_is_closed (socket_source->socket))
4053 if (socket_source->fd_tag)
4054 g_source_remove_unix_fd (source, socket_source->fd_tag);
4055 socket_source->fd_tag = NULL;
4060 events = g_source_query_unix_fd (source, socket_source->fd_tag);
4064 timeout = g_source_get_ready_time (source);
4065 if (timeout >= 0 && timeout < g_source_get_time (source) &&
4066 !g_socket_is_closed (socket_source->socket))
4068 socket->priv->timed_out = TRUE;
4069 events |= (G_IO_IN | G_IO_OUT);
4072 ret = (*func) (socket, events & socket_source->condition, user_data);
4074 if (socket->priv->timeout && !g_socket_is_closed (socket_source->socket))
4075 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
4077 g_source_set_ready_time (source, -1);
4083 socket_source_finalize (GSource *source)
4085 GSocketSource *socket_source = (GSocketSource *)source;
4088 socket = socket_source->socket;
4091 remove_condition_watch (socket, &socket_source->condition);
4094 g_object_unref (socket);
4098 socket_source_closure_callback (GSocket *socket,
4099 GIOCondition condition,
4102 GClosure *closure = data;
4104 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
4105 GValue result_value = G_VALUE_INIT;
4108 g_value_init (&result_value, G_TYPE_BOOLEAN);
4110 g_value_init (¶ms[0], G_TYPE_SOCKET);
4111 g_value_set_object (¶ms[0], socket);
4112 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
4113 g_value_set_flags (¶ms[1], condition);
4115 g_closure_invoke (closure, &result_value, 2, params, NULL);
4117 result = g_value_get_boolean (&result_value);
4118 g_value_unset (&result_value);
4119 g_value_unset (¶ms[0]);
4120 g_value_unset (¶ms[1]);
4125 static GSourceFuncs socket_source_funcs =
4127 socket_source_prepare,
4129 socket_source_check_win32,
4133 socket_source_dispatch,
4134 socket_source_finalize,
4135 (GSourceFunc)socket_source_closure_callback,
4140 socket_source_new (GSocket *socket,
4141 GIOCondition condition,
4142 GCancellable *cancellable)
4145 GSocketSource *socket_source;
4148 ensure_event (socket);
4150 if (socket->priv->event == WSA_INVALID_EVENT)
4152 g_warning ("Failed to create WSAEvent");
4153 return g_source_new (&broken_funcs, sizeof (GSource));
4157 if (!check_socket (socket, NULL))
4159 g_warning ("Socket check failed");
4160 return g_source_new (&broken_funcs, sizeof (GSource));
4163 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
4165 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
4166 g_source_set_static_name (source, "GSocket");
4167 socket_source = (GSocketSource *)source;
4169 socket_source->socket = g_object_ref (socket);
4170 socket_source->condition = condition;
4174 GSource *cancellable_source;
4176 cancellable_source = g_cancellable_source_new (cancellable);
4177 g_source_add_child_source (source, cancellable_source);
4178 g_source_set_dummy_callback (cancellable_source);
4179 g_source_unref (cancellable_source);
4183 add_condition_watch (socket, &socket_source->condition);
4184 socket_source->pollfd.fd = (gintptr) socket->priv->event;
4185 socket_source->pollfd.events = condition;
4186 socket_source->pollfd.revents = 0;
4187 g_source_add_poll (source, &socket_source->pollfd);
4189 socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
4192 if (socket->priv->timeout)
4193 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
4195 g_source_set_ready_time (source, -1);
4201 * g_socket_create_source: (skip)
4202 * @socket: a #GSocket
4203 * @condition: a #GIOCondition mask to monitor
4204 * @cancellable: (nullable): a %GCancellable or %NULL
4206 * Creates a #GSource that can be attached to a %GMainContext to monitor
4207 * for the availability of the specified @condition on the socket. The #GSource
4208 * keeps a reference to the @socket.
4210 * The callback on the source is of the #GSocketSourceFunc type.
4212 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
4213 * these conditions will always be reported output if they are true.
4215 * @cancellable if not %NULL can be used to cancel the source, which will
4216 * cause the source to trigger, reporting the current condition (which
4217 * is likely 0 unless cancellation happened at the same time as a
4218 * condition change). You can check for this in the callback using
4219 * g_cancellable_is_cancelled().
4221 * If @socket has a timeout set, and it is reached before @condition
4222 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
4223 * %G_IO_OUT depending on @condition. However, @socket will have been
4224 * marked as having had a timeout, and so the next #GSocket I/O method
4225 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
4227 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
4232 g_socket_create_source (GSocket *socket,
4233 GIOCondition condition,
4234 GCancellable *cancellable)
4236 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
4238 return socket_source_new (socket, condition, cancellable);
4242 * g_socket_condition_check:
4243 * @socket: a #GSocket
4244 * @condition: a #GIOCondition mask to check
4246 * Checks on the readiness of @socket to perform operations.
4247 * The operations specified in @condition are checked for and masked
4248 * against the currently-satisfied conditions on @socket. The result
4251 * Note that on Windows, it is possible for an operation to return
4252 * %G_IO_ERROR_WOULD_BLOCK even immediately after
4253 * g_socket_condition_check() has claimed that the socket is ready for
4254 * writing. Rather than calling g_socket_condition_check() and then
4255 * writing to the socket if it succeeds, it is generally better to
4256 * simply try writing to the socket right away, and try again later if
4257 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
4259 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
4260 * these conditions will always be set in the output if they are true.
4262 * This call never blocks.
4264 * Returns: the @GIOCondition mask of the current state
4269 g_socket_condition_check (GSocket *socket,
4270 GIOCondition condition)
4272 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
4274 if (!check_socket (socket, NULL))
4279 GIOCondition current_condition;
4281 condition |= G_IO_ERR | G_IO_HUP;
4283 add_condition_watch (socket, &condition);
4284 current_condition = update_condition (socket);
4285 remove_condition_watch (socket, &condition);
4286 return condition & current_condition;
4292 poll_fd.fd = socket->priv->fd;
4293 poll_fd.events = condition;
4294 poll_fd.revents = 0;
4297 result = g_poll (&poll_fd, 1, 0);
4298 while (result == -1 && get_socket_errno () == EINTR);
4300 return poll_fd.revents;
4306 * g_socket_condition_wait:
4307 * @socket: a #GSocket
4308 * @condition: a #GIOCondition mask to wait for
4309 * @cancellable: (nullable): a #GCancellable, or %NULL
4310 * @error: a #GError pointer, or %NULL
4312 * Waits for @condition to become true on @socket. When the condition
4313 * is met, %TRUE is returned.
4315 * If @cancellable is cancelled before the condition is met, or if the
4316 * socket has a timeout set and it is reached before the condition is
4317 * met, then %FALSE is returned and @error, if non-%NULL, is set to
4318 * the appropriate value (%G_IO_ERROR_CANCELLED or
4319 * %G_IO_ERROR_TIMED_OUT).
4321 * See also g_socket_condition_timed_wait().
4323 * Returns: %TRUE if the condition was met, %FALSE otherwise
4328 g_socket_condition_wait (GSocket *socket,
4329 GIOCondition condition,
4330 GCancellable *cancellable,
4333 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4335 return g_socket_condition_timed_wait (socket, condition, -1,
4336 cancellable, error);
4340 * g_socket_condition_timed_wait:
4341 * @socket: a #GSocket
4342 * @condition: a #GIOCondition mask to wait for
4343 * @timeout_us: the maximum time (in microseconds) to wait, or -1
4344 * @cancellable: (nullable): a #GCancellable, or %NULL
4345 * @error: a #GError pointer, or %NULL
4347 * Waits for up to @timeout_us microseconds for @condition to become true
4348 * on @socket. If the condition is met, %TRUE is returned.
4350 * If @cancellable is cancelled before the condition is met, or if
4351 * @timeout_us (or the socket's #GSocket:timeout) is reached before the
4352 * condition is met, then %FALSE is returned and @error, if non-%NULL,
4353 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
4354 * %G_IO_ERROR_TIMED_OUT).
4356 * If you don't want a timeout, use g_socket_condition_wait().
4357 * (Alternatively, you can pass -1 for @timeout_us.)
4359 * Note that although @timeout_us is in microseconds for consistency with
4360 * other GLib APIs, this function actually only has millisecond
4361 * resolution, and the behavior is undefined if @timeout_us is not an
4362 * exact number of milliseconds.
4364 * Returns: %TRUE if the condition was met, %FALSE otherwise
4369 g_socket_condition_timed_wait (GSocket *socket,
4370 GIOCondition condition,
4372 GCancellable *cancellable,
4378 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4380 if (!check_socket (socket, error))
4383 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4386 if (socket->priv->timeout &&
4387 (timeout_us < 0 || socket->priv->timeout < timeout_us / G_USEC_PER_SEC))
4388 timeout_ms = (gint64) socket->priv->timeout * 1000;
4389 else if (timeout_us != -1)
4390 timeout_ms = timeout_us / 1000;
4394 start_time = g_get_monotonic_time ();
4398 GIOCondition current_condition;
4404 /* Always check these */
4405 condition |= G_IO_ERR | G_IO_HUP;
4407 add_condition_watch (socket, &condition);
4410 events[num_events++] = socket->priv->event;
4412 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
4413 events[num_events++] = (WSAEVENT)cancel_fd.fd;
4415 if (timeout_ms == -1)
4416 timeout_ms = WSA_INFINITE;
4418 g_mutex_lock (&socket->priv->win32_source_lock);
4419 current_condition = update_condition_unlocked (socket);
4420 while ((condition & current_condition) == 0)
4422 if (!socket->priv->waiting)
4424 socket->priv->waiting = TRUE;
4425 socket->priv->waiting_result = 0;
4426 g_mutex_unlock (&socket->priv->win32_source_lock);
4428 res = WSAWaitForMultipleEvents (num_events, events, FALSE, timeout_ms, FALSE);
4430 g_mutex_lock (&socket->priv->win32_source_lock);
4431 socket->priv->waiting = FALSE;
4432 socket->priv->waiting_result = res;
4433 g_cond_broadcast (&socket->priv->win32_source_cond);
4437 if (timeout_ms != WSA_INFINITE)
4439 if (!g_cond_wait_until (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock, timeout_ms))
4441 res = WSA_WAIT_TIMEOUT;
4446 res = socket->priv->waiting_result;
4451 g_cond_wait (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock);
4452 res = socket->priv->waiting_result;
4456 if (res == WSA_WAIT_FAILED)
4458 int errsv = get_socket_errno ();
4460 g_set_error (error, G_IO_ERROR,
4461 socket_io_error_from_errno (errsv),
4462 _("Waiting for socket condition: %s"),
4463 socket_strerror (errsv));
4466 else if (res == WSA_WAIT_TIMEOUT)
4468 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4469 _("Socket I/O timed out"));
4473 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4476 current_condition = update_condition_unlocked (socket);
4478 if (timeout_ms != WSA_INFINITE)
4480 timeout_ms -= (g_get_monotonic_time () - start_time) * 1000;
4485 g_mutex_unlock (&socket->priv->win32_source_lock);
4486 remove_condition_watch (socket, &condition);
4488 g_cancellable_release_fd (cancellable);
4490 return (condition & current_condition) != 0;
4498 poll_fd[0].fd = socket->priv->fd;
4499 poll_fd[0].events = condition;
4502 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
4508 result = g_poll (poll_fd, num, timeout_ms);
4510 if (result != -1 || errsv != EINTR)
4513 if (timeout_ms != -1)
4515 timeout_ms -= (g_get_monotonic_time () - start_time) / 1000;
4522 g_cancellable_release_fd (cancellable);
4526 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4527 _("Socket I/O timed out"));
4531 return !g_cancellable_set_error_if_cancelled (cancellable, error);
4539 /* QNX has this weird upper limit, or at least used to back in the 6.x days.
4540 * This was discovered empirically and doesn't appear to be mentioned in any
4541 * of the official documentation. */
4542 # define G_SOCKET_CONTROL_BUFFER_SIZE_BYTES 2016
4544 # define G_SOCKET_CONTROL_BUFFER_SIZE_BYTES 2048
4547 /* Unfortunately these have to be macros rather than inline functions due to
4548 * using alloca(). */
4549 #define output_message_to_msghdr(message, prev_message, msg, prev_msg, error) \
4551 const GOutputMessage *_message = (message); \
4552 const GOutputMessage *_prev_message = (prev_message); \
4553 struct msghdr *_msg = (msg); \
4554 const struct msghdr *_prev_msg = (prev_msg); \
4555 GError **_error = (error); \
4557 _msg->msg_flags = 0; \
4560 if (_prev_message != NULL && _prev_message->address == _message->address) \
4562 _msg->msg_name = _prev_msg->msg_name; \
4563 _msg->msg_namelen = _prev_msg->msg_namelen; \
4565 else if (_message->address != NULL) \
4567 _msg->msg_namelen = g_socket_address_get_native_size (_message->address); \
4568 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4569 if (!g_socket_address_to_native (_message->address, _msg->msg_name, \
4570 _msg->msg_namelen, _error)) \
4575 _msg->msg_name = NULL; \
4576 _msg->msg_namelen = 0; \
4581 /* this entire expression will be evaluated at compile time */ \
4582 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4583 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4584 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4585 G_STRUCT_OFFSET (GOutputVector, buffer) && \
4586 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4587 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4588 G_STRUCT_OFFSET (GOutputVector, size)) \
4589 /* ABI is compatible */ \
4591 _msg->msg_iov = (struct iovec *) _message->vectors; \
4592 _msg->msg_iovlen = _message->num_vectors; \
4595 /* ABI is incompatible */ \
4599 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4600 for (i = 0; i < _message->num_vectors; i++) \
4602 _msg->msg_iov[i].iov_base = (void *) _message->vectors[i].buffer; \
4603 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4605 _msg->msg_iovlen = _message->num_vectors; \
4611 struct cmsghdr *cmsg; \
4614 _msg->msg_controllen = 0; \
4615 for (i = 0; i < _message->num_control_messages; i++) \
4616 _msg->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (_message->control_messages[i])); \
4618 if (_msg->msg_controllen == 0) \
4619 _msg->msg_control = NULL; \
4622 _msg->msg_control = g_alloca0 (_msg->msg_controllen); \
4625 cmsg = CMSG_FIRSTHDR (_msg); \
4626 for (i = 0; i < _message->num_control_messages; i++) \
4628 cmsg->cmsg_level = g_socket_control_message_get_level (_message->control_messages[i]); \
4629 cmsg->cmsg_type = g_socket_control_message_get_msg_type (_message->control_messages[i]); \
4630 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (_message->control_messages[i])); \
4631 g_socket_control_message_serialize (_message->control_messages[i], \
4632 CMSG_DATA (cmsg)); \
4633 cmsg = CMSG_NXTHDR (_msg, cmsg); \
4635 g_assert (cmsg == NULL); \
4639 #define input_message_to_msghdr(message, msg) \
4641 const GInputMessage *_message = (message); \
4642 struct msghdr *_msg = (msg); \
4645 if (_message->address) \
4647 _msg->msg_namelen = sizeof (struct sockaddr_storage); \
4648 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4652 _msg->msg_name = NULL; \
4653 _msg->msg_namelen = 0; \
4657 /* this entire expression will be evaluated at compile time */ \
4658 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4659 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4660 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4661 G_STRUCT_OFFSET (GInputVector, buffer) && \
4662 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4663 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4664 G_STRUCT_OFFSET (GInputVector, size)) \
4665 /* ABI is compatible */ \
4667 _msg->msg_iov = (struct iovec *) _message->vectors; \
4668 _msg->msg_iovlen = _message->num_vectors; \
4671 /* ABI is incompatible */ \
4675 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4676 for (i = 0; i < _message->num_vectors; i++) \
4678 _msg->msg_iov[i].iov_base = _message->vectors[i].buffer; \
4679 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4681 _msg->msg_iovlen = _message->num_vectors; \
4685 if (_message->control_messages == NULL) \
4687 _msg->msg_controllen = 0; \
4688 _msg->msg_control = NULL; \
4692 _msg->msg_controllen = G_SOCKET_CONTROL_BUFFER_SIZE_BYTES; \
4693 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4697 _msg->msg_flags = _message->flags; \
4701 input_message_from_msghdr (const struct msghdr *msg,
4702 GInputMessage *message,
4705 /* decode address */
4706 if (message->address != NULL)
4708 *message->address = cache_recv_address (socket, msg->msg_name,
4712 /* decode control messages */
4714 GPtrArray *my_messages = NULL;
4715 struct cmsghdr *cmsg;
4717 if (msg->msg_controllen >= (socklen_t) sizeof (struct cmsghdr))
4719 g_assert (message->control_messages != NULL);
4720 for (cmsg = CMSG_FIRSTHDR (msg);
4722 cmsg = CMSG_NXTHDR ((struct msghdr *) msg, cmsg))
4724 GSocketControlMessage *control_message;
4726 control_message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4728 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4730 if (control_message == NULL)
4731 /* We've already spewed about the problem in the
4732 deserialization code, so just continue */
4735 if (my_messages == NULL)
4736 my_messages = g_ptr_array_new ();
4737 g_ptr_array_add (my_messages, control_message);
4741 if (message->num_control_messages)
4742 *message->num_control_messages = my_messages != NULL ? my_messages->len : 0;
4744 if (message->control_messages)
4746 if (my_messages == NULL)
4748 *message->control_messages = NULL;
4752 g_ptr_array_add (my_messages, NULL);
4753 *message->control_messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4758 g_assert (my_messages == NULL);
4762 /* capture the flags */
4763 message->flags = msg->msg_flags;
4768 * g_socket_send_message:
4769 * @socket: a #GSocket
4770 * @address: (nullable): a #GSocketAddress, or %NULL
4771 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4772 * @num_vectors: the number of elements in @vectors, or -1
4773 * @messages: (array length=num_messages) (nullable): a pointer to an
4774 * array of #GSocketControlMessages, or %NULL.
4775 * @num_messages: number of elements in @messages, or -1.
4776 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
4777 * contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
4778 * @cancellable: (nullable): a %GCancellable or %NULL
4779 * @error: #GError for error reporting, or %NULL to ignore.
4781 * Send data to @address on @socket. For sending multiple messages see
4782 * g_socket_send_messages(); for easier use, see
4783 * g_socket_send() and g_socket_send_to().
4785 * If @address is %NULL then the message is sent to the default receiver
4786 * (set by g_socket_connect()).
4788 * @vectors must point to an array of #GOutputVector structs and
4789 * @num_vectors must be the length of this array. (If @num_vectors is -1,
4790 * then @vectors is assumed to be terminated by a #GOutputVector with a
4791 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
4792 * that the sent data will be gathered from. Using multiple
4793 * #GOutputVectors is more memory-efficient than manually copying
4794 * data from multiple sources into a single buffer, and more
4795 * network-efficient than making multiple calls to g_socket_send().
4797 * @messages, if non-%NULL, is taken to point to an array of @num_messages
4798 * #GSocketControlMessage instances. These correspond to the control
4799 * messages to be sent on the socket.
4800 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
4803 * @flags modify how the message is sent. The commonly available arguments
4804 * for this are available in the #GSocketMsgFlags enum, but the
4805 * values there are the same as the system values, and the flags
4806 * are passed in as-is, so you can pass in system-specific flags too.
4808 * If the socket is in blocking mode the call will block until there is
4809 * space for the data in the socket queue. If there is no space available
4810 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4811 * will be returned. To be notified when space is available, wait for the
4812 * %G_IO_OUT condition. Note though that you may still receive
4813 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4814 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4815 * very common due to the way the underlying APIs work.)
4817 * The sum of the sizes of each #GOutputVector in vectors must not be
4818 * greater than %G_MAXSSIZE. If the message can be larger than this,
4819 * then it is mandatory to use the g_socket_send_message_with_timeout()
4822 * On error -1 is returned and @error is set accordingly.
4824 * Returns: Number of bytes written (which may be less than @size), or -1
4830 g_socket_send_message (GSocket *socket,
4831 GSocketAddress *address,
4832 GOutputVector *vectors,
4834 GSocketControlMessage **messages,
4837 GCancellable *cancellable,
4840 GPollableReturn res;
4841 gsize bytes_written = 0;
4842 gsize vectors_size = 0;
4844 if (num_vectors != -1)
4846 for (gint i = 0; i < num_vectors; i++)
4848 /* No wrap-around for vectors_size */
4849 if (vectors_size > vectors_size + vectors[i].size)
4851 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
4852 _("Unable to send message: %s"),
4853 _("Message vectors too large"));
4857 vectors_size += vectors[i].size;
4862 for (gsize i = 0; vectors[i].buffer != NULL; i++)
4864 /* No wrap-around for vectors_size */
4865 if (vectors_size > vectors_size + vectors[i].size)
4867 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
4868 _("Unable to send message: %s"),
4869 _("Message vectors too large"));
4873 vectors_size += vectors[i].size;
4877 /* Check if vector's buffers are too big for gssize */
4878 if (vectors_size > G_MAXSSIZE)
4880 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
4881 _("Unable to send message: %s"),
4882 _("Message vectors too large"));
4886 res = g_socket_send_message_with_timeout (socket, address,
4887 vectors, num_vectors,
4888 messages, num_messages, flags,
4889 socket->priv->blocking ? -1 : 0,
4891 cancellable, error);
4893 g_assert (res != G_POLLABLE_RETURN_OK || bytes_written <= G_MAXSSIZE);
4895 if (res == G_POLLABLE_RETURN_WOULD_BLOCK)
4898 socket_set_error_lazy (error, EWOULDBLOCK, _("Error sending message: %s"));
4900 socket_set_error_lazy (error, WSAEWOULDBLOCK, _("Error sending message: %s"));
4904 return res == G_POLLABLE_RETURN_OK ? (gssize) bytes_written : -1;
4908 * g_socket_send_message_with_timeout:
4909 * @socket: a #GSocket
4910 * @address: (nullable): a #GSocketAddress, or %NULL
4911 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4912 * @num_vectors: the number of elements in @vectors, or -1
4913 * @messages: (array length=num_messages) (nullable): a pointer to an
4914 * array of #GSocketControlMessages, or %NULL.
4915 * @num_messages: number of elements in @messages, or -1.
4916 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
4917 * contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
4918 * @timeout_us: the maximum time (in microseconds) to wait, or -1
4919 * @bytes_written: (out) (optional): location to store the number of bytes that were written to the socket
4920 * @cancellable: (nullable): a %GCancellable or %NULL
4921 * @error: #GError for error reporting, or %NULL to ignore.
4923 * This behaves exactly the same as g_socket_send_message(), except that
4924 * the choice of timeout behavior is determined by the @timeout_us argument
4925 * rather than by @socket's properties.
4927 * On error %G_POLLABLE_RETURN_FAILED is returned and @error is set accordingly, or
4928 * if the socket is currently not writable %G_POLLABLE_RETURN_WOULD_BLOCK is
4929 * returned. @bytes_written will contain 0 in both cases.
4931 * Returns: %G_POLLABLE_RETURN_OK if all data was successfully written,
4932 * %G_POLLABLE_RETURN_WOULD_BLOCK if the socket is currently not writable, or
4933 * %G_POLLABLE_RETURN_FAILED if an error happened and @error is set.
4938 g_socket_send_message_with_timeout (GSocket *socket,
4939 GSocketAddress *address,
4940 const GOutputVector *vectors,
4942 GSocketControlMessage **messages,
4946 gsize *bytes_written,
4947 GCancellable *cancellable,
4950 GOutputVector one_vector;
4957 g_return_val_if_fail (G_IS_SOCKET (socket), G_POLLABLE_RETURN_FAILED);
4958 g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), G_POLLABLE_RETURN_FAILED);
4959 g_return_val_if_fail (num_vectors == 0 || vectors != NULL, G_POLLABLE_RETURN_FAILED);
4960 g_return_val_if_fail (num_messages == 0 || messages != NULL, G_POLLABLE_RETURN_FAILED);
4961 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), G_POLLABLE_RETURN_FAILED);
4962 g_return_val_if_fail (error == NULL || *error == NULL, G_POLLABLE_RETURN_FAILED);
4964 start_time = g_get_monotonic_time ();
4966 if (!check_socket (socket, error))
4967 return G_POLLABLE_RETURN_FAILED;
4969 if (!check_timeout (socket, error))
4970 return G_POLLABLE_RETURN_FAILED;
4972 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4973 return G_POLLABLE_RETURN_FAILED;
4975 if (num_vectors == -1)
4977 for (num_vectors = 0;
4978 vectors[num_vectors].buffer != NULL;
4983 if (num_messages == -1)
4985 for (num_messages = 0;
4986 messages != NULL && messages[num_messages] != NULL;
4991 if (num_vectors == 0)
4995 one_vector.buffer = &zero;
4996 one_vector.size = 1;
4998 vectors = &one_vector;
5003 GOutputMessage output_message;
5006 GError *child_error = NULL;
5008 output_message.address = address;
5009 output_message.vectors = (GOutputVector *) vectors;
5010 output_message.num_vectors = num_vectors;
5011 output_message.bytes_sent = 0;
5012 output_message.control_messages = messages;
5013 output_message.num_control_messages = num_messages;
5015 output_message_to_msghdr (&output_message, NULL, &msg, NULL, &child_error);
5017 if (child_error != NULL)
5019 g_propagate_error (error, child_error);
5020 return G_POLLABLE_RETURN_FAILED;
5025 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
5028 int errsv = get_socket_errno ();
5033 if (errsv == EWOULDBLOCK || errsv == EAGAIN)
5035 if (timeout_us != 0)
5037 if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
5038 cancellable, error))
5039 return G_POLLABLE_RETURN_FAILED;
5044 return G_POLLABLE_RETURN_WOULD_BLOCK;
5047 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5048 return G_POLLABLE_RETURN_FAILED;
5054 *bytes_written = result;
5056 return G_POLLABLE_RETURN_OK;
5060 struct sockaddr_storage addr;
5067 /* Win32 doesn't support control messages.
5068 Actually this is possible for raw and datagram sockets
5069 via WSASendMessage on Vista or later, but that doesn't
5071 if (num_messages != 0)
5073 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
5074 _("GSocketControlMessage not supported on Windows"));
5075 return G_POLLABLE_RETURN_FAILED;
5079 bufs = g_newa (WSABUF, num_vectors);
5080 for (i = 0; i < num_vectors; i++)
5082 bufs[i].buf = (char *)vectors[i].buffer;
5083 bufs[i].len = (gulong)vectors[i].size;
5087 addrlen = 0; /* Avoid warning */
5090 addrlen = g_socket_address_get_native_size (address);
5091 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
5092 return G_POLLABLE_RETURN_FAILED;
5098 result = WSASendTo (socket->priv->fd,
5101 (const struct sockaddr *)&addr, addrlen,
5104 result = WSASend (socket->priv->fd,
5111 int errsv = get_socket_errno ();
5113 if (errsv == WSAEINTR)
5116 if (errsv == WSAEWOULDBLOCK)
5118 win32_unset_event_mask (socket, FD_WRITE);
5120 if (timeout_us != 0)
5122 if (!block_on_timeout (socket, G_IO_OUT, timeout_us,
5123 start_time, cancellable, error))
5124 return G_POLLABLE_RETURN_FAILED;
5129 return G_POLLABLE_RETURN_WOULD_BLOCK;
5132 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5133 return G_POLLABLE_RETURN_FAILED;
5139 *bytes_written = bytes_sent;
5140 return G_POLLABLE_RETURN_OK;
5146 * g_socket_send_messages:
5147 * @socket: a #GSocket
5148 * @messages: (array length=num_messages): an array of #GOutputMessage structs
5149 * @num_messages: the number of elements in @messages
5150 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
5151 * contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5152 * @cancellable: (nullable): a %GCancellable or %NULL
5153 * @error: #GError for error reporting, or %NULL to ignore.
5155 * Send multiple data messages from @socket in one go. This is the most
5156 * complicated and fully-featured version of this call. For easier use, see
5157 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
5159 * @messages must point to an array of #GOutputMessage structs and
5160 * @num_messages must be the length of this array. Each #GOutputMessage
5161 * contains an address to send the data to, and a pointer to an array of
5162 * #GOutputVector structs to describe the buffers that the data to be sent
5163 * for each message will be gathered from. Using multiple #GOutputVectors is
5164 * more memory-efficient than manually copying data from multiple sources
5165 * into a single buffer, and more network-efficient than making multiple
5166 * calls to g_socket_send(). Sending multiple messages in one go avoids the
5167 * overhead of making a lot of syscalls in scenarios where a lot of data
5168 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
5169 * or where the same data needs to be sent to multiple recipients.
5171 * @flags modify how the message is sent. The commonly available arguments
5172 * for this are available in the #GSocketMsgFlags enum, but the
5173 * values there are the same as the system values, and the flags
5174 * are passed in as-is, so you can pass in system-specific flags too.
5176 * If the socket is in blocking mode the call will block until there is
5177 * space for all the data in the socket queue. If there is no space available
5178 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
5179 * will be returned if no data was written at all, otherwise the number of
5180 * messages sent will be returned. To be notified when space is available,
5181 * wait for the %G_IO_OUT condition. Note though that you may still receive
5182 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
5183 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
5184 * very common due to the way the underlying APIs work.)
5186 * On error -1 is returned and @error is set accordingly. An error will only
5187 * be returned if zero messages could be sent; otherwise the number of messages
5188 * successfully sent before the error will be returned.
5190 * Returns: number of messages sent, or -1 on error. Note that the number of
5191 * messages sent may be smaller than @num_messages if the socket is
5192 * non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
5193 * in which case the caller may re-try to send the remaining messages.
5198 g_socket_send_messages (GSocket *socket,
5199 GOutputMessage *messages,
5202 GCancellable *cancellable,
5205 return g_socket_send_messages_with_timeout (socket, messages, num_messages,
5207 socket->priv->blocking ? -1 : 0,
5208 cancellable, error);
5212 g_socket_send_messages_with_timeout (GSocket *socket,
5213 GOutputMessage *messages,
5217 GCancellable *cancellable,
5222 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5223 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5224 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
5225 g_return_val_if_fail (error == NULL || *error == NULL, -1);
5227 start_time = g_get_monotonic_time ();
5229 if (!check_socket (socket, error))
5232 if (!check_timeout (socket, error))
5235 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5238 if (num_messages == 0)
5241 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
5243 struct mmsghdr *msgvec;
5246 /* Clamp the number of vectors if more given than we can write in one go.
5247 * The caller has to handle short writes anyway.
5249 if (num_messages > G_IOV_MAX)
5250 num_messages = G_IOV_MAX;
5252 msgvec = g_newa (struct mmsghdr, num_messages);
5254 for (i = 0; i < num_messages; ++i)
5256 GOutputMessage *msg = &messages[i];
5257 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5258 GError *child_error = NULL;
5260 msgvec[i].msg_len = 0;
5262 output_message_to_msghdr (msg, (i > 0) ? &messages[i - 1] : NULL,
5263 msg_hdr, (i > 0) ? &msgvec[i - 1].msg_hdr : NULL,
5266 if (child_error != NULL)
5268 g_propagate_error (error, child_error);
5273 for (num_sent = 0; num_sent < num_messages;)
5277 ret = sendmmsg (socket->priv->fd, msgvec + num_sent, num_messages - num_sent,
5278 flags | G_SOCKET_DEFAULT_SEND_FLAGS);
5282 int errsv = get_socket_errno ();
5287 if (timeout_us != 0 &&
5288 (errsv == EWOULDBLOCK ||
5291 if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
5292 cancellable, error))
5296 g_clear_error (error);
5306 /* If any messages were successfully sent, do not error. */
5310 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5318 for (i = 0; i < num_sent; ++i)
5319 messages[i].bytes_sent = msgvec[i].msg_len;
5327 gint64 wait_timeout;
5329 wait_timeout = timeout_us;
5331 for (i = 0; i < num_messages; ++i)
5333 GOutputMessage *msg = &messages[i];
5334 GError *msg_error = NULL;
5335 GPollableReturn pollable_result;
5336 gsize bytes_written = 0;
5338 pollable_result = g_socket_send_message_with_timeout (socket, msg->address,
5341 msg->control_messages,
5342 msg->num_control_messages,
5343 flags, wait_timeout,
5345 cancellable, &msg_error);
5347 if (pollable_result == G_POLLABLE_RETURN_WOULD_BLOCK)
5350 socket_set_error_lazy (&msg_error, EWOULDBLOCK, _("Error sending message: %s"));
5352 socket_set_error_lazy (&msg_error, WSAEWOULDBLOCK, _("Error sending message: %s"));
5356 if (G_MAXSSIZE > bytes_written &&
5357 pollable_result == G_POLLABLE_RETURN_OK)
5358 result = (gssize) bytes_written;
5362 /* check if we've timed out or how much time to wait at most */
5365 gint64 elapsed = g_get_monotonic_time () - start_time;
5366 wait_timeout = MAX (timeout_us - elapsed, 1);
5371 /* if we couldn't send all messages, just return how many we did
5372 * manage to send, provided we managed to send at least one */
5375 g_error_free (msg_error);
5380 g_propagate_error (error, msg_error);
5385 msg->bytes_sent = result;
5393 static GSocketAddress *
5394 cache_recv_address (GSocket *socket, struct sockaddr *native, size_t native_len)
5396 GSocketAddress *saddr;
5398 guint64 oldest_time = G_MAXUINT64;
5399 gint oldest_index = 0;
5401 if (native_len == 0)
5405 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
5407 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
5408 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
5409 gsize tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
5414 if (tmp_native_len != native_len)
5417 if (memcmp (tmp_native, native, native_len) == 0)
5419 saddr = g_object_ref (tmp);
5420 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
5424 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
5426 oldest_time = socket->priv->recv_addr_cache[i].last_used;
5431 saddr = g_socket_address_new_from_native (native, native_len);
5433 if (socket->priv->recv_addr_cache[oldest_index].addr)
5435 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
5436 g_free (socket->priv->recv_addr_cache[oldest_index].native);
5439 socket->priv->recv_addr_cache[oldest_index].native = g_memdup2 (native, native_len);
5440 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
5441 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
5442 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
5448 g_socket_receive_message_with_timeout (GSocket *socket,
5449 GSocketAddress **address,
5450 GInputVector *vectors,
5452 GSocketControlMessage ***messages,
5456 GCancellable *cancellable,
5459 GInputVector one_vector;
5463 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5465 start_time = g_get_monotonic_time ();
5467 if (!check_socket (socket, error))
5470 if (!check_timeout (socket, error))
5473 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5476 if (num_vectors == -1)
5478 for (num_vectors = 0;
5479 vectors[num_vectors].buffer != NULL;
5484 if (num_vectors == 0)
5486 one_vector.buffer = &one_byte;
5487 one_vector.size = 1;
5489 vectors = &one_vector;
5494 GInputMessage input_message;
5498 input_message.address = address;
5499 input_message.vectors = vectors;
5500 input_message.num_vectors = num_vectors;
5501 input_message.bytes_received = 0;
5502 input_message.flags = (flags != NULL) ? *flags : 0;
5503 input_message.control_messages = messages;
5504 input_message.num_control_messages = (guint *) num_messages;
5506 /* We always set the close-on-exec flag so we don't leak file
5507 * descriptors into child processes. Note that gunixfdmessage.c
5508 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5510 #ifdef MSG_CMSG_CLOEXEC
5511 input_message.flags |= MSG_CMSG_CLOEXEC;
5514 input_message_to_msghdr (&input_message, &msg);
5519 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5520 #ifdef MSG_CMSG_CLOEXEC
5521 if (result < 0 && get_socket_errno () == EINVAL)
5523 /* We must be running on an old kernel. Call without the flag. */
5524 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
5525 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5531 int errsv = get_socket_errno ();
5536 if (timeout_us != 0 &&
5537 (errsv == EWOULDBLOCK ||
5540 if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
5541 cancellable, error))
5547 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5553 input_message_from_msghdr (&msg, &input_message, socket);
5556 *flags = input_message.flags;
5562 struct sockaddr_storage addr;
5564 DWORD bytes_received;
5571 bufs = g_newa (WSABUF, num_vectors);
5572 for (i = 0; i < num_vectors; i++)
5574 bufs[i].buf = (char *)vectors[i].buffer;
5575 bufs[i].len = (gulong)vectors[i].size;
5587 /* addrlen has to be of type int because that’s how WSARecvFrom() is defined */
5588 G_STATIC_ASSERT (sizeof addr <= G_MAXINT);
5590 addrlen = sizeof addr;
5592 result = WSARecvFrom (socket->priv->fd,
5594 &bytes_received, &win_flags,
5595 (struct sockaddr *)&addr, &addrlen,
5598 result = WSARecv (socket->priv->fd,
5600 &bytes_received, &win_flags,
5604 int errsv = get_socket_errno ();
5606 if (errsv == WSAEINTR)
5609 win32_unset_event_mask (socket, FD_READ);
5611 if (errsv == WSAEWOULDBLOCK)
5613 if (timeout_us != 0)
5615 if (!block_on_timeout (socket, G_IO_IN, timeout_us,
5616 start_time, cancellable, error))
5623 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5626 win32_unset_event_mask (socket, FD_READ);
5630 /* decode address */
5631 if (address != NULL)
5633 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
5636 /* capture the flags */
5640 if (messages != NULL)
5642 if (num_messages != NULL)
5645 return bytes_received;
5651 * g_socket_receive_messages:
5652 * @socket: a #GSocket
5653 * @messages: (array length=num_messages): an array of #GInputMessage structs
5654 * @num_messages: the number of elements in @messages
5655 * @flags: an int containing #GSocketMsgFlags flags for the overall operation,
5656 * which may additionally contain
5657 * [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5658 * @cancellable: (nullable): a %GCancellable or %NULL
5659 * @error: #GError for error reporting, or %NULL to ignore
5661 * Receive multiple data messages from @socket in one go. This is the most
5662 * complicated and fully-featured version of this call. For easier use, see
5663 * g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
5665 * @messages must point to an array of #GInputMessage structs and
5666 * @num_messages must be the length of this array. Each #GInputMessage
5667 * contains a pointer to an array of #GInputVector structs describing the
5668 * buffers that the data received in each message will be written to. Using
5669 * multiple #GInputVectors is more memory-efficient than manually copying data
5670 * out of a single buffer to multiple sources, and more system-call-efficient
5671 * than making multiple calls to g_socket_receive(), such as in scenarios where
5672 * a lot of data packets need to be received (e.g. high-bandwidth video
5673 * streaming over RTP/UDP).
5675 * @flags modify how all messages are received. The commonly available
5676 * arguments for this are available in the #GSocketMsgFlags enum, but the
5677 * values there are the same as the system values, and the flags
5678 * are passed in as-is, so you can pass in system-specific flags too. These
5679 * flags affect the overall receive operation. Flags affecting individual
5680 * messages are returned in #GInputMessage.flags.
5682 * The other members of #GInputMessage are treated as described in its
5685 * If #GSocket:blocking is %TRUE the call will block until @num_messages have
5686 * been received, or the end of the stream is reached.
5688 * If #GSocket:blocking is %FALSE the call will return up to @num_messages
5689 * without blocking, or %G_IO_ERROR_WOULD_BLOCK if no messages are queued in the
5690 * operating system to be received.
5692 * In blocking mode, if #GSocket:timeout is positive and is reached before any
5693 * messages are received, %G_IO_ERROR_TIMED_OUT is returned, otherwise up to
5694 * @num_messages are returned. (Note: This is effectively the
5695 * behaviour of `MSG_WAITFORONE` with recvmmsg().)
5697 * To be notified when messages are available, wait for the
5698 * %G_IO_IN condition. Note though that you may still receive
5699 * %G_IO_ERROR_WOULD_BLOCK from g_socket_receive_messages() even if you were
5700 * previously notified of a %G_IO_IN condition.
5702 * If the remote peer closes the connection, any messages queued in the
5703 * operating system will be returned, and subsequent calls to
5704 * g_socket_receive_messages() will return 0 (with no error set).
5706 * On error -1 is returned and @error is set accordingly. An error will only
5707 * be returned if zero messages could be received; otherwise the number of
5708 * messages successfully received before the error will be returned.
5710 * Returns: number of messages received, or -1 on error. Note that the number
5711 * of messages received may be smaller than @num_messages if in non-blocking
5712 * mode, if the peer closed the connection, or if @num_messages
5713 * was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
5714 * to receive the remaining messages.
5719 g_socket_receive_messages (GSocket *socket,
5720 GInputMessage *messages,
5723 GCancellable *cancellable,
5726 if (!check_socket (socket, error) ||
5727 !check_timeout (socket, error))
5730 return g_socket_receive_messages_with_timeout (socket, messages, num_messages,
5732 socket->priv->blocking ? -1 : 0,
5733 cancellable, error);
5737 g_socket_receive_messages_with_timeout (GSocket *socket,
5738 GInputMessage *messages,
5742 GCancellable *cancellable,
5747 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5748 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5749 g_return_val_if_fail (cancellable == NULL ||
5750 G_IS_CANCELLABLE (cancellable), -1);
5751 g_return_val_if_fail (error == NULL || *error == NULL, -1);
5753 start_time = g_get_monotonic_time ();
5755 if (!check_socket (socket, error))
5758 if (!check_timeout (socket, error))
5761 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5764 if (num_messages == 0)
5767 #if !defined (G_OS_WIN32) && defined (HAVE_RECVMMSG)
5769 struct mmsghdr *msgvec;
5770 guint i, num_received;
5772 /* Clamp the number of vectors if more given than we can write in one go.
5773 * The caller has to handle short writes anyway.
5775 if (num_messages > G_IOV_MAX)
5776 num_messages = G_IOV_MAX;
5778 msgvec = g_newa (struct mmsghdr, num_messages);
5780 for (i = 0; i < num_messages; ++i)
5782 GInputMessage *msg = &messages[i];
5783 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5785 input_message_to_msghdr (msg, msg_hdr);
5786 msgvec[i].msg_len = 0;
5789 /* We always set the close-on-exec flag so we don't leak file
5790 * descriptors into child processes. Note that gunixfdmessage.c
5791 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5793 #ifdef MSG_CMSG_CLOEXEC
5794 flags |= MSG_CMSG_CLOEXEC;
5797 for (num_received = 0; num_received < num_messages;)
5801 /* We operate in non-blocking mode and handle the timeout ourselves. */
5802 ret = recvmmsg (socket->priv->fd,
5803 msgvec + num_received,
5804 num_messages - num_received,
5805 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5806 #ifdef MSG_CMSG_CLOEXEC
5807 if (ret < 0 && get_socket_errno () == EINVAL)
5809 /* We must be running on an old kernel. Call without the flag. */
5810 flags &= ~(MSG_CMSG_CLOEXEC);
5811 ret = recvmmsg (socket->priv->fd,
5812 msgvec + num_received,
5813 num_messages - num_received,
5814 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5820 int errsv = get_socket_errno ();
5825 if (timeout_us != 0 &&
5826 (errsv == EWOULDBLOCK ||
5829 if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
5830 cancellable, error))
5832 if (num_received > 0)
5834 g_clear_error (error);
5844 /* If any messages were successfully received, do not error. */
5845 if (num_received > 0)
5848 socket_set_error_lazy (error, errsv,
5849 _("Error receiving message: %s"));
5859 num_received += ret;
5862 for (i = 0; i < num_received; ++i)
5864 input_message_from_msghdr (&msgvec[i].msg_hdr, &messages[i], socket);
5865 messages[i].bytes_received = msgvec[i].msg_len;
5868 return num_received;
5873 gint64 wait_timeout;
5875 wait_timeout = timeout_us;
5877 for (i = 0; i < num_messages; i++)
5879 GInputMessage *msg = &messages[i];
5881 GError *msg_error = NULL;
5883 msg->flags = flags; /* in-out parameter */
5885 len = g_socket_receive_message_with_timeout (socket,
5889 msg->control_messages,
5890 (gint *) msg->num_control_messages,
5896 /* check if we've timed out or how much time to wait at most */
5899 gint64 elapsed = g_get_monotonic_time () - start_time;
5900 wait_timeout = MAX (timeout_us - elapsed, 1);
5904 msg->bytes_received = len;
5907 (g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK) ||
5908 g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)))
5910 g_clear_error (&msg_error);
5914 if (msg_error != NULL)
5916 g_propagate_error (error, msg_error);
5930 * g_socket_receive_message:
5931 * @socket: a #GSocket
5932 * @address: (out) (optional): a pointer to a #GSocketAddress
5934 * @vectors: (array length=num_vectors): an array of #GInputVector structs
5935 * @num_vectors: the number of elements in @vectors, or -1
5936 * @messages: (array length=num_messages) (out) (optional) (nullable): a pointer
5937 * which may be filled with an array of #GSocketControlMessages, or %NULL
5938 * @num_messages: (out): a pointer which will be filled with the number of
5939 * elements in @messages, or %NULL
5940 * @flags: (inout): a pointer to an int containing #GSocketMsgFlags flags,
5941 * which may additionally contain
5942 * [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5943 * @cancellable: a %GCancellable or %NULL
5944 * @error: a #GError pointer, or %NULL
5946 * Receive data from a socket. For receiving multiple messages, see
5947 * g_socket_receive_messages(); for easier use, see
5948 * g_socket_receive() and g_socket_receive_from().
5950 * If @address is non-%NULL then @address will be set equal to the
5951 * source address of the received packet.
5952 * @address is owned by the caller.
5954 * @vector must point to an array of #GInputVector structs and
5955 * @num_vectors must be the length of this array. These structs
5956 * describe the buffers that received data will be scattered into.
5957 * If @num_vectors is -1, then @vectors is assumed to be terminated
5958 * by a #GInputVector with a %NULL buffer pointer.
5960 * As a special case, if @num_vectors is 0 (in which case, @vectors
5961 * may of course be %NULL), then a single byte is received and
5962 * discarded. This is to facilitate the common practice of sending a
5963 * single '\0' byte for the purposes of transferring ancillary data.
5965 * @messages, if non-%NULL, will be set to point to a newly-allocated
5966 * array of #GSocketControlMessage instances or %NULL if no such
5967 * messages was received. These correspond to the control messages
5968 * received from the kernel, one #GSocketControlMessage per message
5969 * from the kernel. This array is %NULL-terminated and must be freed
5970 * by the caller using g_free() after calling g_object_unref() on each
5971 * element. If @messages is %NULL, any control messages received will
5974 * @num_messages, if non-%NULL, will be set to the number of control
5975 * messages received.
5977 * If both @messages and @num_messages are non-%NULL, then
5978 * @num_messages gives the number of #GSocketControlMessage instances
5979 * in @messages (ie: not including the %NULL terminator).
5981 * @flags is an in/out parameter. The commonly available arguments
5982 * for this are available in the #GSocketMsgFlags enum, but the
5983 * values there are the same as the system values, and the flags
5984 * are passed in as-is, so you can pass in system-specific flags too
5985 * (and g_socket_receive_message() may pass system-specific flags out).
5986 * Flags passed in to the parameter affect the receive operation; flags returned
5987 * out of it are relevant to the specific returned message.
5989 * As with g_socket_receive(), data may be discarded if @socket is
5990 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
5991 * provide enough buffer space to read a complete message. You can pass
5992 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
5993 * removing it from the receive queue, but there is no portable way to find
5994 * out the length of the message other than by reading it into a
5995 * sufficiently-large buffer.
5997 * If the socket is in blocking mode the call will block until there
5998 * is some data to receive, the connection is closed, or there is an
5999 * error. If there is no data available and the socket is in
6000 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
6001 * returned. To be notified when data is available, wait for the
6002 * %G_IO_IN condition.
6004 * On error -1 is returned and @error is set accordingly.
6006 * Returns: Number of bytes read, or 0 if the connection was closed by
6007 * the peer, or -1 on error
6012 g_socket_receive_message (GSocket *socket,
6013 GSocketAddress **address,
6014 GInputVector *vectors,
6016 GSocketControlMessage ***messages,
6019 GCancellable *cancellable,
6022 return g_socket_receive_message_with_timeout (socket, address, vectors,
6023 num_vectors, messages,
6024 num_messages, flags,
6025 socket->priv->blocking ? -1 : 0,
6026 cancellable, error);
6030 * g_socket_get_credentials:
6031 * @socket: a #GSocket.
6032 * @error: #GError for error reporting, or %NULL to ignore.
6034 * Returns the credentials of the foreign process connected to this
6035 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
6038 * If this operation isn't supported on the OS, the method fails with
6039 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
6040 * by reading the %SO_PEERCRED option on the underlying socket.
6042 * This method can be expected to be available on the following platforms:
6044 * - Linux since GLib 2.26
6045 * - OpenBSD since GLib 2.30
6046 * - Solaris, Illumos and OpenSolaris since GLib 2.40
6047 * - NetBSD since GLib 2.42
6048 * - macOS, tvOS, iOS since GLib 2.66
6050 * Other ways to obtain credentials from a foreign peer includes the
6051 * #GUnixCredentialsMessage type and
6052 * g_unix_connection_send_credentials() /
6053 * g_unix_connection_receive_credentials() functions.
6055 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
6056 * that must be freed with g_object_unref().
6061 g_socket_get_credentials (GSocket *socket,
6066 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
6067 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6069 if (!check_socket (socket, error))
6074 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
6078 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
6079 socklen_t optlen = sizeof (native_creds_buf);
6081 if (getsockopt (socket->priv->fd,
6087 ret = g_credentials_new ();
6088 g_credentials_set_native (ret,
6089 G_CREDENTIALS_NATIVE_TYPE,
6093 #elif G_CREDENTIALS_USE_APPLE_XUCRED
6096 socklen_t optlen = sizeof (cred);
6098 if (getsockopt (socket->priv->fd,
6105 if (cred.cr_version == XUCRED_VERSION)
6108 socklen_t optlen = sizeof (pid);
6110 ret = g_credentials_new ();
6111 g_credentials_set_native (ret,
6112 G_CREDENTIALS_NATIVE_TYPE,
6115 #ifdef LOCAL_PEERPID
6116 if (getsockopt (socket->priv->fd,
6121 _g_credentials_set_local_peerid (ret, pid);
6128 G_IO_ERROR_NOT_SUPPORTED,
6129 /* No point in translating this! */
6130 "struct xucred cr_version %u != %u",
6131 cred.cr_version, XUCRED_VERSION);
6132 /* Reuse a translatable string we already have */
6133 g_prefix_error (error,
6134 _("Unable to read socket credentials: %s"),
6140 else if (optlen == 0 || errno == EINVAL)
6144 G_IO_ERROR_NOT_SUPPORTED,
6145 _("Unable to read socket credentials: %s"),
6146 "unsupported socket type");
6150 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
6152 struct unpcbid cred;
6153 socklen_t optlen = sizeof (cred);
6155 if (getsockopt (socket->priv->fd,
6161 ret = g_credentials_new ();
6162 g_credentials_set_native (ret,
6163 G_CREDENTIALS_NATIVE_TYPE,
6167 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
6169 ucred_t *ucred = NULL;
6171 if (getpeerucred (socket->priv->fd, &ucred) == 0)
6173 ret = g_credentials_new ();
6174 g_credentials_set_native (ret,
6175 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
6180 #elif G_CREDENTIALS_USE_WIN32_PID
6184 if (WSAIoctl (socket->priv->fd, SIO_AF_UNIX_GETPEERPID,
6186 &peerid, sizeof(peerid),
6187 /* Windows bug: always 0 https://github.com/microsoft/WSL/issues/4676 */
6191 ret = g_credentials_new ();
6192 g_credentials_set_native (ret,
6193 G_CREDENTIALS_TYPE_WIN32_PID,
6198 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
6203 int errsv = get_socket_errno ();
6207 socket_io_error_from_errno (errsv),
6208 _("Unable to read socket credentials: %s"),
6209 socket_strerror (errsv));
6214 g_set_error_literal (error,
6216 G_IO_ERROR_NOT_SUPPORTED,
6217 _("g_socket_get_credentials not implemented for this OS"));
6224 * g_socket_get_option:
6225 * @socket: a #GSocket
6226 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
6227 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
6228 * @value: (out): return location for the option value
6229 * @error: #GError for error reporting, or %NULL to ignore.
6231 * Gets the value of an integer-valued option on @socket, as with
6232 * getsockopt(). (If you need to fetch a non-integer-valued option,
6233 * you will need to call getsockopt() directly.)
6235 * The [<gio/gnetworking.h>][gio-gnetworking.h]
6236 * header pulls in system headers that will define most of the
6237 * standard/portable socket options. For unusual socket protocols or
6238 * platform-dependent options, you may need to include additional
6241 * Note that even for socket options that are a single byte in size,
6242 * @value is still a pointer to a #gint variable, not a #guchar;
6243 * g_socket_get_option() will handle the conversion internally.
6245 * Returns: success or failure. On failure, @error will be set, and
6246 * the system error value (`errno` or WSAGetLastError()) will still
6247 * be set to the result of the getsockopt() call.
6252 g_socket_get_option (GSocket *socket,
6260 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
6262 /* g_socket_get_option() is called during socket init, so skip the init checks
6263 * in check_socket() */
6264 if (socket->priv->inited && !check_socket (socket, error))
6268 size = sizeof (gint);
6269 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
6271 int errsv = get_socket_errno ();
6273 g_set_error_literal (error,
6275 socket_io_error_from_errno (errsv),
6276 socket_strerror (errsv));
6278 /* Reset errno in case the caller wants to look at it */
6284 #if G_BYTE_ORDER == G_BIG_ENDIAN
6285 /* If the returned value is smaller than an int then we need to
6286 * slide it over into the low-order bytes of *value.
6288 if (size != sizeof (gint))
6289 *value = *value >> (8 * (sizeof (gint) - size));
6296 * g_socket_set_option:
6297 * @socket: a #GSocket
6298 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
6299 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
6300 * @value: the value to set the option to
6301 * @error: #GError for error reporting, or %NULL to ignore.
6303 * Sets the value of an integer-valued option on @socket, as with
6304 * setsockopt(). (If you need to set a non-integer-valued option,
6305 * you will need to call setsockopt() directly.)
6307 * The [<gio/gnetworking.h>][gio-gnetworking.h]
6308 * header pulls in system headers that will define most of the
6309 * standard/portable socket options. For unusual socket protocols or
6310 * platform-dependent options, you may need to include additional
6313 * Returns: success or failure. On failure, @error will be set, and
6314 * the system error value (`errno` or WSAGetLastError()) will still
6315 * be set to the result of the setsockopt() call.
6320 g_socket_set_option (GSocket *socket,
6328 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
6330 /* g_socket_set_option() is called during socket init, so skip the init checks
6331 * in check_socket() */
6332 if (socket->priv->inited && !check_socket (socket, error))
6335 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
6338 #if !defined (__linux__) && !defined (G_OS_WIN32)
6339 /* Linux and Windows let you set a single-byte value from an int,
6340 * but most other platforms don't.
6342 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
6344 #if G_BYTE_ORDER == G_BIG_ENDIAN
6345 value = value << (8 * (sizeof (gint) - 1));
6347 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
6352 errsv = get_socket_errno ();
6354 g_set_error_literal (error,
6356 socket_io_error_from_errno (errsv),
6357 socket_strerror (errsv));