1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2008 Christian Kellner, Samuel Cormier-Iijima
4 * Copyright © 2009 Codethink Limited
5 * Copyright © 2009 Red Hat, Inc
6 * Copyright © 2015 Collabora, Ltd.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General
19 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 * Authors: Christian Kellner <gicmo@gnome.org>
22 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
23 * Ryan Lortie <desrt@desrt.ca>
24 * Alexander Larsson <alexl@redhat.com>
25 * Philip Withnall <philip.withnall@collabora.co.uk>
33 #include "glib-unix.h"
44 # include <sys/ioctl.h>
47 #ifdef HAVE_SYS_FILIO_H
48 # include <sys/filio.h>
55 #include "gcancellable.h"
56 #include "gdatagrambased.h"
57 #include "gioenumtypes.h"
58 #include "ginetaddress.h"
59 #include "ginitable.h"
63 #include "gnetworkingprivate.h"
64 #include "gsocketaddress.h"
65 #include "gsocketcontrolmessage.h"
66 #include "gcredentials.h"
67 #include "gcredentialsprivate.h"
71 /* For Windows XP runtime compatibility, but use the system's if_nametoindex() if available */
72 #include "gwin32networking.h"
77 * @short_description: Low-level socket object
79 * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
81 * A #GSocket is a low-level networking primitive. It is a more or less
82 * direct mapping of the BSD socket API in a portable GObject based API.
83 * It supports both the UNIX socket implementations and winsock2 on Windows.
85 * #GSocket is the platform independent base upon which the higher level
86 * network primitives are based. Applications are not typically meant to
87 * use it directly, but rather through classes like #GSocketClient,
88 * #GSocketService and #GSocketConnection. However there may be cases where
89 * direct use of #GSocket is useful.
91 * #GSocket implements the #GInitable interface, so if it is manually constructed
92 * by e.g. g_object_new() you must call g_initable_init() and check the
93 * results before using the object. This is done automatically in
94 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
97 * Sockets operate in two general modes, blocking or non-blocking. When
98 * in blocking mode all operations (which don’t take an explicit blocking
99 * parameter) block until the requested operation
100 * is finished or there is an error. In non-blocking mode all calls that
101 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
102 * To know when a call would successfully run you can call g_socket_condition_check(),
103 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
104 * attach it to a #GMainContext to get callbacks when I/O is possible.
105 * Note that all sockets are always set to non blocking mode in the system, and
106 * blocking mode is emulated in GSocket.
108 * When working in non-blocking mode applications should always be able to
109 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
110 * function said that I/O was possible. This can easily happen in case
111 * of a race condition in the application, but it can also happen for other
112 * reasons. For instance, on Windows a socket is always seen as writable
113 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
115 * #GSockets can be either connection oriented or datagram based.
116 * For connection oriented types you must first establish a connection by
117 * either connecting to an address or accepting a connection from another
118 * address. For connectionless socket types the target/source address is
119 * specified or received in each I/O operation.
121 * All socket file descriptors are set to be close-on-exec.
123 * Note that creating a #GSocket causes the signal %SIGPIPE to be
124 * ignored for the remainder of the program. If you are writing a
125 * command-line utility that uses #GSocket, you may need to take into
126 * account the fact that your program will not automatically be killed
127 * if it tries to write to %stdout after it has been closed.
129 * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
130 * a #GSocket concurrently from multiple threads, you must implement your own
136 static void g_socket_initable_iface_init (GInitableIface *iface);
137 static gboolean g_socket_initable_init (GInitable *initable,
138 GCancellable *cancellable,
141 static void g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface);
142 static gint g_socket_datagram_based_receive_messages (GDatagramBased *self,
143 GInputMessage *messages,
147 GCancellable *cancellable,
149 static gint g_socket_datagram_based_send_messages (GDatagramBased *self,
150 GOutputMessage *messages,
154 GCancellable *cancellable,
156 static GSource *g_socket_datagram_based_create_source (GDatagramBased *self,
157 GIOCondition condition,
158 GCancellable *cancellable);
159 static GIOCondition g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
160 GIOCondition condition);
161 static gboolean g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
162 GIOCondition condition,
164 GCancellable *cancellable,
167 static GSocketAddress *
168 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len);
171 g_socket_receive_message_with_timeout (GSocket *socket,
172 GSocketAddress **address,
173 GInputVector *vectors,
175 GSocketControlMessage ***messages,
179 GCancellable *cancellable,
182 g_socket_receive_messages_with_timeout (GSocket *socket,
183 GInputMessage *messages,
187 GCancellable *cancellable,
190 g_socket_send_message_with_timeout (GSocket *socket,
191 GSocketAddress *address,
192 GOutputVector *vectors,
194 GSocketControlMessage **messages,
198 GCancellable *cancellable,
201 g_socket_send_messages_with_timeout (GSocket *socket,
202 GOutputMessage *messages,
206 GCancellable *cancellable,
224 PROP_MULTICAST_LOOPBACK,
228 /* Size of the receiver cache for g_socket_receive_from() */
229 #define RECV_ADDR_CACHE_SIZE 8
231 struct _GSocketPrivate
233 GSocketFamily family;
235 GSocketProtocol protocol;
239 GError *construct_error;
240 GSocketAddress *remote_address;
245 guint connected_read : 1;
246 guint connected_write : 1;
249 guint connect_pending : 1;
255 GList *requested_conditions; /* list of requested GIOCondition * */
256 GMutex win32_source_lock;
260 GSocketAddress *addr;
261 struct sockaddr *native;
264 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
267 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
268 G_ADD_PRIVATE (GSocket)
269 g_networking_init ();
270 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
271 g_socket_initable_iface_init);
272 G_IMPLEMENT_INTERFACE (G_TYPE_DATAGRAM_BASED,
273 g_socket_datagram_based_iface_init));
276 get_socket_errno (void)
281 return WSAGetLastError ();
286 socket_io_error_from_errno (int err)
289 return g_io_error_from_win32_error (err);
291 return g_io_error_from_errno (err);
296 socket_strerror (int err)
299 return g_strerror (err);
304 msg = g_win32_error_message (err);
306 msg_ret = g_intern_string (msg);
313 /* Wrapper around g_set_error() to avoid doing excess work */
314 #define socket_set_error_lazy(err, errsv, fmt) \
316 GError **__err = (err); \
317 int __errsv = (errsv); \
321 int __code = socket_io_error_from_errno (__errsv); \
322 const char *__strerr = socket_strerror (__errsv); \
324 if (__code == G_IO_ERROR_WOULD_BLOCK) \
325 g_set_error_literal (__err, G_IO_ERROR, __code, __strerr); \
327 g_set_error (__err, G_IO_ERROR, __code, fmt, __strerr); \
332 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
334 _win32_unset_event_mask (GSocket *socket, int mask)
336 socket->priv->current_events &= ~mask;
337 socket->priv->current_errors &= ~mask;
340 #define win32_unset_event_mask(_socket, _mask)
343 /* Windows has broken prototypes... */
345 #define getsockopt(sockfd, level, optname, optval, optlen) \
346 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
347 #define setsockopt(sockfd, level, optname, optval, optlen) \
348 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
349 #define getsockname(sockfd, addr, addrlen) \
350 getsockname (sockfd, addr, (int *)addrlen)
351 #define getpeername(sockfd, addr, addrlen) \
352 getpeername (sockfd, addr, (int *)addrlen)
353 #define recv(sockfd, buf, len, flags) \
354 recv (sockfd, (gpointer)buf, len, flags)
358 check_socket (GSocket *socket,
361 if (!socket->priv->inited)
363 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
364 _("Invalid socket, not initialized"));
368 if (socket->priv->construct_error)
370 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
371 _("Invalid socket, initialization failed due to: %s"),
372 socket->priv->construct_error->message);
376 if (socket->priv->closed)
378 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
379 _("Socket is already closed"));
387 check_timeout (GSocket *socket,
390 if (socket->priv->timed_out)
392 socket->priv->timed_out = FALSE;
393 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
394 _("Socket I/O timed out"));
402 g_socket_details_from_fd (GSocket *socket)
404 struct sockaddr_storage address;
410 fd = socket->priv->fd;
411 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
413 errsv = get_socket_errno ();
420 socket->priv->type = G_SOCKET_TYPE_STREAM;
424 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
428 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
432 socket->priv->type = G_SOCKET_TYPE_INVALID;
436 addrlen = sizeof address;
437 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
439 errsv = get_socket_errno ();
445 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
446 sizeof address.ss_family <= addrlen);
447 family = address.ss_family;
451 /* On Solaris, this happens if the socket is not yet connected.
452 * But we can use SO_DOMAIN as a workaround there.
455 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
457 errsv = get_socket_errno ();
461 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
469 case G_SOCKET_FAMILY_IPV4:
470 case G_SOCKET_FAMILY_IPV6:
471 socket->priv->family = address.ss_family;
472 switch (socket->priv->type)
474 case G_SOCKET_TYPE_STREAM:
475 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
478 case G_SOCKET_TYPE_DATAGRAM:
479 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
482 case G_SOCKET_TYPE_SEQPACKET:
483 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
491 case G_SOCKET_FAMILY_UNIX:
492 socket->priv->family = G_SOCKET_FAMILY_UNIX;
493 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
497 socket->priv->family = G_SOCKET_FAMILY_INVALID;
501 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
503 addrlen = sizeof address;
504 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
506 socket->priv->connected_read = TRUE;
507 socket->priv->connected_write = TRUE;
511 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
513 socket->priv->keepalive = !!value;
517 /* Can't read, maybe not supported, assume FALSE */
518 socket->priv->keepalive = FALSE;
524 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
525 socket_io_error_from_errno (errsv),
526 _("creating GSocket from fd: %s"),
527 socket_strerror (errsv));
530 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
532 g_socket (gint domain,
540 fd = socket (domain, type | SOCK_CLOEXEC, protocol);
544 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
545 if (fd < 0 && (errno == EINVAL || errno == EPROTOTYPE))
547 fd = socket (domain, type, protocol);
551 int errsv = get_socket_errno ();
553 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
554 _("Unable to create socket: %s"), socket_strerror (errsv));
563 /* We always want to set close-on-exec to protect users. If you
564 need to so some weird inheritance to exec you can re-enable this
565 using lower level hacks with g_socket_get_fd(). */
566 flags = fcntl (fd, F_GETFD, 0);
568 (flags & FD_CLOEXEC) == 0)
571 fcntl (fd, F_SETFD, flags);
580 g_socket_create_socket (GSocketFamily family,
589 case G_SOCKET_TYPE_STREAM:
590 native_type = SOCK_STREAM;
593 case G_SOCKET_TYPE_DATAGRAM:
594 native_type = SOCK_DGRAM;
597 case G_SOCKET_TYPE_SEQPACKET:
598 native_type = SOCK_SEQPACKET;
602 g_assert_not_reached ();
607 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
608 _("Unable to create socket: %s"), _("Unknown family was specified"));
614 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
615 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
619 return g_socket (family, native_type, protocol, error);
623 g_socket_constructed (GObject *object)
625 GSocket *socket = G_SOCKET (object);
627 if (socket->priv->fd >= 0)
628 /* create socket->priv info from the fd */
629 g_socket_details_from_fd (socket);
632 /* create the fd from socket->priv info */
633 socket->priv->fd = g_socket_create_socket (socket->priv->family,
635 socket->priv->protocol,
636 &socket->priv->construct_error);
638 if (socket->priv->fd != -1)
641 GError *error = NULL;
646 /* Always use native nonblocking sockets, as Windows sets sockets to
647 * nonblocking automatically in certain operations. This way we make
648 * things work the same on all platforms.
651 if (!g_unix_set_fd_nonblocking (socket->priv->fd, TRUE, &error))
653 g_warning ("Error setting socket nonblocking: %s", error->message);
654 g_clear_error (&error);
659 if (ioctlsocket (socket->priv->fd, FIONBIO, &arg) == SOCKET_ERROR)
661 int errsv = get_socket_errno ();
662 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
667 /* See note about SIGPIPE below. */
668 g_socket_set_option (socket, SOL_SOCKET, SO_NOSIGPIPE, TRUE, NULL);
674 g_socket_get_property (GObject *object,
679 GSocket *socket = G_SOCKET (object);
680 GSocketAddress *address;
685 g_value_set_enum (value, socket->priv->family);
689 g_value_set_enum (value, socket->priv->type);
693 g_value_set_enum (value, socket->priv->protocol);
697 g_value_set_int (value, socket->priv->fd);
701 g_value_set_boolean (value, socket->priv->blocking);
704 case PROP_LISTEN_BACKLOG:
705 g_value_set_int (value, socket->priv->listen_backlog);
709 g_value_set_boolean (value, socket->priv->keepalive);
712 case PROP_LOCAL_ADDRESS:
713 address = g_socket_get_local_address (socket, NULL);
714 g_value_take_object (value, address);
717 case PROP_REMOTE_ADDRESS:
718 address = g_socket_get_remote_address (socket, NULL);
719 g_value_take_object (value, address);
723 g_value_set_uint (value, socket->priv->timeout);
727 g_value_set_uint (value, g_socket_get_ttl (socket));
731 g_value_set_boolean (value, g_socket_get_broadcast (socket));
734 case PROP_MULTICAST_LOOPBACK:
735 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
738 case PROP_MULTICAST_TTL:
739 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
743 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
748 g_socket_set_property (GObject *object,
753 GSocket *socket = G_SOCKET (object);
758 socket->priv->family = g_value_get_enum (value);
762 socket->priv->type = g_value_get_enum (value);
766 socket->priv->protocol = g_value_get_enum (value);
770 socket->priv->fd = g_value_get_int (value);
774 g_socket_set_blocking (socket, g_value_get_boolean (value));
777 case PROP_LISTEN_BACKLOG:
778 g_socket_set_listen_backlog (socket, g_value_get_int (value));
782 g_socket_set_keepalive (socket, g_value_get_boolean (value));
786 g_socket_set_timeout (socket, g_value_get_uint (value));
790 g_socket_set_ttl (socket, g_value_get_uint (value));
794 g_socket_set_broadcast (socket, g_value_get_boolean (value));
797 case PROP_MULTICAST_LOOPBACK:
798 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
801 case PROP_MULTICAST_TTL:
802 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
806 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
811 g_socket_finalize (GObject *object)
813 GSocket *socket = G_SOCKET (object);
816 g_clear_error (&socket->priv->construct_error);
818 if (socket->priv->fd != -1 &&
819 !socket->priv->closed)
820 g_socket_close (socket, NULL);
822 if (socket->priv->remote_address)
823 g_object_unref (socket->priv->remote_address);
826 if (socket->priv->event != WSA_INVALID_EVENT)
828 WSACloseEvent (socket->priv->event);
829 socket->priv->event = WSA_INVALID_EVENT;
832 g_assert (socket->priv->requested_conditions == NULL);
833 g_mutex_clear (&socket->priv->win32_source_lock);
836 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
838 if (socket->priv->recv_addr_cache[i].addr)
840 g_object_unref (socket->priv->recv_addr_cache[i].addr);
841 g_free (socket->priv->recv_addr_cache[i].native);
845 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
846 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
850 g_socket_class_init (GSocketClass *klass)
852 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
855 /* There is no portable, thread-safe way to avoid having the process
856 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
857 * forced to simply ignore the signal process-wide.
859 * Even if we ignore it though, gdb will still stop if the app
860 * receives a SIGPIPE, which can be confusing and annoying. So when
861 * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
862 * prevent the signal from occurring at all.
864 signal (SIGPIPE, SIG_IGN);
867 gobject_class->finalize = g_socket_finalize;
868 gobject_class->constructed = g_socket_constructed;
869 gobject_class->set_property = g_socket_set_property;
870 gobject_class->get_property = g_socket_get_property;
872 g_object_class_install_property (gobject_class, PROP_FAMILY,
873 g_param_spec_enum ("family",
875 P_("The sockets address family"),
876 G_TYPE_SOCKET_FAMILY,
877 G_SOCKET_FAMILY_INVALID,
878 G_PARAM_CONSTRUCT_ONLY |
880 G_PARAM_STATIC_STRINGS));
882 g_object_class_install_property (gobject_class, PROP_TYPE,
883 g_param_spec_enum ("type",
885 P_("The sockets type"),
887 G_SOCKET_TYPE_STREAM,
888 G_PARAM_CONSTRUCT_ONLY |
890 G_PARAM_STATIC_STRINGS));
892 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
893 g_param_spec_enum ("protocol",
894 P_("Socket protocol"),
895 P_("The id of the protocol to use, or -1 for unknown"),
896 G_TYPE_SOCKET_PROTOCOL,
897 G_SOCKET_PROTOCOL_UNKNOWN,
898 G_PARAM_CONSTRUCT_ONLY |
900 G_PARAM_STATIC_STRINGS));
902 g_object_class_install_property (gobject_class, PROP_FD,
903 g_param_spec_int ("fd",
904 P_("File descriptor"),
905 P_("The sockets file descriptor"),
909 G_PARAM_CONSTRUCT_ONLY |
911 G_PARAM_STATIC_STRINGS));
913 g_object_class_install_property (gobject_class, PROP_BLOCKING,
914 g_param_spec_boolean ("blocking",
916 P_("Whether or not I/O on this socket is blocking"),
919 G_PARAM_STATIC_STRINGS));
921 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
922 g_param_spec_int ("listen-backlog",
923 P_("Listen backlog"),
924 P_("Outstanding connections in the listen queue"),
929 G_PARAM_STATIC_STRINGS));
931 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
932 g_param_spec_boolean ("keepalive",
933 P_("Keep connection alive"),
934 P_("Keep connection alive by sending periodic pings"),
937 G_PARAM_STATIC_STRINGS));
939 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
940 g_param_spec_object ("local-address",
942 P_("The local address the socket is bound to"),
943 G_TYPE_SOCKET_ADDRESS,
945 G_PARAM_STATIC_STRINGS));
947 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
948 g_param_spec_object ("remote-address",
949 P_("Remote address"),
950 P_("The remote address the socket is connected to"),
951 G_TYPE_SOCKET_ADDRESS,
953 G_PARAM_STATIC_STRINGS));
958 * The timeout in seconds on socket I/O
962 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
963 g_param_spec_uint ("timeout",
965 P_("The timeout in seconds on socket I/O"),
970 G_PARAM_STATIC_STRINGS));
975 * Whether the socket should allow sending to broadcast addresses.
979 g_object_class_install_property (gobject_class, PROP_BROADCAST,
980 g_param_spec_boolean ("broadcast",
982 P_("Whether to allow sending to broadcast addresses"),
985 G_PARAM_STATIC_STRINGS));
990 * Time-to-live for outgoing unicast packets
994 g_object_class_install_property (gobject_class, PROP_TTL,
995 g_param_spec_uint ("ttl",
997 P_("Time-to-live of outgoing unicast packets"),
1000 G_PARAM_STATIC_STRINGS));
1003 * GSocket:multicast-loopback:
1005 * Whether outgoing multicast packets loop back to the local host.
1009 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
1010 g_param_spec_boolean ("multicast-loopback",
1011 P_("Multicast loopback"),
1012 P_("Whether outgoing multicast packets loop back to the local host"),
1015 G_PARAM_STATIC_STRINGS));
1018 * GSocket:multicast-ttl:
1020 * Time-to-live out outgoing multicast packets
1024 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
1025 g_param_spec_uint ("multicast-ttl",
1026 P_("Multicast TTL"),
1027 P_("Time-to-live of outgoing multicast packets"),
1030 G_PARAM_STATIC_STRINGS));
1034 g_socket_initable_iface_init (GInitableIface *iface)
1036 iface->init = g_socket_initable_init;
1040 g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface)
1042 iface->receive_messages = g_socket_datagram_based_receive_messages;
1043 iface->send_messages = g_socket_datagram_based_send_messages;
1044 iface->create_source = g_socket_datagram_based_create_source;
1045 iface->condition_check = g_socket_datagram_based_condition_check;
1046 iface->condition_wait = g_socket_datagram_based_condition_wait;
1050 g_socket_init (GSocket *socket)
1052 socket->priv = g_socket_get_instance_private (socket);
1054 socket->priv->fd = -1;
1055 socket->priv->blocking = TRUE;
1056 socket->priv->listen_backlog = 10;
1057 socket->priv->construct_error = NULL;
1059 socket->priv->event = WSA_INVALID_EVENT;
1060 g_mutex_init (&socket->priv->win32_source_lock);
1065 g_socket_initable_init (GInitable *initable,
1066 GCancellable *cancellable,
1071 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
1073 socket = G_SOCKET (initable);
1075 if (cancellable != NULL)
1077 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1078 _("Cancellable initialization not supported"));
1082 socket->priv->inited = TRUE;
1084 if (socket->priv->construct_error)
1087 *error = g_error_copy (socket->priv->construct_error);
1096 check_datagram_based (GDatagramBased *self,
1099 switch (g_socket_get_socket_type (G_SOCKET (self)))
1101 case G_SOCKET_TYPE_INVALID:
1102 case G_SOCKET_TYPE_STREAM:
1103 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1104 _("Cannot use datagram operations on a non-datagram "
1107 case G_SOCKET_TYPE_DATAGRAM:
1108 case G_SOCKET_TYPE_SEQPACKET:
1113 /* Due to us sharing #GSocketSource with the #GSocket implementation, it is
1114 * pretty tricky to split out #GSocket:timeout so that it does not affect
1115 * #GDatagramBased operations (but still affects #GSocket operations). It is
1116 * not worth that effort — just disallow it and require the user to specify
1117 * timeouts on a per-operation basis. */
1118 if (g_socket_get_timeout (G_SOCKET (self)) != 0)
1120 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1121 _("Cannot use datagram operations on a socket with a "
1130 g_socket_datagram_based_receive_messages (GDatagramBased *self,
1131 GInputMessage *messages,
1135 GCancellable *cancellable,
1138 if (!check_datagram_based (self, error))
1141 return g_socket_receive_messages_with_timeout (G_SOCKET (self), messages,
1142 num_messages, flags, timeout,
1143 cancellable, error);
1147 g_socket_datagram_based_send_messages (GDatagramBased *self,
1148 GOutputMessage *messages,
1152 GCancellable *cancellable,
1155 if (!check_datagram_based (self, error))
1158 return g_socket_send_messages_with_timeout (G_SOCKET (self), messages,
1159 num_messages, flags, timeout,
1160 cancellable, error);
1164 g_socket_datagram_based_create_source (GDatagramBased *self,
1165 GIOCondition condition,
1166 GCancellable *cancellable)
1168 if (!check_datagram_based (self, NULL))
1171 return g_socket_create_source (G_SOCKET (self), condition, cancellable);
1175 g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
1176 GIOCondition condition)
1178 if (!check_datagram_based (datagram_based, NULL))
1181 return g_socket_condition_check (G_SOCKET (datagram_based), condition);
1185 g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
1186 GIOCondition condition,
1188 GCancellable *cancellable,
1191 if (!check_datagram_based (datagram_based, error))
1194 return g_socket_condition_timed_wait (G_SOCKET (datagram_based), condition,
1195 timeout, cancellable, error);
1200 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1201 * @type: the socket type to use.
1202 * @protocol: the id of the protocol to use, or 0 for default.
1203 * @error: #GError for error reporting, or %NULL to ignore.
1205 * Creates a new #GSocket with the defined family, type and protocol.
1206 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1207 * for the family and type is used.
1209 * The @protocol is a family and type specific int that specifies what
1210 * kind of protocol to use. #GSocketProtocol lists several common ones.
1211 * Many families only support one protocol, and use 0 for this, others
1212 * support several and using 0 means to use the default protocol for
1213 * the family and type.
1215 * The protocol id is passed directly to the operating
1216 * system, so you can use protocols not listed in #GSocketProtocol if you
1217 * know the protocol number used for it.
1219 * Returns: a #GSocket or %NULL on error.
1220 * Free the returned object with g_object_unref().
1225 g_socket_new (GSocketFamily family,
1227 GSocketProtocol protocol,
1230 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1234 "protocol", protocol,
1239 * g_socket_new_from_fd:
1240 * @fd: a native socket file descriptor.
1241 * @error: #GError for error reporting, or %NULL to ignore.
1243 * Creates a new #GSocket from a native file descriptor
1244 * or winsock SOCKET handle.
1246 * This reads all the settings from the file descriptor so that
1247 * all properties should work. Note that the file descriptor
1248 * will be set to non-blocking mode, independent on the blocking
1249 * mode of the #GSocket.
1251 * On success, the returned #GSocket takes ownership of @fd. On failure, the
1252 * caller must close @fd themselves.
1254 * Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
1255 * descriptor. Instead, a GError will be set with code %G_IO_ERROR_FAILED
1257 * Returns: a #GSocket or %NULL on error.
1258 * Free the returned object with g_object_unref().
1263 g_socket_new_from_fd (gint fd,
1266 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1273 * g_socket_set_blocking:
1274 * @socket: a #GSocket.
1275 * @blocking: Whether to use blocking I/O or not.
1277 * Sets the blocking mode of the socket. In blocking mode
1278 * all operations (which don’t take an explicit blocking parameter) block until
1279 * they succeed or there is an error. In
1280 * non-blocking mode all functions return results immediately or
1281 * with a %G_IO_ERROR_WOULD_BLOCK error.
1283 * All sockets are created in blocking mode. However, note that the
1284 * platform level socket is always non-blocking, and blocking mode
1285 * is a GSocket level feature.
1290 g_socket_set_blocking (GSocket *socket,
1293 g_return_if_fail (G_IS_SOCKET (socket));
1295 blocking = !!blocking;
1297 if (socket->priv->blocking == blocking)
1300 socket->priv->blocking = blocking;
1301 g_object_notify (G_OBJECT (socket), "blocking");
1305 * g_socket_get_blocking:
1306 * @socket: a #GSocket.
1308 * Gets the blocking mode of the socket. For details on blocking I/O,
1309 * see g_socket_set_blocking().
1311 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1316 g_socket_get_blocking (GSocket *socket)
1318 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1320 return socket->priv->blocking;
1324 * g_socket_set_keepalive:
1325 * @socket: a #GSocket.
1326 * @keepalive: Value for the keepalive flag
1328 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1329 * this flag is set on a socket, the system will attempt to verify that the
1330 * remote socket endpoint is still present if a sufficiently long period of
1331 * time passes with no data being exchanged. If the system is unable to
1332 * verify the presence of the remote endpoint, it will automatically close
1335 * This option is only functional on certain kinds of sockets. (Notably,
1336 * %G_SOCKET_PROTOCOL_TCP sockets.)
1338 * The exact time between pings is system- and protocol-dependent, but will
1339 * normally be at least two hours. Most commonly, you would set this flag
1340 * on a server socket if you want to allow clients to remain idle for long
1341 * periods of time, but also want to ensure that connections are eventually
1342 * garbage-collected if clients crash or become unreachable.
1347 g_socket_set_keepalive (GSocket *socket,
1350 GError *error = NULL;
1352 g_return_if_fail (G_IS_SOCKET (socket));
1354 keepalive = !!keepalive;
1355 if (socket->priv->keepalive == keepalive)
1358 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1361 g_warning ("error setting keepalive: %s", error->message);
1362 g_error_free (error);
1366 socket->priv->keepalive = keepalive;
1367 g_object_notify (G_OBJECT (socket), "keepalive");
1371 * g_socket_get_keepalive:
1372 * @socket: a #GSocket.
1374 * Gets the keepalive mode of the socket. For details on this,
1375 * see g_socket_set_keepalive().
1377 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1382 g_socket_get_keepalive (GSocket *socket)
1384 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1386 return socket->priv->keepalive;
1390 * g_socket_get_listen_backlog:
1391 * @socket: a #GSocket.
1393 * Gets the listen backlog setting of the socket. For details on this,
1394 * see g_socket_set_listen_backlog().
1396 * Returns: the maximum number of pending connections.
1401 g_socket_get_listen_backlog (GSocket *socket)
1403 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1405 return socket->priv->listen_backlog;
1409 * g_socket_set_listen_backlog:
1410 * @socket: a #GSocket.
1411 * @backlog: the maximum number of pending connections.
1413 * Sets the maximum number of outstanding connections allowed
1414 * when listening on this socket. If more clients than this are
1415 * connecting to the socket and the application is not handling them
1416 * on time then the new connections will be refused.
1418 * Note that this must be called before g_socket_listen() and has no
1419 * effect if called after that.
1424 g_socket_set_listen_backlog (GSocket *socket,
1427 g_return_if_fail (G_IS_SOCKET (socket));
1428 g_return_if_fail (!socket->priv->listening);
1430 if (backlog != socket->priv->listen_backlog)
1432 socket->priv->listen_backlog = backlog;
1433 g_object_notify (G_OBJECT (socket), "listen-backlog");
1438 * g_socket_get_timeout:
1439 * @socket: a #GSocket.
1441 * Gets the timeout setting of the socket. For details on this, see
1442 * g_socket_set_timeout().
1444 * Returns: the timeout in seconds
1449 g_socket_get_timeout (GSocket *socket)
1451 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1453 return socket->priv->timeout;
1457 * g_socket_set_timeout:
1458 * @socket: a #GSocket.
1459 * @timeout: the timeout for @socket, in seconds, or 0 for none
1461 * Sets the time in seconds after which I/O operations on @socket will
1462 * time out if they have not yet completed.
1464 * On a blocking socket, this means that any blocking #GSocket
1465 * operation will time out after @timeout seconds of inactivity,
1466 * returning %G_IO_ERROR_TIMED_OUT.
1468 * On a non-blocking socket, calls to g_socket_condition_wait() will
1469 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1470 * created with g_socket_create_source() will trigger after
1471 * @timeout seconds of inactivity, with the requested condition
1472 * set, at which point calling g_socket_receive(), g_socket_send(),
1473 * g_socket_check_connect_result(), etc, will fail with
1474 * %G_IO_ERROR_TIMED_OUT.
1476 * If @timeout is 0 (the default), operations will never time out
1479 * Note that if an I/O operation is interrupted by a signal, this may
1480 * cause the timeout to be reset.
1485 g_socket_set_timeout (GSocket *socket,
1488 g_return_if_fail (G_IS_SOCKET (socket));
1490 if (timeout != socket->priv->timeout)
1492 socket->priv->timeout = timeout;
1493 g_object_notify (G_OBJECT (socket), "timeout");
1499 * @socket: a #GSocket.
1501 * Gets the unicast time-to-live setting on @socket; see
1502 * g_socket_set_ttl() for more details.
1504 * Returns: the time-to-live setting on @socket
1509 g_socket_get_ttl (GSocket *socket)
1511 GError *error = NULL;
1514 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1516 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1518 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1521 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1523 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1527 g_return_val_if_reached (0);
1531 g_warning ("error getting unicast ttl: %s", error->message);
1532 g_error_free (error);
1541 * @socket: a #GSocket.
1542 * @ttl: the time-to-live value for all unicast packets on @socket
1544 * Sets the time-to-live for outgoing unicast packets on @socket.
1545 * By default the platform-specific default value is used.
1550 g_socket_set_ttl (GSocket *socket,
1553 GError *error = NULL;
1555 g_return_if_fail (G_IS_SOCKET (socket));
1557 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1559 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1562 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1564 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1566 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1570 g_return_if_reached ();
1574 g_warning ("error setting unicast ttl: %s", error->message);
1575 g_error_free (error);
1579 g_object_notify (G_OBJECT (socket), "ttl");
1583 * g_socket_get_broadcast:
1584 * @socket: a #GSocket.
1586 * Gets the broadcast setting on @socket; if %TRUE,
1587 * it is possible to send packets to broadcast
1590 * Returns: the broadcast setting on @socket
1595 g_socket_get_broadcast (GSocket *socket)
1597 GError *error = NULL;
1600 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1602 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1605 g_warning ("error getting broadcast: %s", error->message);
1606 g_error_free (error);
1614 * g_socket_set_broadcast:
1615 * @socket: a #GSocket.
1616 * @broadcast: whether @socket should allow sending to broadcast
1619 * Sets whether @socket should allow sending to broadcast addresses.
1620 * This is %FALSE by default.
1625 g_socket_set_broadcast (GSocket *socket,
1628 GError *error = NULL;
1630 g_return_if_fail (G_IS_SOCKET (socket));
1632 broadcast = !!broadcast;
1634 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1637 g_warning ("error setting broadcast: %s", error->message);
1638 g_error_free (error);
1642 g_object_notify (G_OBJECT (socket), "broadcast");
1646 * g_socket_get_multicast_loopback:
1647 * @socket: a #GSocket.
1649 * Gets the multicast loopback setting on @socket; if %TRUE (the
1650 * default), outgoing multicast packets will be looped back to
1651 * multicast listeners on the same host.
1653 * Returns: the multicast loopback setting on @socket
1658 g_socket_get_multicast_loopback (GSocket *socket)
1660 GError *error = NULL;
1663 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1665 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1667 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1670 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1672 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1676 g_return_val_if_reached (FALSE);
1680 g_warning ("error getting multicast loopback: %s", error->message);
1681 g_error_free (error);
1689 * g_socket_set_multicast_loopback:
1690 * @socket: a #GSocket.
1691 * @loopback: whether @socket should receive messages sent to its
1692 * multicast groups from the local host
1694 * Sets whether outgoing multicast packets will be received by sockets
1695 * listening on that multicast address on the same host. This is %TRUE
1701 g_socket_set_multicast_loopback (GSocket *socket,
1704 GError *error = NULL;
1706 g_return_if_fail (G_IS_SOCKET (socket));
1708 loopback = !!loopback;
1710 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1712 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1715 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1717 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1719 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1723 g_return_if_reached ();
1727 g_warning ("error setting multicast loopback: %s", error->message);
1728 g_error_free (error);
1732 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1736 * g_socket_get_multicast_ttl:
1737 * @socket: a #GSocket.
1739 * Gets the multicast time-to-live setting on @socket; see
1740 * g_socket_set_multicast_ttl() for more details.
1742 * Returns: the multicast time-to-live setting on @socket
1747 g_socket_get_multicast_ttl (GSocket *socket)
1749 GError *error = NULL;
1752 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1754 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1756 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1759 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1761 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1765 g_return_val_if_reached (FALSE);
1769 g_warning ("error getting multicast ttl: %s", error->message);
1770 g_error_free (error);
1778 * g_socket_set_multicast_ttl:
1779 * @socket: a #GSocket.
1780 * @ttl: the time-to-live value for all multicast datagrams on @socket
1782 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1783 * By default, this is 1, meaning that multicast packets will not leave
1784 * the local network.
1789 g_socket_set_multicast_ttl (GSocket *socket,
1792 GError *error = NULL;
1794 g_return_if_fail (G_IS_SOCKET (socket));
1796 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1798 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1801 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1803 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1805 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1809 g_return_if_reached ();
1813 g_warning ("error setting multicast ttl: %s", error->message);
1814 g_error_free (error);
1818 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1822 * g_socket_get_family:
1823 * @socket: a #GSocket.
1825 * Gets the socket family of the socket.
1827 * Returns: a #GSocketFamily
1832 g_socket_get_family (GSocket *socket)
1834 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1836 return socket->priv->family;
1840 * g_socket_get_socket_type:
1841 * @socket: a #GSocket.
1843 * Gets the socket type of the socket.
1845 * Returns: a #GSocketType
1850 g_socket_get_socket_type (GSocket *socket)
1852 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1854 return socket->priv->type;
1858 * g_socket_get_protocol:
1859 * @socket: a #GSocket.
1861 * Gets the socket protocol id the socket was created with.
1862 * In case the protocol is unknown, -1 is returned.
1864 * Returns: a protocol id, or -1 if unknown
1869 g_socket_get_protocol (GSocket *socket)
1871 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1873 return socket->priv->protocol;
1878 * @socket: a #GSocket.
1880 * Returns the underlying OS socket object. On unix this
1881 * is a socket file descriptor, and on Windows this is
1882 * a Winsock2 SOCKET handle. This may be useful for
1883 * doing platform specific or otherwise unusual operations
1886 * Returns: the file descriptor of the socket.
1891 g_socket_get_fd (GSocket *socket)
1893 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1895 return socket->priv->fd;
1899 * g_socket_get_local_address:
1900 * @socket: a #GSocket.
1901 * @error: #GError for error reporting, or %NULL to ignore.
1903 * Try to get the local address of a bound socket. This is only
1904 * useful if the socket has been bound to a local address,
1905 * either explicitly or implicitly when connecting.
1907 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1908 * Free the returned object with g_object_unref().
1913 g_socket_get_local_address (GSocket *socket,
1916 struct sockaddr_storage buffer;
1917 guint len = sizeof (buffer);
1919 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1921 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1923 int errsv = get_socket_errno ();
1924 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1925 _("could not get local address: %s"), socket_strerror (errsv));
1929 return g_socket_address_new_from_native (&buffer, len);
1933 * g_socket_get_remote_address:
1934 * @socket: a #GSocket.
1935 * @error: #GError for error reporting, or %NULL to ignore.
1937 * Try to get the remove address of a connected socket. This is only
1938 * useful for connection oriented sockets that have been connected.
1940 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1941 * Free the returned object with g_object_unref().
1946 g_socket_get_remote_address (GSocket *socket,
1949 struct sockaddr_storage buffer;
1950 guint len = sizeof (buffer);
1952 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1954 if (socket->priv->connect_pending)
1956 if (!g_socket_check_connect_result (socket, error))
1959 socket->priv->connect_pending = FALSE;
1962 if (!socket->priv->remote_address)
1964 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1966 int errsv = get_socket_errno ();
1967 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1968 _("could not get remote address: %s"), socket_strerror (errsv));
1972 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1975 return g_object_ref (socket->priv->remote_address);
1979 * g_socket_is_connected:
1980 * @socket: a #GSocket.
1982 * Check whether the socket is connected. This is only useful for
1983 * connection-oriented sockets.
1985 * If using g_socket_shutdown(), this function will return %TRUE until the
1986 * socket has been shut down for reading and writing. If you do a non-blocking
1987 * connect, this function will not return %TRUE until after you call
1988 * g_socket_check_connect_result().
1990 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1995 g_socket_is_connected (GSocket *socket)
1997 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1999 return (socket->priv->connected_read || socket->priv->connected_write);
2004 * @socket: a #GSocket.
2005 * @error: #GError for error reporting, or %NULL to ignore.
2007 * Marks the socket as a server socket, i.e. a socket that is used
2008 * to accept incoming requests using g_socket_accept().
2010 * Before calling this the socket must be bound to a local address using
2013 * To set the maximum amount of outstanding clients, use
2014 * g_socket_set_listen_backlog().
2016 * Returns: %TRUE on success, %FALSE on error.
2021 g_socket_listen (GSocket *socket,
2024 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2026 if (!check_socket (socket, error))
2029 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
2031 int errsv = get_socket_errno ();
2033 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2034 _("could not listen: %s"), socket_strerror (errsv));
2038 socket->priv->listening = TRUE;
2045 * @socket: a #GSocket.
2046 * @address: a #GSocketAddress specifying the local address.
2047 * @allow_reuse: whether to allow reusing this address
2048 * @error: #GError for error reporting, or %NULL to ignore.
2050 * When a socket is created it is attached to an address family, but it
2051 * doesn't have an address in this family. g_socket_bind() assigns the
2052 * address (sometimes called name) of the socket.
2054 * It is generally required to bind to a local address before you can
2055 * receive connections. (See g_socket_listen() and g_socket_accept() ).
2056 * In certain situations, you may also want to bind a socket that will be
2057 * used to initiate connections, though this is not normally required.
2059 * If @socket is a TCP socket, then @allow_reuse controls the setting
2060 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
2061 * server sockets (sockets that you will eventually call
2062 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
2063 * set this flag on a server socket may cause g_socket_bind() to return
2064 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
2065 * immediately restarted.)
2067 * If @socket is a UDP socket, then @allow_reuse determines whether or
2068 * not other UDP sockets can be bound to the same address at the same
2069 * time. In particular, you can have several UDP sockets bound to the
2070 * same address, and they will all receive all of the multicast and
2071 * broadcast packets sent to that address. (The behavior of unicast
2072 * UDP packets to an address with multiple listeners is not defined.)
2074 * Returns: %TRUE on success, %FALSE on error.
2079 g_socket_bind (GSocket *socket,
2080 GSocketAddress *address,
2081 gboolean reuse_address,
2084 struct sockaddr_storage addr;
2085 gboolean so_reuseaddr;
2087 gboolean so_reuseport;
2090 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2092 if (!check_socket (socket, error))
2095 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2098 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
2099 * sockets, but has nasty side effects we don't want for TCP
2102 * On other platforms, we set SO_REUSEPORT, if it exists, for
2103 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
2104 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
2105 * the desired semantics on UDP (as it does on Linux, although
2106 * Linux has SO_REUSEPORT too as of 3.9).
2110 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2112 so_reuseaddr = !!reuse_address;
2116 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2119 /* Ignore errors here, the only likely error is "not supported", and
2120 * this is a "best effort" thing mainly.
2122 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
2124 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
2127 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
2128 g_socket_address_get_native_size (address)) < 0)
2130 int errsv = get_socket_errno ();
2132 G_IO_ERROR, socket_io_error_from_errno (errsv),
2133 _("Error binding to address: %s"), socket_strerror (errsv));
2140 #if !defined(HAVE_IF_NAMETOINDEX) && defined(G_OS_WIN32)
2142 if_nametoindex (const gchar *iface)
2144 PIP_ADAPTER_ADDRESSES addresses = NULL, p;
2145 gulong addresses_len = 0;
2149 if (ws2funcs.pIfNameToIndex != NULL)
2150 return ws2funcs.pIfNameToIndex (iface);
2152 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, NULL, &addresses_len);
2153 if (res != NO_ERROR && res != ERROR_BUFFER_OVERFLOW)
2155 if (res == ERROR_NO_DATA)
2162 addresses = g_malloc (addresses_len);
2163 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, addresses, &addresses_len);
2165 if (res != NO_ERROR)
2168 if (res == ERROR_NO_DATA)
2178 if (strcmp (p->AdapterName, iface) == 0)
2194 #define HAVE_IF_NAMETOINDEX 1
2198 g_socket_multicast_group_operation (GSocket *socket,
2199 GInetAddress *group,
2200 gboolean source_specific,
2202 gboolean join_group,
2205 const guint8 *native_addr;
2206 gint optname, result;
2208 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2209 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2210 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2212 if (!check_socket (socket, error))
2215 native_addr = g_inet_address_to_bytes (group);
2216 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2218 #ifdef HAVE_IP_MREQN
2219 struct ip_mreqn mc_req;
2221 struct ip_mreq mc_req;
2224 memset (&mc_req, 0, sizeof (mc_req));
2225 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2227 #ifdef HAVE_IP_MREQN
2229 mc_req.imr_ifindex = if_nametoindex (iface);
2231 mc_req.imr_ifindex = 0; /* Pick any. */
2232 #elif defined(G_OS_WIN32)
2234 mc_req.imr_interface.s_addr = g_htonl (if_nametoindex (iface));
2236 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2238 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2241 if (source_specific)
2243 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2244 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2246 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2248 _("Error joining multicast group: %s") :
2249 _("Error leaving multicast group: %s"),
2250 _("No support for source-specific multicast"));
2255 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2256 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2257 &mc_req, sizeof (mc_req));
2259 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2261 struct ipv6_mreq mc_req_ipv6;
2263 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2264 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2265 #ifdef HAVE_IF_NAMETOINDEX
2267 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2270 mc_req_ipv6.ipv6mr_interface = 0;
2272 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2273 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2274 &mc_req_ipv6, sizeof (mc_req_ipv6));
2277 g_return_val_if_reached (FALSE);
2281 int errsv = get_socket_errno ();
2283 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2285 _("Error joining multicast group: %s") :
2286 _("Error leaving multicast group: %s"),
2287 socket_strerror (errsv));
2295 * g_socket_join_multicast_group:
2296 * @socket: a #GSocket.
2297 * @group: a #GInetAddress specifying the group address to join.
2298 * @iface: (allow-none): Name of the interface to use, or %NULL
2299 * @source_specific: %TRUE if source-specific multicast should be used
2300 * @error: #GError for error reporting, or %NULL to ignore.
2302 * Registers @socket to receive multicast messages sent to @group.
2303 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2304 * been bound to an appropriate interface and port with
2307 * If @iface is %NULL, the system will automatically pick an interface
2308 * to bind to based on @group.
2310 * If @source_specific is %TRUE, source-specific multicast as defined
2311 * in RFC 4604 is used. Note that on older platforms this may fail
2312 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2314 * Returns: %TRUE on success, %FALSE on error.
2319 g_socket_join_multicast_group (GSocket *socket,
2320 GInetAddress *group,
2321 gboolean source_specific,
2325 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2329 * g_socket_leave_multicast_group:
2330 * @socket: a #GSocket.
2331 * @group: a #GInetAddress specifying the group address to leave.
2332 * @iface: (allow-none): Interface used
2333 * @source_specific: %TRUE if source-specific multicast was used
2334 * @error: #GError for error reporting, or %NULL to ignore.
2336 * Removes @socket from the multicast group defined by @group, @iface,
2337 * and @source_specific (which must all have the same values they had
2338 * when you joined the group).
2340 * @socket remains bound to its address and port, and can still receive
2341 * unicast messages after calling this.
2343 * Returns: %TRUE on success, %FALSE on error.
2348 g_socket_leave_multicast_group (GSocket *socket,
2349 GInetAddress *group,
2350 gboolean source_specific,
2354 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2358 * g_socket_speaks_ipv4:
2359 * @socket: a #GSocket
2361 * Checks if a socket is capable of speaking IPv4.
2363 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2364 * and under some combinations of circumstances IPv6 sockets are also
2365 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2368 * No other types of sockets are currently considered as being capable
2371 * Returns: %TRUE if this socket can be used with IPv4.
2376 g_socket_speaks_ipv4 (GSocket *socket)
2378 switch (socket->priv->family)
2380 case G_SOCKET_FAMILY_IPV4:
2383 case G_SOCKET_FAMILY_IPV6:
2384 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2388 if (!g_socket_get_option (socket,
2389 IPPROTO_IPV6, IPV6_V6ONLY,
2406 * @socket: a #GSocket.
2407 * @cancellable: (allow-none): a %GCancellable or %NULL
2408 * @error: #GError for error reporting, or %NULL to ignore.
2410 * Accept incoming connections on a connection-based socket. This removes
2411 * the first outstanding connection request from the listening socket and
2412 * creates a #GSocket object for it.
2414 * The @socket must be bound to a local address with g_socket_bind() and
2415 * must be listening for incoming connections (g_socket_listen()).
2417 * If there are no outstanding connections then the operation will block
2418 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2419 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2421 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2422 * Free the returned object with g_object_unref().
2427 g_socket_accept (GSocket *socket,
2428 GCancellable *cancellable,
2431 GSocket *new_socket;
2434 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2436 if (!check_socket (socket, error))
2439 if (!check_timeout (socket, error))
2444 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2446 int errsv = get_socket_errno ();
2451 #ifdef WSAEWOULDBLOCK
2452 if (errsv == WSAEWOULDBLOCK)
2454 if (errsv == EWOULDBLOCK ||
2458 win32_unset_event_mask (socket, FD_ACCEPT);
2460 if (socket->priv->blocking)
2462 if (!g_socket_condition_wait (socket,
2463 G_IO_IN, cancellable, error))
2470 socket_set_error_lazy (error, errsv, _("Error accepting connection: %s"));
2476 win32_unset_event_mask (socket, FD_ACCEPT);
2480 /* The socket inherits the accepting sockets event mask and even object,
2481 we need to remove that */
2482 WSAEventSelect (ret, NULL, 0);
2488 /* We always want to set close-on-exec to protect users. If you
2489 need to so some weird inheritance to exec you can re-enable this
2490 using lower level hacks with g_socket_get_fd(). */
2491 flags = fcntl (ret, F_GETFD, 0);
2493 (flags & FD_CLOEXEC) == 0)
2495 flags |= FD_CLOEXEC;
2496 fcntl (ret, F_SETFD, flags);
2501 new_socket = g_socket_new_from_fd (ret, error);
2502 if (new_socket == NULL)
2511 new_socket->priv->protocol = socket->priv->protocol;
2518 * @socket: a #GSocket.
2519 * @address: a #GSocketAddress specifying the remote address.
2520 * @cancellable: (allow-none): a %GCancellable or %NULL
2521 * @error: #GError for error reporting, or %NULL to ignore.
2523 * Connect the socket to the specified remote address.
2525 * For connection oriented socket this generally means we attempt to make
2526 * a connection to the @address. For a connection-less socket it sets
2527 * the default address for g_socket_send() and discards all incoming datagrams
2528 * from other sources.
2530 * Generally connection oriented sockets can only connect once, but
2531 * connection-less sockets can connect multiple times to change the
2534 * If the connect call needs to do network I/O it will block, unless
2535 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2536 * and the user can be notified of the connection finishing by waiting
2537 * for the G_IO_OUT condition. The result of the connection must then be
2538 * checked with g_socket_check_connect_result().
2540 * Returns: %TRUE if connected, %FALSE on error.
2545 g_socket_connect (GSocket *socket,
2546 GSocketAddress *address,
2547 GCancellable *cancellable,
2550 struct sockaddr_storage buffer;
2552 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2554 if (!check_socket (socket, error))
2557 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2560 if (socket->priv->remote_address)
2561 g_object_unref (socket->priv->remote_address);
2562 socket->priv->remote_address = g_object_ref (address);
2566 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2567 g_socket_address_get_native_size (address)) < 0)
2569 int errsv = get_socket_errno ();
2575 if (errsv == EINPROGRESS)
2577 if (errsv == WSAEWOULDBLOCK)
2580 win32_unset_event_mask (socket, FD_CONNECT);
2582 if (socket->priv->blocking)
2584 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2586 if (g_socket_check_connect_result (socket, error))
2592 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2593 _("Connection in progress"));
2594 socket->priv->connect_pending = TRUE;
2598 g_set_error_literal (error, G_IO_ERROR,
2599 socket_io_error_from_errno (errsv),
2600 socket_strerror (errsv));
2607 win32_unset_event_mask (socket, FD_CONNECT);
2609 socket->priv->connected_read = TRUE;
2610 socket->priv->connected_write = TRUE;
2616 * g_socket_check_connect_result:
2617 * @socket: a #GSocket
2618 * @error: #GError for error reporting, or %NULL to ignore.
2620 * Checks and resets the pending connect error for the socket.
2621 * This is used to check for errors when g_socket_connect() is
2622 * used in non-blocking mode.
2624 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2629 g_socket_check_connect_result (GSocket *socket,
2634 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2636 if (!check_socket (socket, error))
2639 if (!check_timeout (socket, error))
2642 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
2644 g_prefix_error (error, _("Unable to get pending error: "));
2650 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2651 socket_strerror (value));
2652 if (socket->priv->remote_address)
2654 g_object_unref (socket->priv->remote_address);
2655 socket->priv->remote_address = NULL;
2660 socket->priv->connected_read = TRUE;
2661 socket->priv->connected_write = TRUE;
2667 * g_socket_get_available_bytes:
2668 * @socket: a #GSocket
2670 * Get the amount of data pending in the OS input buffer, without blocking.
2672 * If @socket is a UDP or SCTP socket, this will return the size of
2673 * just the next packet, even if additional packets are buffered after
2676 * Note that on Windows, this function is rather inefficient in the
2677 * UDP case, and so if you know any plausible upper bound on the size
2678 * of the incoming packet, it is better to just do a
2679 * g_socket_receive() with a buffer of that size, rather than calling
2680 * g_socket_get_available_bytes() first and then doing a receive of
2681 * exactly the right size.
2683 * Returns: the number of bytes that can be read from the socket
2684 * without blocking or truncating, or -1 on error.
2689 g_socket_get_available_bytes (GSocket *socket)
2692 const gint bufsize = 64 * 1024;
2693 static guchar *buf = NULL;
2699 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2701 #if defined (SO_NREAD)
2702 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
2704 #elif !defined (G_OS_WIN32)
2705 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2708 if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
2710 if (G_UNLIKELY (g_once_init_enter (&buf)))
2711 g_once_init_leave (&buf, g_malloc (bufsize));
2713 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
2714 if (avail == -1 && get_socket_errno () == WSAEWOULDBLOCK)
2719 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
2727 /* Block on a timed wait for @condition until (@start_time + @timeout).
2728 * Return %G_IO_ERROR_TIMED_OUT if the timeout is reached; otherwise %TRUE.
2731 block_on_timeout (GSocket *socket,
2732 GIOCondition condition,
2735 GCancellable *cancellable,
2738 gint64 wait_timeout = -1;
2740 g_return_val_if_fail (timeout != 0, TRUE);
2742 /* check if we've timed out or how much time to wait at most */
2745 gint64 elapsed = g_get_monotonic_time () - start_time;
2747 if (elapsed >= timeout)
2749 g_set_error_literal (error,
2750 G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2751 _("Socket I/O timed out"));
2755 wait_timeout = timeout - elapsed;
2758 return g_socket_condition_timed_wait (socket, condition, wait_timeout,
2759 cancellable, error);
2763 g_socket_receive_with_timeout (GSocket *socket,
2767 GCancellable *cancellable,
2773 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2775 start_time = g_get_monotonic_time ();
2777 if (!check_socket (socket, error))
2780 if (!check_timeout (socket, error))
2783 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2788 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2790 int errsv = get_socket_errno ();
2795 #ifdef WSAEWOULDBLOCK
2796 if (errsv == WSAEWOULDBLOCK)
2798 if (errsv == EWOULDBLOCK ||
2802 win32_unset_event_mask (socket, FD_READ);
2806 if (!block_on_timeout (socket, G_IO_IN, timeout, start_time,
2807 cancellable, error))
2814 win32_unset_event_mask (socket, FD_READ);
2816 socket_set_error_lazy (error, errsv, _("Error receiving data: %s"));
2820 win32_unset_event_mask (socket, FD_READ);
2830 * @socket: a #GSocket
2831 * @buffer: (array length=size) (element-type guint8): a buffer to
2832 * read data into (which should be at least @size bytes long).
2833 * @size: the number of bytes you want to read from the socket
2834 * @cancellable: (allow-none): a %GCancellable or %NULL
2835 * @error: #GError for error reporting, or %NULL to ignore.
2837 * Receive data (up to @size bytes) from a socket. This is mainly used by
2838 * connection-oriented sockets; it is identical to g_socket_receive_from()
2839 * with @address set to %NULL.
2841 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2842 * g_socket_receive() will always read either 0 or 1 complete messages from
2843 * the socket. If the received message is too large to fit in @buffer, then
2844 * the data beyond @size bytes will be discarded, without any explicit
2845 * indication that this has occurred.
2847 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2848 * number of bytes, up to @size. If more than @size bytes have been
2849 * received, the additional data will be returned in future calls to
2850 * g_socket_receive().
2852 * If the socket is in blocking mode the call will block until there
2853 * is some data to receive, the connection is closed, or there is an
2854 * error. If there is no data available and the socket is in
2855 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2856 * returned. To be notified when data is available, wait for the
2857 * %G_IO_IN condition.
2859 * On error -1 is returned and @error is set accordingly.
2861 * Returns: Number of bytes read, or 0 if the connection was closed by
2862 * the peer, or -1 on error
2867 g_socket_receive (GSocket *socket,
2870 GCancellable *cancellable,
2873 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
2874 socket->priv->blocking ? -1 : 0,
2875 cancellable, error);
2879 * g_socket_receive_with_blocking:
2880 * @socket: a #GSocket
2881 * @buffer: (array length=size) (element-type guint8): a buffer to
2882 * read data into (which should be at least @size bytes long).
2883 * @size: the number of bytes you want to read from the socket
2884 * @blocking: whether to do blocking or non-blocking I/O
2885 * @cancellable: (allow-none): a %GCancellable or %NULL
2886 * @error: #GError for error reporting, or %NULL to ignore.
2888 * This behaves exactly the same as g_socket_receive(), except that
2889 * the choice of blocking or non-blocking behavior is determined by
2890 * the @blocking argument rather than by @socket's properties.
2892 * Returns: Number of bytes read, or 0 if the connection was closed by
2893 * the peer, or -1 on error
2898 g_socket_receive_with_blocking (GSocket *socket,
2902 GCancellable *cancellable,
2905 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
2906 blocking ? -1 : 0, cancellable, error);
2910 * g_socket_receive_from:
2911 * @socket: a #GSocket
2912 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2914 * @buffer: (array length=size) (element-type guint8): a buffer to
2915 * read data into (which should be at least @size bytes long).
2916 * @size: the number of bytes you want to read from the socket
2917 * @cancellable: (allow-none): a %GCancellable or %NULL
2918 * @error: #GError for error reporting, or %NULL to ignore.
2920 * Receive data (up to @size bytes) from a socket.
2922 * If @address is non-%NULL then @address will be set equal to the
2923 * source address of the received packet.
2924 * @address is owned by the caller.
2926 * See g_socket_receive() for additional information.
2928 * Returns: Number of bytes read, or 0 if the connection was closed by
2929 * the peer, or -1 on error
2934 g_socket_receive_from (GSocket *socket,
2935 GSocketAddress **address,
2938 GCancellable *cancellable,
2946 return g_socket_receive_message (socket,
2954 /* See the comment about SIGPIPE above. */
2956 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2958 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2962 g_socket_send_with_timeout (GSocket *socket,
2963 const guint8 *buffer,
2966 GCancellable *cancellable,
2972 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2974 start_time = g_get_monotonic_time ();
2976 if (!check_socket (socket, error))
2979 if (!check_timeout (socket, error))
2982 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2987 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2989 int errsv = get_socket_errno ();
2994 #ifdef WSAEWOULDBLOCK
2995 if (errsv == WSAEWOULDBLOCK)
2997 if (errsv == EWOULDBLOCK ||
3001 win32_unset_event_mask (socket, FD_WRITE);
3005 if (!block_on_timeout (socket, G_IO_OUT, timeout, start_time,
3006 cancellable, error))
3013 socket_set_error_lazy (error, errsv, _("Error sending data: %s"));
3024 * @socket: a #GSocket
3025 * @buffer: (array length=size) (element-type guint8): the buffer
3026 * containing the data to send.
3027 * @size: the number of bytes to send
3028 * @cancellable: (allow-none): a %GCancellable or %NULL
3029 * @error: #GError for error reporting, or %NULL to ignore.
3031 * Tries to send @size bytes from @buffer on the socket. This is
3032 * mainly used by connection-oriented sockets; it is identical to
3033 * g_socket_send_to() with @address set to %NULL.
3035 * If the socket is in blocking mode the call will block until there is
3036 * space for the data in the socket queue. If there is no space available
3037 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3038 * will be returned. To be notified when space is available, wait for the
3039 * %G_IO_OUT condition. Note though that you may still receive
3040 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3041 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3042 * very common due to the way the underlying APIs work.)
3044 * On error -1 is returned and @error is set accordingly.
3046 * Returns: Number of bytes written (which may be less than @size), or -1
3052 g_socket_send (GSocket *socket,
3053 const gchar *buffer,
3055 GCancellable *cancellable,
3058 return g_socket_send_with_blocking (socket, buffer, size,
3059 socket->priv->blocking,
3060 cancellable, error);
3064 * g_socket_send_with_blocking:
3065 * @socket: a #GSocket
3066 * @buffer: (array length=size) (element-type guint8): the buffer
3067 * containing the data to send.
3068 * @size: the number of bytes to send
3069 * @blocking: whether to do blocking or non-blocking I/O
3070 * @cancellable: (allow-none): a %GCancellable or %NULL
3071 * @error: #GError for error reporting, or %NULL to ignore.
3073 * This behaves exactly the same as g_socket_send(), except that
3074 * the choice of blocking or non-blocking behavior is determined by
3075 * the @blocking argument rather than by @socket's properties.
3077 * Returns: Number of bytes written (which may be less than @size), or -1
3083 g_socket_send_with_blocking (GSocket *socket,
3084 const gchar *buffer,
3087 GCancellable *cancellable,
3090 return g_socket_send_with_timeout (socket, (const guint8 *) buffer, size,
3091 blocking ? -1 : 0, cancellable, error);
3096 * @socket: a #GSocket
3097 * @address: (allow-none): a #GSocketAddress, or %NULL
3098 * @buffer: (array length=size) (element-type guint8): the buffer
3099 * containing the data to send.
3100 * @size: the number of bytes to send
3101 * @cancellable: (allow-none): a %GCancellable or %NULL
3102 * @error: #GError for error reporting, or %NULL to ignore.
3104 * Tries to send @size bytes from @buffer to @address. If @address is
3105 * %NULL then the message is sent to the default receiver (set by
3106 * g_socket_connect()).
3108 * See g_socket_send() for additional information.
3110 * Returns: Number of bytes written (which may be less than @size), or -1
3116 g_socket_send_to (GSocket *socket,
3117 GSocketAddress *address,
3118 const gchar *buffer,
3120 GCancellable *cancellable,
3128 return g_socket_send_message (socket,
3138 * g_socket_shutdown:
3139 * @socket: a #GSocket
3140 * @shutdown_read: whether to shut down the read side
3141 * @shutdown_write: whether to shut down the write side
3142 * @error: #GError for error reporting, or %NULL to ignore.
3144 * Shut down part or all of a full-duplex connection.
3146 * If @shutdown_read is %TRUE then the receiving side of the connection
3147 * is shut down, and further reading is disallowed.
3149 * If @shutdown_write is %TRUE then the sending side of the connection
3150 * is shut down, and further writing is disallowed.
3152 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
3154 * One example where it is useful to shut down only one side of a connection is
3155 * graceful disconnect for TCP connections where you close the sending side,
3156 * then wait for the other side to close the connection, thus ensuring that the
3157 * other side saw all sent data.
3159 * Returns: %TRUE on success, %FALSE on error
3164 g_socket_shutdown (GSocket *socket,
3165 gboolean shutdown_read,
3166 gboolean shutdown_write,
3171 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3173 if (!check_socket (socket, error))
3177 if (!shutdown_read && !shutdown_write)
3181 if (shutdown_read && shutdown_write)
3183 else if (shutdown_read)
3188 if (shutdown_read && shutdown_write)
3190 else if (shutdown_read)
3196 if (shutdown (socket->priv->fd, how) != 0)
3198 int errsv = get_socket_errno ();
3199 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
3200 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
3205 socket->priv->connected_read = FALSE;
3207 socket->priv->connected_write = FALSE;
3214 * @socket: a #GSocket
3215 * @error: #GError for error reporting, or %NULL to ignore.
3217 * Closes the socket, shutting down any active connection.
3219 * Closing a socket does not wait for all outstanding I/O operations
3220 * to finish, so the caller should not rely on them to be guaranteed
3221 * to complete even if the close returns with no error.
3223 * Once the socket is closed, all other operations will return
3224 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
3227 * Sockets will be automatically closed when the last reference
3228 * is dropped, but you might want to call this function to make sure
3229 * resources are released as early as possible.
3231 * Beware that due to the way that TCP works, it is possible for
3232 * recently-sent data to be lost if either you close a socket while the
3233 * %G_IO_IN condition is set, or else if the remote connection tries to
3234 * send something to you after you close the socket but before it has
3235 * finished reading all of the data you sent. There is no easy generic
3236 * way to avoid this problem; the easiest fix is to design the network
3237 * protocol such that the client will never send data "out of turn".
3238 * Another solution is for the server to half-close the connection by
3239 * calling g_socket_shutdown() with only the @shutdown_write flag set,
3240 * and then wait for the client to notice this and close its side of the
3241 * connection, after which the server can safely call g_socket_close().
3242 * (This is what #GTcpConnection does if you call
3243 * g_tcp_connection_set_graceful_disconnect(). But of course, this
3244 * only works if the client will close its connection after the server
3247 * Returns: %TRUE on success, %FALSE on error
3252 g_socket_close (GSocket *socket,
3257 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3259 if (socket->priv->closed)
3260 return TRUE; /* Multiple close not an error */
3262 if (!check_socket (socket, error))
3268 res = closesocket (socket->priv->fd);
3270 res = close (socket->priv->fd);
3274 int errsv = get_socket_errno ();
3279 g_set_error (error, G_IO_ERROR,
3280 socket_io_error_from_errno (errsv),
3281 _("Error closing socket: %s"),
3282 socket_strerror (errsv));
3288 socket->priv->connected_read = FALSE;
3289 socket->priv->connected_write = FALSE;
3290 socket->priv->closed = TRUE;
3291 if (socket->priv->remote_address)
3293 g_object_unref (socket->priv->remote_address);
3294 socket->priv->remote_address = NULL;
3301 * g_socket_is_closed:
3302 * @socket: a #GSocket
3304 * Checks whether a socket is closed.
3306 * Returns: %TRUE if socket is closed, %FALSE otherwise
3311 g_socket_is_closed (GSocket *socket)
3313 return socket->priv->closed;
3317 /* Broken source, used on errors */
3319 broken_dispatch (GSource *source,
3320 GSourceFunc callback,
3326 static GSourceFuncs broken_funcs =
3335 network_events_for_condition (GIOCondition condition)
3339 if (condition & G_IO_IN)
3340 event_mask |= (FD_READ | FD_ACCEPT);
3341 if (condition & G_IO_OUT)
3342 event_mask |= (FD_WRITE | FD_CONNECT);
3343 event_mask |= FD_CLOSE;
3349 ensure_event (GSocket *socket)
3351 if (socket->priv->event == WSA_INVALID_EVENT)
3352 socket->priv->event = WSACreateEvent();
3356 update_select_events (GSocket *socket)
3363 ensure_event (socket);
3366 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3369 event_mask |= network_events_for_condition (*ptr);
3372 if (event_mask != socket->priv->selected_events)
3374 /* If no events selected, disable event so we can unset
3377 if (event_mask == 0)
3380 event = socket->priv->event;
3382 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3383 socket->priv->selected_events = event_mask;
3388 add_condition_watch (GSocket *socket,
3389 GIOCondition *condition)
3391 g_mutex_lock (&socket->priv->win32_source_lock);
3392 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3394 socket->priv->requested_conditions =
3395 g_list_prepend (socket->priv->requested_conditions, condition);
3397 update_select_events (socket);
3398 g_mutex_unlock (&socket->priv->win32_source_lock);
3402 remove_condition_watch (GSocket *socket,
3403 GIOCondition *condition)
3405 g_mutex_lock (&socket->priv->win32_source_lock);
3406 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3408 socket->priv->requested_conditions =
3409 g_list_remove (socket->priv->requested_conditions, condition);
3411 update_select_events (socket);
3412 g_mutex_unlock (&socket->priv->win32_source_lock);
3416 update_condition (GSocket *socket)
3418 WSANETWORKEVENTS events;
3419 GIOCondition condition;
3421 if (WSAEnumNetworkEvents (socket->priv->fd,
3422 socket->priv->event,
3425 socket->priv->current_events |= events.lNetworkEvents;
3426 if (events.lNetworkEvents & FD_WRITE &&
3427 events.iErrorCode[FD_WRITE_BIT] != 0)
3428 socket->priv->current_errors |= FD_WRITE;
3429 if (events.lNetworkEvents & FD_CONNECT &&
3430 events.iErrorCode[FD_CONNECT_BIT] != 0)
3431 socket->priv->current_errors |= FD_CONNECT;
3435 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3436 condition |= G_IO_IN;
3438 if (socket->priv->current_events & FD_CLOSE)
3440 int r, errsv, buffer;
3442 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3444 errsv = get_socket_errno ();
3447 (r < 0 && errsv == WSAENOTCONN))
3448 condition |= G_IO_IN;
3450 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3451 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3452 condition |= G_IO_HUP;
3454 condition |= G_IO_ERR;
3457 if (socket->priv->closed)
3458 condition |= G_IO_HUP;
3460 /* Never report both G_IO_OUT and HUP, these are
3461 mutually exclusive (can't write to a closed socket) */
3462 if ((condition & G_IO_HUP) == 0 &&
3463 socket->priv->current_events & FD_WRITE)
3465 if (socket->priv->current_errors & FD_WRITE)
3466 condition |= G_IO_ERR;
3468 condition |= G_IO_OUT;
3472 if (socket->priv->current_events & FD_CONNECT)
3474 if (socket->priv->current_errors & FD_CONNECT)
3475 condition |= (G_IO_HUP | G_IO_ERR);
3477 condition |= G_IO_OUT;
3493 GIOCondition condition;
3498 socket_source_prepare_win32 (GSource *source,
3501 GSocketSource *socket_source = (GSocketSource *)source;
3505 return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3509 socket_source_check_win32 (GSource *source)
3513 return socket_source_prepare_win32 (source, &timeout);
3518 socket_source_dispatch (GSource *source,
3519 GSourceFunc callback,
3522 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3523 GSocketSource *socket_source = (GSocketSource *)source;
3524 GSocket *socket = socket_source->socket;
3530 events = update_condition (socket_source->socket);
3532 events = g_source_query_unix_fd (source, socket_source->fd_tag);
3535 timeout = g_source_get_ready_time (source);
3536 if (timeout >= 0 && timeout < g_source_get_time (source))
3538 socket->priv->timed_out = TRUE;
3539 events |= (G_IO_IN | G_IO_OUT);
3542 ret = (*func) (socket, events & socket_source->condition, user_data);
3544 if (socket->priv->timeout)
3545 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3547 g_source_set_ready_time (source, -1);
3553 socket_source_finalize (GSource *source)
3555 GSocketSource *socket_source = (GSocketSource *)source;
3558 socket = socket_source->socket;
3561 remove_condition_watch (socket, &socket_source->condition);
3564 g_object_unref (socket);
3568 socket_source_closure_callback (GSocket *socket,
3569 GIOCondition condition,
3572 GClosure *closure = data;
3574 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3575 GValue result_value = G_VALUE_INIT;
3578 g_value_init (&result_value, G_TYPE_BOOLEAN);
3580 g_value_init (¶ms[0], G_TYPE_SOCKET);
3581 g_value_set_object (¶ms[0], socket);
3582 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
3583 g_value_set_flags (¶ms[1], condition);
3585 g_closure_invoke (closure, &result_value, 2, params, NULL);
3587 result = g_value_get_boolean (&result_value);
3588 g_value_unset (&result_value);
3589 g_value_unset (¶ms[0]);
3590 g_value_unset (¶ms[1]);
3595 static GSourceFuncs socket_source_funcs =
3598 socket_source_prepare_win32,
3599 socket_source_check_win32,
3601 NULL, NULL, /* check, prepare */
3603 socket_source_dispatch,
3604 socket_source_finalize,
3605 (GSourceFunc)socket_source_closure_callback,
3609 socket_source_new (GSocket *socket,
3610 GIOCondition condition,
3611 GCancellable *cancellable)
3614 GSocketSource *socket_source;
3617 ensure_event (socket);
3619 if (socket->priv->event == WSA_INVALID_EVENT)
3621 g_warning ("Failed to create WSAEvent");
3622 return g_source_new (&broken_funcs, sizeof (GSource));
3626 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
3628 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3629 g_source_set_name (source, "GSocket");
3630 socket_source = (GSocketSource *)source;
3632 socket_source->socket = g_object_ref (socket);
3633 socket_source->condition = condition;
3637 GSource *cancellable_source;
3639 cancellable_source = g_cancellable_source_new (cancellable);
3640 g_source_add_child_source (source, cancellable_source);
3641 g_source_set_dummy_callback (cancellable_source);
3642 g_source_unref (cancellable_source);
3646 add_condition_watch (socket, &socket_source->condition);
3647 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3648 socket_source->pollfd.events = condition;
3649 socket_source->pollfd.revents = 0;
3650 g_source_add_poll (source, &socket_source->pollfd);
3652 socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
3655 if (socket->priv->timeout)
3656 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3658 g_source_set_ready_time (source, -1);
3664 * g_socket_create_source: (skip)
3665 * @socket: a #GSocket
3666 * @condition: a #GIOCondition mask to monitor
3667 * @cancellable: (allow-none): a %GCancellable or %NULL
3669 * Creates a #GSource that can be attached to a %GMainContext to monitor
3670 * for the availability of the specified @condition on the socket. The #GSource
3671 * keeps a reference to the @socket.
3673 * The callback on the source is of the #GSocketSourceFunc type.
3675 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3676 * these conditions will always be reported output if they are true.
3678 * @cancellable if not %NULL can be used to cancel the source, which will
3679 * cause the source to trigger, reporting the current condition (which
3680 * is likely 0 unless cancellation happened at the same time as a
3681 * condition change). You can check for this in the callback using
3682 * g_cancellable_is_cancelled().
3684 * If @socket has a timeout set, and it is reached before @condition
3685 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3686 * %G_IO_OUT depending on @condition. However, @socket will have been
3687 * marked as having had a timeout, and so the next #GSocket I/O method
3688 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3690 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3695 g_socket_create_source (GSocket *socket,
3696 GIOCondition condition,
3697 GCancellable *cancellable)
3699 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3701 return socket_source_new (socket, condition, cancellable);
3705 * g_socket_condition_check:
3706 * @socket: a #GSocket
3707 * @condition: a #GIOCondition mask to check
3709 * Checks on the readiness of @socket to perform operations.
3710 * The operations specified in @condition are checked for and masked
3711 * against the currently-satisfied conditions on @socket. The result
3714 * Note that on Windows, it is possible for an operation to return
3715 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3716 * g_socket_condition_check() has claimed that the socket is ready for
3717 * writing. Rather than calling g_socket_condition_check() and then
3718 * writing to the socket if it succeeds, it is generally better to
3719 * simply try writing to the socket right away, and try again later if
3720 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3722 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3723 * these conditions will always be set in the output if they are true.
3725 * This call never blocks.
3727 * Returns: the @GIOCondition mask of the current state
3732 g_socket_condition_check (GSocket *socket,
3733 GIOCondition condition)
3735 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3737 if (!check_socket (socket, NULL))
3742 GIOCondition current_condition;
3744 condition |= G_IO_ERR | G_IO_HUP;
3746 add_condition_watch (socket, &condition);
3747 current_condition = update_condition (socket);
3748 remove_condition_watch (socket, &condition);
3749 return condition & current_condition;
3755 poll_fd.fd = socket->priv->fd;
3756 poll_fd.events = condition;
3757 poll_fd.revents = 0;
3760 result = g_poll (&poll_fd, 1, 0);
3761 while (result == -1 && get_socket_errno () == EINTR);
3763 return poll_fd.revents;
3769 * g_socket_condition_wait:
3770 * @socket: a #GSocket
3771 * @condition: a #GIOCondition mask to wait for
3772 * @cancellable: (allow-none): a #GCancellable, or %NULL
3773 * @error: a #GError pointer, or %NULL
3775 * Waits for @condition to become true on @socket. When the condition
3776 * is met, %TRUE is returned.
3778 * If @cancellable is cancelled before the condition is met, or if the
3779 * socket has a timeout set and it is reached before the condition is
3780 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3781 * the appropriate value (%G_IO_ERROR_CANCELLED or
3782 * %G_IO_ERROR_TIMED_OUT).
3784 * See also g_socket_condition_timed_wait().
3786 * Returns: %TRUE if the condition was met, %FALSE otherwise
3791 g_socket_condition_wait (GSocket *socket,
3792 GIOCondition condition,
3793 GCancellable *cancellable,
3796 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3798 return g_socket_condition_timed_wait (socket, condition, -1,
3799 cancellable, error);
3803 * g_socket_condition_timed_wait:
3804 * @socket: a #GSocket
3805 * @condition: a #GIOCondition mask to wait for
3806 * @timeout: the maximum time (in microseconds) to wait, or -1
3807 * @cancellable: (allow-none): a #GCancellable, or %NULL
3808 * @error: a #GError pointer, or %NULL
3810 * Waits for up to @timeout microseconds for @condition to become true
3811 * on @socket. If the condition is met, %TRUE is returned.
3813 * If @cancellable is cancelled before the condition is met, or if
3814 * @timeout (or the socket's #GSocket:timeout) is reached before the
3815 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3816 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3817 * %G_IO_ERROR_TIMED_OUT).
3819 * If you don't want a timeout, use g_socket_condition_wait().
3820 * (Alternatively, you can pass -1 for @timeout.)
3822 * Note that although @timeout is in microseconds for consistency with
3823 * other GLib APIs, this function actually only has millisecond
3824 * resolution, and the behavior is undefined if @timeout is not an
3825 * exact number of milliseconds.
3827 * Returns: %TRUE if the condition was met, %FALSE otherwise
3832 g_socket_condition_timed_wait (GSocket *socket,
3833 GIOCondition condition,
3835 GCancellable *cancellable,
3840 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3842 if (!check_socket (socket, error))
3845 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3848 if (socket->priv->timeout &&
3849 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3850 timeout = socket->priv->timeout * 1000;
3851 else if (timeout != -1)
3852 timeout = timeout / 1000;
3854 start_time = g_get_monotonic_time ();
3858 GIOCondition current_condition;
3864 /* Always check these */
3865 condition |= G_IO_ERR | G_IO_HUP;
3867 add_condition_watch (socket, &condition);
3870 events[num_events++] = socket->priv->event;
3872 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3873 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3876 timeout = WSA_INFINITE;
3878 current_condition = update_condition (socket);
3879 while ((condition & current_condition) == 0)
3881 res = WSAWaitForMultipleEvents (num_events, events,
3882 FALSE, timeout, FALSE);
3883 if (res == WSA_WAIT_FAILED)
3885 int errsv = get_socket_errno ();
3887 g_set_error (error, G_IO_ERROR,
3888 socket_io_error_from_errno (errsv),
3889 _("Waiting for socket condition: %s"),
3890 socket_strerror (errsv));
3893 else if (res == WSA_WAIT_TIMEOUT)
3895 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3896 _("Socket I/O timed out"));
3900 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3903 current_condition = update_condition (socket);
3905 if (timeout != WSA_INFINITE)
3907 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3912 remove_condition_watch (socket, &condition);
3914 g_cancellable_release_fd (cancellable);
3916 return (condition & current_condition) != 0;
3924 poll_fd[0].fd = socket->priv->fd;
3925 poll_fd[0].events = condition;
3928 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3933 result = g_poll (poll_fd, num, timeout);
3934 if (result != -1 || errno != EINTR)
3939 timeout -= (g_get_monotonic_time () - start_time) / 1000;
3946 g_cancellable_release_fd (cancellable);
3950 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3951 _("Socket I/O timed out"));
3955 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3962 /* Unfortunately these have to be macros rather than inline functions due to
3963 * using alloca(). */
3964 #define output_message_to_msghdr(message, prev_message, msg, prev_msg, error) \
3966 const GOutputMessage *_message = (message); \
3967 const GOutputMessage *_prev_message = (prev_message); \
3968 struct msghdr *_msg = (msg); \
3969 const struct msghdr *_prev_msg = (prev_msg); \
3970 GError **_error = (error); \
3972 _msg->msg_flags = 0; \
3975 if (_prev_message != NULL && _prev_message->address == _message->address) \
3977 _msg->msg_name = _prev_msg->msg_name; \
3978 _msg->msg_namelen = _prev_msg->msg_namelen; \
3980 else if (_message->address != NULL) \
3982 _msg->msg_namelen = g_socket_address_get_native_size (_message->address); \
3983 _msg->msg_name = g_alloca (_msg->msg_namelen); \
3984 if (!g_socket_address_to_native (_message->address, _msg->msg_name, \
3985 _msg->msg_namelen, _error)) \
3990 _msg->msg_name = NULL; \
3991 _msg->msg_namelen = 0; \
3996 /* this entire expression will be evaluated at compile time */ \
3997 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
3998 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
3999 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4000 G_STRUCT_OFFSET (GOutputVector, buffer) && \
4001 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4002 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4003 G_STRUCT_OFFSET (GOutputVector, size)) \
4004 /* ABI is compatible */ \
4006 _msg->msg_iov = (struct iovec *) _message->vectors; \
4007 _msg->msg_iovlen = _message->num_vectors; \
4010 /* ABI is incompatible */ \
4014 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4015 for (i = 0; i < _message->num_vectors; i++) \
4017 _msg->msg_iov[i].iov_base = (void *) _message->vectors[i].buffer; \
4018 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4020 _msg->msg_iovlen = _message->num_vectors; \
4026 struct cmsghdr *cmsg; \
4029 _msg->msg_controllen = 0; \
4030 for (i = 0; i < _message->num_control_messages; i++) \
4031 _msg->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (_message->control_messages[i])); \
4033 if (_msg->msg_controllen == 0) \
4034 _msg->msg_control = NULL; \
4037 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4038 memset (_msg->msg_control, '\0', _msg->msg_controllen); \
4041 cmsg = CMSG_FIRSTHDR (_msg); \
4042 for (i = 0; i < _message->num_control_messages; i++) \
4044 cmsg->cmsg_level = g_socket_control_message_get_level (_message->control_messages[i]); \
4045 cmsg->cmsg_type = g_socket_control_message_get_msg_type (_message->control_messages[i]); \
4046 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (_message->control_messages[i])); \
4047 g_socket_control_message_serialize (_message->control_messages[i], \
4048 CMSG_DATA (cmsg)); \
4049 cmsg = CMSG_NXTHDR (_msg, cmsg); \
4051 g_assert (cmsg == NULL); \
4055 #define input_message_to_msghdr(message, msg) \
4057 const GInputMessage *_message = (message); \
4058 struct msghdr *_msg = (msg); \
4061 if (_message->address) \
4063 _msg->msg_namelen = sizeof (struct sockaddr_storage); \
4064 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4068 _msg->msg_name = NULL; \
4069 _msg->msg_namelen = 0; \
4073 /* this entire expression will be evaluated at compile time */ \
4074 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4075 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4076 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4077 G_STRUCT_OFFSET (GInputVector, buffer) && \
4078 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4079 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4080 G_STRUCT_OFFSET (GInputVector, size)) \
4081 /* ABI is compatible */ \
4083 _msg->msg_iov = (struct iovec *) _message->vectors; \
4084 _msg->msg_iovlen = _message->num_vectors; \
4087 /* ABI is incompatible */ \
4091 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4092 for (i = 0; i < _message->num_vectors; i++) \
4094 _msg->msg_iov[i].iov_base = _message->vectors[i].buffer; \
4095 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4097 _msg->msg_iovlen = _message->num_vectors; \
4101 _msg->msg_controllen = 2048; \
4102 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4105 _msg->msg_flags = _message->flags; \
4109 input_message_from_msghdr (const struct msghdr *msg,
4110 GInputMessage *message,
4113 /* decode address */
4114 if (message->address != NULL)
4116 *message->address = cache_recv_address (socket, msg->msg_name,
4120 /* decode control messages */
4122 GPtrArray *my_messages = NULL;
4123 struct cmsghdr *cmsg;
4125 if (msg->msg_controllen >= sizeof (struct cmsghdr))
4127 for (cmsg = CMSG_FIRSTHDR (msg);
4129 cmsg = CMSG_NXTHDR ((struct msghdr *) msg, cmsg))
4131 GSocketControlMessage *control_message;
4133 control_message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4135 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4137 if (control_message == NULL)
4138 /* We've already spewed about the problem in the
4139 deserialization code, so just continue */
4142 if (message->control_messages == NULL)
4144 /* we have to do it this way if the user ignores the
4145 * messages so that we will close any received fds.
4147 g_object_unref (control_message);
4151 if (my_messages == NULL)
4152 my_messages = g_ptr_array_new ();
4153 g_ptr_array_add (my_messages, control_message);
4158 if (message->num_control_messages)
4159 *message->num_control_messages = my_messages != NULL ? my_messages->len : 0;
4161 if (message->control_messages)
4163 if (my_messages == NULL)
4165 *message->control_messages = NULL;
4169 g_ptr_array_add (my_messages, NULL);
4170 *message->control_messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4175 g_assert (my_messages == NULL);
4179 /* capture the flags */
4180 message->flags = msg->msg_flags;
4185 * g_socket_send_message:
4186 * @socket: a #GSocket
4187 * @address: (allow-none): a #GSocketAddress, or %NULL
4188 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4189 * @num_vectors: the number of elements in @vectors, or -1
4190 * @messages: (array length=num_messages) (allow-none): a pointer to an
4191 * array of #GSocketControlMessages, or %NULL.
4192 * @num_messages: number of elements in @messages, or -1.
4193 * @flags: an int containing #GSocketMsgFlags flags
4194 * @cancellable: (allow-none): a %GCancellable or %NULL
4195 * @error: #GError for error reporting, or %NULL to ignore.
4197 * Send data to @address on @socket. For sending multiple messages see
4198 * g_socket_send_messages(); for easier use, see
4199 * g_socket_send() and g_socket_send_to().
4201 * If @address is %NULL then the message is sent to the default receiver
4202 * (set by g_socket_connect()).
4204 * @vectors must point to an array of #GOutputVector structs and
4205 * @num_vectors must be the length of this array. (If @num_vectors is -1,
4206 * then @vectors is assumed to be terminated by a #GOutputVector with a
4207 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
4208 * that the sent data will be gathered from. Using multiple
4209 * #GOutputVectors is more memory-efficient than manually copying
4210 * data from multiple sources into a single buffer, and more
4211 * network-efficient than making multiple calls to g_socket_send().
4213 * @messages, if non-%NULL, is taken to point to an array of @num_messages
4214 * #GSocketControlMessage instances. These correspond to the control
4215 * messages to be sent on the socket.
4216 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
4219 * @flags modify how the message is sent. The commonly available arguments
4220 * for this are available in the #GSocketMsgFlags enum, but the
4221 * values there are the same as the system values, and the flags
4222 * are passed in as-is, so you can pass in system-specific flags too.
4224 * If the socket is in blocking mode the call will block until there is
4225 * space for the data in the socket queue. If there is no space available
4226 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4227 * will be returned. To be notified when space is available, wait for the
4228 * %G_IO_OUT condition. Note though that you may still receive
4229 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4230 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4231 * very common due to the way the underlying APIs work.)
4233 * On error -1 is returned and @error is set accordingly.
4235 * Returns: Number of bytes written (which may be less than @size), or -1
4241 g_socket_send_message (GSocket *socket,
4242 GSocketAddress *address,
4243 GOutputVector *vectors,
4245 GSocketControlMessage **messages,
4248 GCancellable *cancellable,
4251 return g_socket_send_message_with_timeout (socket, address,
4252 vectors, num_vectors,
4253 messages, num_messages, flags,
4254 socket->priv->blocking ? -1 : 0,
4255 cancellable, error);
4259 g_socket_send_message_with_timeout (GSocket *socket,
4260 GSocketAddress *address,
4261 GOutputVector *vectors,
4263 GSocketControlMessage **messages,
4267 GCancellable *cancellable,
4270 GOutputVector one_vector;
4274 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4275 g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), -1);
4276 g_return_val_if_fail (num_vectors == 0 || vectors != NULL, -1);
4277 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
4278 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
4279 g_return_val_if_fail (error == NULL || *error == NULL, -1);
4281 start_time = g_get_monotonic_time ();
4283 if (!check_socket (socket, error))
4286 if (!check_timeout (socket, error))
4289 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4292 if (num_vectors == -1)
4294 for (num_vectors = 0;
4295 vectors[num_vectors].buffer != NULL;
4300 if (num_messages == -1)
4302 for (num_messages = 0;
4303 messages != NULL && messages[num_messages] != NULL;
4308 if (num_vectors == 0)
4312 one_vector.buffer = &zero;
4313 one_vector.size = 1;
4315 vectors = &one_vector;
4320 GOutputMessage output_message;
4323 GError *child_error = NULL;
4325 output_message.address = address;
4326 output_message.vectors = vectors;
4327 output_message.num_vectors = num_vectors;
4328 output_message.bytes_sent = 0;
4329 output_message.control_messages = messages;
4330 output_message.num_control_messages = num_messages;
4332 output_message_to_msghdr (&output_message, NULL, &msg, NULL, &child_error);
4334 if (child_error != NULL)
4336 g_propagate_error (error, child_error);
4342 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4345 int errsv = get_socket_errno ();
4351 (errsv == EWOULDBLOCK ||
4354 if (!block_on_timeout (socket, G_IO_OUT, timeout, start_time,
4355 cancellable, error))
4361 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4371 struct sockaddr_storage addr;
4378 /* Win32 doesn't support control messages.
4379 Actually this is possible for raw and datagram sockets
4380 via WSASendMessage on Vista or later, but that doesn't
4382 if (num_messages != 0)
4384 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
4385 _("GSocketControlMessage not supported on Windows"));
4390 bufs = g_newa (WSABUF, num_vectors);
4391 for (i = 0; i < num_vectors; i++)
4393 bufs[i].buf = (char *)vectors[i].buffer;
4394 bufs[i].len = (gulong)vectors[i].size;
4398 addrlen = 0; /* Avoid warning */
4401 addrlen = g_socket_address_get_native_size (address);
4402 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
4409 result = WSASendTo (socket->priv->fd,
4412 (const struct sockaddr *)&addr, addrlen,
4415 result = WSASend (socket->priv->fd,
4422 int errsv = get_socket_errno ();
4424 if (errsv == WSAEINTR)
4427 if (errsv == WSAEWOULDBLOCK)
4429 win32_unset_event_mask (socket, FD_WRITE);
4433 if (!block_on_timeout (socket, G_IO_OUT, timeout,
4434 start_time, cancellable, error))
4441 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4453 * g_socket_send_messages:
4454 * @socket: a #GSocket
4455 * @messages: (array length=num_messages): an array of #GOutputMessage structs
4456 * @num_messages: the number of elements in @messages
4457 * @flags: an int containing #GSocketMsgFlags flags
4458 * @cancellable: (allow-none): a %GCancellable or %NULL
4459 * @error: #GError for error reporting, or %NULL to ignore.
4461 * Send multiple data messages from @socket in one go. This is the most
4462 * complicated and fully-featured version of this call. For easier use, see
4463 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
4465 * @messages must point to an array of #GOutputMessage structs and
4466 * @num_messages must be the length of this array. Each #GOutputMessage
4467 * contains an address to send the data to, and a pointer to an array of
4468 * #GOutputVector structs to describe the buffers that the data to be sent
4469 * for each message will be gathered from. Using multiple #GOutputVectors is
4470 * more memory-efficient than manually copying data from multiple sources
4471 * into a single buffer, and more network-efficient than making multiple
4472 * calls to g_socket_send(). Sending multiple messages in one go avoids the
4473 * overhead of making a lot of syscalls in scenarios where a lot of data
4474 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
4475 * or where the same data needs to be sent to multiple recipients.
4477 * @flags modify how the message is sent. The commonly available arguments
4478 * for this are available in the #GSocketMsgFlags enum, but the
4479 * values there are the same as the system values, and the flags
4480 * are passed in as-is, so you can pass in system-specific flags too.
4482 * If the socket is in blocking mode the call will block until there is
4483 * space for all the data in the socket queue. If there is no space available
4484 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4485 * will be returned if no data was written at all, otherwise the number of
4486 * messages sent will be returned. To be notified when space is available,
4487 * wait for the %G_IO_OUT condition. Note though that you may still receive
4488 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4489 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4490 * very common due to the way the underlying APIs work.)
4492 * On error -1 is returned and @error is set accordingly. An error will only
4493 * be returned if zero messages could be sent; otherwise the number of messages
4494 * successfully sent before the error will be returned.
4496 * Returns: number of messages sent, or -1 on error. Note that the number of
4497 * messages sent may be smaller than @num_messages if the socket is
4498 * non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
4499 * in which case the caller may re-try to send the remaining messages.
4504 g_socket_send_messages (GSocket *socket,
4505 GOutputMessage *messages,
4508 GCancellable *cancellable,
4511 return g_socket_send_messages_with_timeout (socket, messages, num_messages,
4513 socket->priv->blocking ? -1 : 0,
4514 cancellable, error);
4518 g_socket_send_messages_with_timeout (GSocket *socket,
4519 GOutputMessage *messages,
4523 GCancellable *cancellable,
4528 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4529 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
4530 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
4531 g_return_val_if_fail (error == NULL || *error == NULL, -1);
4533 start_time = g_get_monotonic_time ();
4535 if (!check_socket (socket, error))
4538 if (!check_timeout (socket, error))
4541 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4544 if (num_messages == 0)
4547 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
4549 struct mmsghdr *msgvec;
4553 #define MAX_NUM_MESSAGES UIO_MAXIOV
4555 #define MAX_NUM_MESSAGES 1024
4558 if (num_messages > MAX_NUM_MESSAGES)
4559 num_messages = MAX_NUM_MESSAGES;
4561 msgvec = g_newa (struct mmsghdr, num_messages);
4563 for (i = 0; i < num_messages; ++i)
4565 GOutputMessage *msg = &messages[i];
4566 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
4567 GError *child_error = NULL;
4569 msgvec[i].msg_len = 0;
4571 output_message_to_msghdr (msg, (i > 0) ? &messages[i - 1] : NULL,
4572 msg_hdr, (i > 0) ? &msgvec[i - 1].msg_hdr : NULL,
4575 if (child_error != NULL)
4577 g_propagate_error (error, child_error);
4582 for (num_sent = 0; num_sent < num_messages;)
4586 ret = sendmmsg (socket->priv->fd, msgvec + num_sent, num_messages - num_sent,
4587 flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4591 int errsv = get_socket_errno ();
4597 (errsv == EWOULDBLOCK ||
4600 if (!block_on_timeout (socket, G_IO_OUT, timeout, start_time,
4601 cancellable, error))
4605 g_clear_error (error);
4615 /* If any messages were successfully sent, do not error. */
4619 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4627 for (i = 0; i < num_sent; ++i)
4628 messages[i].bytes_sent = msgvec[i].msg_len;
4636 gint64 wait_timeout;
4638 wait_timeout = timeout;
4640 for (i = 0; i < num_messages; ++i)
4642 GOutputMessage *msg = &messages[i];
4643 GError *msg_error = NULL;
4645 result = g_socket_send_message_with_timeout (socket, msg->address,
4648 msg->control_messages,
4649 msg->num_control_messages,
4650 flags, wait_timeout,
4651 cancellable, &msg_error);
4653 /* check if we've timed out or how much time to wait at most */
4656 gint64 elapsed = g_get_monotonic_time () - start_time;
4657 wait_timeout = MAX (timeout - elapsed, 1);
4662 /* if we couldn't send all messages, just return how many we did
4663 * manage to send, provided we managed to send at least one */
4665 (g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK) ||
4666 g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)))
4668 g_error_free (msg_error);
4673 g_propagate_error (error, msg_error);
4678 msg->bytes_sent = result;
4686 static GSocketAddress *
4687 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
4689 GSocketAddress *saddr;
4691 guint64 oldest_time = G_MAXUINT64;
4692 gint oldest_index = 0;
4694 if (native_len <= 0)
4698 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
4700 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
4701 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
4702 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
4707 if (tmp_native_len != native_len)
4710 if (memcmp (tmp_native, native, native_len) == 0)
4712 saddr = g_object_ref (tmp);
4713 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
4717 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
4719 oldest_time = socket->priv->recv_addr_cache[i].last_used;
4724 saddr = g_socket_address_new_from_native (native, native_len);
4726 if (socket->priv->recv_addr_cache[oldest_index].addr)
4728 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
4729 g_free (socket->priv->recv_addr_cache[oldest_index].native);
4732 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
4733 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
4734 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
4735 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
4741 g_socket_receive_message_with_timeout (GSocket *socket,
4742 GSocketAddress **address,
4743 GInputVector *vectors,
4745 GSocketControlMessage ***messages,
4749 GCancellable *cancellable,
4752 GInputVector one_vector;
4756 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4758 start_time = g_get_monotonic_time ();
4760 if (!check_socket (socket, error))
4763 if (!check_timeout (socket, error))
4766 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4769 if (num_vectors == -1)
4771 for (num_vectors = 0;
4772 vectors[num_vectors].buffer != NULL;
4777 if (num_vectors == 0)
4779 one_vector.buffer = &one_byte;
4780 one_vector.size = 1;
4782 vectors = &one_vector;
4787 GInputMessage input_message;
4791 input_message.address = address;
4792 input_message.vectors = vectors;
4793 input_message.num_vectors = num_vectors;
4794 input_message.bytes_received = 0;
4795 input_message.flags = (flags != NULL) ? *flags : 0;
4796 input_message.control_messages = messages;
4797 input_message.num_control_messages = (guint *) num_messages;
4799 /* We always set the close-on-exec flag so we don't leak file
4800 * descriptors into child processes. Note that gunixfdmessage.c
4801 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4803 #ifdef MSG_CMSG_CLOEXEC
4804 input_message.flags |= MSG_CMSG_CLOEXEC;
4807 input_message_to_msghdr (&input_message, &msg);
4812 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4813 #ifdef MSG_CMSG_CLOEXEC
4814 if (result < 0 && get_socket_errno () == EINVAL)
4816 /* We must be running on an old kernel. Call without the flag. */
4817 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4818 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4824 int errsv = get_socket_errno ();
4830 (errsv == EWOULDBLOCK ||
4833 if (!block_on_timeout (socket, G_IO_IN, timeout, start_time,
4834 cancellable, error))
4840 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
4846 input_message_from_msghdr (&msg, &input_message, socket);
4849 *flags = input_message.flags;
4855 struct sockaddr_storage addr;
4857 DWORD bytes_received;
4864 bufs = g_newa (WSABUF, num_vectors);
4865 for (i = 0; i < num_vectors; i++)
4867 bufs[i].buf = (char *)vectors[i].buffer;
4868 bufs[i].len = (gulong)vectors[i].size;
4880 addrlen = sizeof addr;
4882 result = WSARecvFrom (socket->priv->fd,
4884 &bytes_received, &win_flags,
4885 (struct sockaddr *)&addr, &addrlen,
4888 result = WSARecv (socket->priv->fd,
4890 &bytes_received, &win_flags,
4894 int errsv = get_socket_errno ();
4896 if (errsv == WSAEINTR)
4899 if (errsv == WSAEWOULDBLOCK)
4901 win32_unset_event_mask (socket, FD_READ);
4905 if (!block_on_timeout (socket, G_IO_IN, timeout,
4906 start_time, cancellable, error))
4913 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
4916 win32_unset_event_mask (socket, FD_READ);
4920 /* decode address */
4921 if (address != NULL)
4923 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
4926 /* capture the flags */
4930 if (messages != NULL)
4932 if (num_messages != NULL)
4935 return bytes_received;
4941 * g_socket_receive_messages:
4942 * @socket: a #GSocket
4943 * @messages: (array length=num_messages): an array of #GInputMessage structs
4944 * @num_messages: the number of elements in @messages
4945 * @flags: an int containing #GSocketMsgFlags flags for the overall operation
4946 * @cancellable: (allow-none): a %GCancellable or %NULL
4947 * @error: #GError for error reporting, or %NULL to ignore
4949 * Receive multiple data messages from @socket in one go. This is the most
4950 * complicated and fully-featured version of this call. For easier use, see
4951 * g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
4953 * @messages must point to an array of #GInputMessage structs and
4954 * @num_messages must be the length of this array. Each #GInputMessage
4955 * contains a pointer to an array of #GInputVector structs describing the
4956 * buffers that the data received in each message will be written to. Using
4957 * multiple #GInputVectors is more memory-efficient than manually copying data
4958 * out of a single buffer to multiple sources, and more system-call-efficient
4959 * than making multiple calls to g_socket_receive(), such as in scenarios where
4960 * a lot of data packets need to be received (e.g. high-bandwidth video
4961 * streaming over RTP/UDP).
4963 * @flags modify how all messages are received. The commonly available
4964 * arguments for this are available in the #GSocketMsgFlags enum, but the
4965 * values there are the same as the system values, and the flags
4966 * are passed in as-is, so you can pass in system-specific flags too. These
4967 * flags affect the overall receive operation. Flags affecting individual
4968 * messages are returned in #GInputMessage.flags.
4970 * The other members of #GInputMessage are treated as described in its
4973 * If #GSocket:blocking is %TRUE the call will block until @num_messages have
4974 * been received, or the end of the stream is reached.
4976 * If #GSocket:blocking is %FALSE the call will return up to @num_messages
4977 * without blocking, or %G_IO_ERROR_WOULD_BLOCK if no messages are queued in the
4978 * operating system to be received.
4980 * In blocking mode, if #GSocket:timeout is positive and is reached before any
4981 * messages are received, %G_IO_ERROR_TIMED_OUT is returned, otherwise up to
4982 * @num_messages are returned. (Note: This is effectively the
4983 * behaviour of `MSG_WAITFORONE` with recvmmsg().)
4985 * To be notified when messages are available, wait for the
4986 * %G_IO_IN condition. Note though that you may still receive
4987 * %G_IO_ERROR_WOULD_BLOCK from g_socket_receive_messages() even if you were
4988 * previously notified of a %G_IO_IN condition.
4990 * If the remote peer closes the connection, any messages queued in the
4991 * operating system will be returned, and subsequent calls to
4992 * g_socket_receive_messages() will return 0 (with no error set).
4994 * On error -1 is returned and @error is set accordingly. An error will only
4995 * be returned if zero messages could be received; otherwise the number of
4996 * messages successfully received before the error will be returned.
4998 * Returns: number of messages received, or -1 on error. Note that the number
4999 * of messages received may be smaller than @num_messages if in non-blocking
5000 * mode, if the peer closed the connection, or if @num_messages
5001 * was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
5002 * to receive the remaining messages.
5007 g_socket_receive_messages (GSocket *socket,
5008 GInputMessage *messages,
5011 GCancellable *cancellable,
5014 if (!check_socket (socket, error) ||
5015 !check_timeout (socket, error))
5018 return g_socket_receive_messages_with_timeout (socket, messages, num_messages,
5020 socket->priv->blocking ? -1 : 0,
5021 cancellable, error);
5025 g_socket_receive_messages_with_timeout (GSocket *socket,
5026 GInputMessage *messages,
5030 GCancellable *cancellable,
5035 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5036 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5037 g_return_val_if_fail (cancellable == NULL ||
5038 G_IS_CANCELLABLE (cancellable), -1);
5039 g_return_val_if_fail (error == NULL || *error == NULL, -1);
5041 start_time = g_get_monotonic_time ();
5043 if (!check_socket (socket, error))
5046 if (!check_timeout (socket, error))
5049 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5052 if (num_messages == 0)
5055 #if !defined (G_OS_WIN32) && defined (HAVE_RECVMMSG)
5057 struct mmsghdr *msgvec;
5058 guint i, num_received;
5061 #define MAX_NUM_MESSAGES UIO_MAXIOV
5063 #define MAX_NUM_MESSAGES 1024
5066 if (num_messages > MAX_NUM_MESSAGES)
5067 num_messages = MAX_NUM_MESSAGES;
5069 msgvec = g_newa (struct mmsghdr, num_messages);
5071 for (i = 0; i < num_messages; ++i)
5073 GInputMessage *msg = &messages[i];
5074 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5076 input_message_to_msghdr (msg, msg_hdr);
5077 msgvec[i].msg_len = 0;
5080 /* We always set the close-on-exec flag so we don't leak file
5081 * descriptors into child processes. Note that gunixfdmessage.c
5082 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5084 #ifdef MSG_CMSG_CLOEXEC
5085 flags |= MSG_CMSG_CLOEXEC;
5088 for (num_received = 0; num_received < num_messages;)
5092 /* We operate in non-blocking mode and handle the timeout ourselves. */
5093 ret = recvmmsg (socket->priv->fd,
5094 msgvec + num_received,
5095 num_messages - num_received,
5096 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5097 #ifdef MSG_CMSG_CLOEXEC
5098 if (ret < 0 && get_socket_errno () == EINVAL)
5100 /* We must be running on an old kernel. Call without the flag. */
5101 flags &= ~(MSG_CMSG_CLOEXEC);
5102 ret = recvmmsg (socket->priv->fd,
5103 msgvec + num_received,
5104 num_messages - num_received,
5105 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5111 int errsv = get_socket_errno ();
5117 (errsv == EWOULDBLOCK ||
5120 if (!block_on_timeout (socket, G_IO_IN, timeout, start_time,
5121 cancellable, error))
5123 if (num_received > 0)
5125 g_clear_error (error);
5135 /* If any messages were successfully received, do not error. */
5136 if (num_received > 0)
5139 socket_set_error_lazy (error, errsv,
5140 _("Error receiving message: %s"));
5150 num_received += ret;
5153 for (i = 0; i < num_received; ++i)
5155 input_message_from_msghdr (&msgvec[i].msg_hdr, &messages[i], socket);
5156 messages[i].bytes_received = msgvec[i].msg_len;
5159 return num_received;
5164 gint64 wait_timeout;
5166 wait_timeout = timeout;
5168 for (i = 0; i < num_messages; i++)
5170 GInputMessage *msg = &messages[i];
5172 GError *msg_error = NULL;
5174 msg->flags = flags; /* in-out parameter */
5176 len = g_socket_receive_message_with_timeout (socket,
5180 msg->control_messages,
5181 (gint *) msg->num_control_messages,
5187 /* check if we've timed out or how much time to wait at most */
5190 gint64 elapsed = g_get_monotonic_time () - start_time;
5191 wait_timeout = MAX (timeout - elapsed, 1);
5195 msg->bytes_received = len;
5198 (g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK) ||
5199 g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)))
5201 g_clear_error (&msg_error);
5205 if (msg_error != NULL)
5207 g_propagate_error (error, msg_error);
5221 * g_socket_receive_message:
5222 * @socket: a #GSocket
5223 * @address: (out) (nullable): a pointer to a #GSocketAddress
5225 * @vectors: (array length=num_vectors): an array of #GInputVector structs
5226 * @num_vectors: the number of elements in @vectors, or -1
5227 * @messages: (array length=num_messages) (out) (nullable): a pointer which
5228 * may be filled with an array of #GSocketControlMessages, or %NULL
5229 * @num_messages: (out): a pointer which will be filled with the number of
5230 * elements in @messages, or %NULL
5231 * @flags: (inout): a pointer to an int containing #GSocketMsgFlags flags
5232 * @cancellable: a %GCancellable or %NULL
5233 * @error: a #GError pointer, or %NULL
5235 * Receive data from a socket. For receiving multiple messages, see
5236 * g_socket_receive_messages(); for easier use, see
5237 * g_socket_receive() and g_socket_receive_from().
5239 * If @address is non-%NULL then @address will be set equal to the
5240 * source address of the received packet.
5241 * @address is owned by the caller.
5243 * @vector must point to an array of #GInputVector structs and
5244 * @num_vectors must be the length of this array. These structs
5245 * describe the buffers that received data will be scattered into.
5246 * If @num_vectors is -1, then @vectors is assumed to be terminated
5247 * by a #GInputVector with a %NULL buffer pointer.
5249 * As a special case, if @num_vectors is 0 (in which case, @vectors
5250 * may of course be %NULL), then a single byte is received and
5251 * discarded. This is to facilitate the common practice of sending a
5252 * single '\0' byte for the purposes of transferring ancillary data.
5254 * @messages, if non-%NULL, will be set to point to a newly-allocated
5255 * array of #GSocketControlMessage instances or %NULL if no such
5256 * messages was received. These correspond to the control messages
5257 * received from the kernel, one #GSocketControlMessage per message
5258 * from the kernel. This array is %NULL-terminated and must be freed
5259 * by the caller using g_free() after calling g_object_unref() on each
5260 * element. If @messages is %NULL, any control messages received will
5263 * @num_messages, if non-%NULL, will be set to the number of control
5264 * messages received.
5266 * If both @messages and @num_messages are non-%NULL, then
5267 * @num_messages gives the number of #GSocketControlMessage instances
5268 * in @messages (ie: not including the %NULL terminator).
5270 * @flags is an in/out parameter. The commonly available arguments
5271 * for this are available in the #GSocketMsgFlags enum, but the
5272 * values there are the same as the system values, and the flags
5273 * are passed in as-is, so you can pass in system-specific flags too
5274 * (and g_socket_receive_message() may pass system-specific flags out).
5275 * Flags passed in to the parameter affect the receive operation; flags returned
5276 * out of it are relevant to the specific returned message.
5278 * As with g_socket_receive(), data may be discarded if @socket is
5279 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
5280 * provide enough buffer space to read a complete message. You can pass
5281 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
5282 * removing it from the receive queue, but there is no portable way to find
5283 * out the length of the message other than by reading it into a
5284 * sufficiently-large buffer.
5286 * If the socket is in blocking mode the call will block until there
5287 * is some data to receive, the connection is closed, or there is an
5288 * error. If there is no data available and the socket is in
5289 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
5290 * returned. To be notified when data is available, wait for the
5291 * %G_IO_IN condition.
5293 * On error -1 is returned and @error is set accordingly.
5295 * Returns: Number of bytes read, or 0 if the connection was closed by
5296 * the peer, or -1 on error
5301 g_socket_receive_message (GSocket *socket,
5302 GSocketAddress **address,
5303 GInputVector *vectors,
5305 GSocketControlMessage ***messages,
5308 GCancellable *cancellable,
5311 return g_socket_receive_message_with_timeout (socket, address, vectors,
5312 num_vectors, messages,
5313 num_messages, flags,
5314 socket->priv->blocking ? -1 : 0,
5315 cancellable, error);
5319 * g_socket_get_credentials:
5320 * @socket: a #GSocket.
5321 * @error: #GError for error reporting, or %NULL to ignore.
5323 * Returns the credentials of the foreign process connected to this
5324 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
5327 * If this operation isn't supported on the OS, the method fails with
5328 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
5329 * by reading the %SO_PEERCRED option on the underlying socket.
5331 * Other ways to obtain credentials from a foreign peer includes the
5332 * #GUnixCredentialsMessage type and
5333 * g_unix_connection_send_credentials() /
5334 * g_unix_connection_receive_credentials() functions.
5336 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
5337 * that must be freed with g_object_unref().
5342 g_socket_get_credentials (GSocket *socket,
5347 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
5348 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5352 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
5356 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
5357 socklen_t optlen = sizeof (native_creds_buf);
5359 if (getsockopt (socket->priv->fd,
5365 ret = g_credentials_new ();
5366 g_credentials_set_native (ret,
5367 G_CREDENTIALS_NATIVE_TYPE,
5371 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
5373 struct unpcbid cred;
5374 socklen_t optlen = sizeof (cred);
5376 if (getsockopt (socket->priv->fd,
5382 ret = g_credentials_new ();
5383 g_credentials_set_native (ret,
5384 G_CREDENTIALS_NATIVE_TYPE,
5388 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
5390 ucred_t *ucred = NULL;
5392 if (getpeerucred (socket->priv->fd, &ucred) == 0)
5394 ret = g_credentials_new ();
5395 g_credentials_set_native (ret,
5396 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
5402 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
5407 int errsv = get_socket_errno ();
5411 socket_io_error_from_errno (errsv),
5412 _("Unable to read socket credentials: %s"),
5413 socket_strerror (errsv));
5418 g_set_error_literal (error,
5420 G_IO_ERROR_NOT_SUPPORTED,
5421 _("g_socket_get_credentials not implemented for this OS"));
5428 * g_socket_get_option:
5429 * @socket: a #GSocket
5430 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5431 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5432 * @value: (out): return location for the option value
5433 * @error: #GError for error reporting, or %NULL to ignore.
5435 * Gets the value of an integer-valued option on @socket, as with
5436 * getsockopt(). (If you need to fetch a non-integer-valued option,
5437 * you will need to call getsockopt() directly.)
5439 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5440 * header pulls in system headers that will define most of the
5441 * standard/portable socket options. For unusual socket protocols or
5442 * platform-dependent options, you may need to include additional
5445 * Note that even for socket options that are a single byte in size,
5446 * @value is still a pointer to a #gint variable, not a #guchar;
5447 * g_socket_get_option() will handle the conversion internally.
5449 * Returns: success or failure. On failure, @error will be set, and
5450 * the system error value (`errno` or WSAGetLastError()) will still
5451 * be set to the result of the getsockopt() call.
5456 g_socket_get_option (GSocket *socket,
5464 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
5467 size = sizeof (gint);
5468 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
5470 int errsv = get_socket_errno ();
5472 g_set_error_literal (error,
5474 socket_io_error_from_errno (errsv),
5475 socket_strerror (errsv));
5477 /* Reset errno in case the caller wants to look at it */
5483 #if G_BYTE_ORDER == G_BIG_ENDIAN
5484 /* If the returned value is smaller than an int then we need to
5485 * slide it over into the low-order bytes of *value.
5487 if (size != sizeof (gint))
5488 *value = *value >> (8 * (sizeof (gint) - size));
5495 * g_socket_set_option:
5496 * @socket: a #GSocket
5497 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5498 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5499 * @value: the value to set the option to
5500 * @error: #GError for error reporting, or %NULL to ignore.
5502 * Sets the value of an integer-valued option on @socket, as with
5503 * setsockopt(). (If you need to set a non-integer-valued option,
5504 * you will need to call setsockopt() directly.)
5506 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5507 * header pulls in system headers that will define most of the
5508 * standard/portable socket options. For unusual socket protocols or
5509 * platform-dependent options, you may need to include additional
5512 * Returns: success or failure. On failure, @error will be set, and
5513 * the system error value (`errno` or WSAGetLastError()) will still
5514 * be set to the result of the setsockopt() call.
5519 g_socket_set_option (GSocket *socket,
5527 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
5529 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
5532 #if !defined (__linux__) && !defined (G_OS_WIN32)
5533 /* Linux and Windows let you set a single-byte value from an int,
5534 * but most other platforms don't.
5536 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
5538 #if G_BYTE_ORDER == G_BIG_ENDIAN
5539 value = value << (8 * (sizeof (gint) - 1));
5541 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
5546 errsv = get_socket_errno ();
5548 g_set_error_literal (error,
5550 socket_io_error_from_errno (errsv),
5551 socket_strerror (errsv));