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
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General
18 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 * Authors: Christian Kellner <gicmo@gnome.org>
21 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
22 * Ryan Lortie <desrt@desrt.ca>
23 * Alexander Larsson <alexl@redhat.com>
31 #include "glib-unix.h"
42 # include <sys/ioctl.h>
45 #ifdef HAVE_SYS_FILIO_H
46 # include <sys/filio.h>
53 #include "gcancellable.h"
54 #include "gioenumtypes.h"
55 #include "ginetaddress.h"
56 #include "ginitable.h"
60 #include "gnetworkingprivate.h"
61 #include "gsocketaddress.h"
62 #include "gsocketcontrolmessage.h"
63 #include "gcredentials.h"
64 #include "gcredentialsprivate.h"
69 * @short_description: Low-level socket object
71 * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
73 * A #GSocket is a low-level networking primitive. It is a more or less
74 * direct mapping of the BSD socket API in a portable GObject based API.
75 * It supports both the UNIX socket implementations and winsock2 on Windows.
77 * #GSocket is the platform independent base upon which the higher level
78 * network primitives are based. Applications are not typically meant to
79 * use it directly, but rather through classes like #GSocketClient,
80 * #GSocketService and #GSocketConnection. However there may be cases where
81 * direct use of #GSocket is useful.
83 * #GSocket implements the #GInitable interface, so if it is manually constructed
84 * by e.g. g_object_new() you must call g_initable_init() and check the
85 * results before using the object. This is done automatically in
86 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
89 * Sockets operate in two general modes, blocking or non-blocking. When
90 * in blocking mode all operations block until the requested operation
91 * is finished or there is an error. In non-blocking mode all calls that
92 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
93 * To know when a call would successfully run you can call g_socket_condition_check(),
94 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
95 * attach it to a #GMainContext to get callbacks when I/O is possible.
96 * Note that all sockets are always set to non blocking mode in the system, and
97 * blocking mode is emulated in GSocket.
99 * When working in non-blocking mode applications should always be able to
100 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
101 * function said that I/O was possible. This can easily happen in case
102 * of a race condition in the application, but it can also happen for other
103 * reasons. For instance, on Windows a socket is always seen as writable
104 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
106 * #GSockets can be either connection oriented or datagram based.
107 * For connection oriented types you must first establish a connection by
108 * either connecting to an address or accepting a connection from another
109 * address. For connectionless socket types the target/source address is
110 * specified or received in each I/O operation.
112 * All socket file descriptors are set to be close-on-exec.
114 * Note that creating a #GSocket causes the signal %SIGPIPE to be
115 * ignored for the remainder of the program. If you are writing a
116 * command-line utility that uses #GSocket, you may need to take into
117 * account the fact that your program will not automatically be killed
118 * if it tries to write to %stdout after it has been closed.
120 * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
121 * a #GSocket concurrently from multiple threads, you must implement your own
127 static void g_socket_initable_iface_init (GInitableIface *iface);
128 static gboolean g_socket_initable_init (GInitable *initable,
129 GCancellable *cancellable,
147 PROP_MULTICAST_LOOPBACK,
151 /* Size of the receiver cache for g_socket_receive_from() */
152 #define RECV_ADDR_CACHE_SIZE 8
154 struct _GSocketPrivate
156 GSocketFamily family;
158 GSocketProtocol protocol;
162 GError *construct_error;
163 GSocketAddress *remote_address;
171 guint connect_pending : 1;
177 GList *requested_conditions; /* list of requested GIOCondition * */
178 GMutex win32_source_lock;
182 GSocketAddress *addr;
183 struct sockaddr *native;
186 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
189 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
190 G_ADD_PRIVATE (GSocket)
191 g_networking_init ();
192 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
193 g_socket_initable_iface_init));
196 get_socket_errno (void)
201 return WSAGetLastError ();
206 socket_io_error_from_errno (int err)
209 return g_io_error_from_win32_error (err);
211 return g_io_error_from_errno (err);
216 socket_strerror (int err)
219 return g_strerror (err);
224 msg = g_win32_error_message (err);
226 msg_ret = g_intern_string (msg);
234 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
236 _win32_unset_event_mask (GSocket *socket, int mask)
238 socket->priv->current_events &= ~mask;
239 socket->priv->current_errors &= ~mask;
242 #define win32_unset_event_mask(_socket, _mask)
245 /* Windows has broken prototypes... */
247 #define getsockopt(sockfd, level, optname, optval, optlen) \
248 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
249 #define setsockopt(sockfd, level, optname, optval, optlen) \
250 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
251 #define getsockname(sockfd, addr, addrlen) \
252 getsockname (sockfd, addr, (int *)addrlen)
253 #define getpeername(sockfd, addr, addrlen) \
254 getpeername (sockfd, addr, (int *)addrlen)
255 #define recv(sockfd, buf, len, flags) \
256 recv (sockfd, (gpointer)buf, len, flags)
260 check_socket (GSocket *socket,
263 if (!socket->priv->inited)
265 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
266 _("Invalid socket, not initialized"));
270 if (socket->priv->construct_error)
272 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
273 _("Invalid socket, initialization failed due to: %s"),
274 socket->priv->construct_error->message);
278 if (socket->priv->closed)
280 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
281 _("Socket is already closed"));
289 check_timeout (GSocket *socket,
292 if (socket->priv->timed_out)
294 socket->priv->timed_out = FALSE;
295 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
296 _("Socket I/O timed out"));
304 g_socket_details_from_fd (GSocket *socket)
306 struct sockaddr_storage address;
312 fd = socket->priv->fd;
313 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
315 errsv = get_socket_errno ();
327 /* programmer error */
328 g_error ("creating GSocket from fd %d: %s\n",
329 fd, socket_strerror (errsv));
340 socket->priv->type = G_SOCKET_TYPE_STREAM;
344 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
348 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
352 socket->priv->type = G_SOCKET_TYPE_INVALID;
356 addrlen = sizeof address;
357 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
359 errsv = get_socket_errno ();
365 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
366 sizeof address.ss_family <= addrlen);
367 family = address.ss_family;
371 /* On Solaris, this happens if the socket is not yet connected.
372 * But we can use SO_DOMAIN as a workaround there.
375 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
377 errsv = get_socket_errno ();
381 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
389 case G_SOCKET_FAMILY_IPV4:
390 case G_SOCKET_FAMILY_IPV6:
391 socket->priv->family = address.ss_family;
392 switch (socket->priv->type)
394 case G_SOCKET_TYPE_STREAM:
395 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
398 case G_SOCKET_TYPE_DATAGRAM:
399 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
402 case G_SOCKET_TYPE_SEQPACKET:
403 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
411 case G_SOCKET_FAMILY_UNIX:
412 socket->priv->family = G_SOCKET_FAMILY_UNIX;
413 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
417 socket->priv->family = G_SOCKET_FAMILY_INVALID;
421 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
423 addrlen = sizeof address;
424 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
425 socket->priv->connected = TRUE;
428 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
430 socket->priv->keepalive = !!value;
434 /* Can't read, maybe not supported, assume FALSE */
435 socket->priv->keepalive = FALSE;
441 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
442 socket_io_error_from_errno (errsv),
443 _("creating GSocket from fd: %s"),
444 socket_strerror (errsv));
447 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
449 g_socket (gint domain,
457 fd = socket (domain, type | SOCK_CLOEXEC, protocol);
461 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
462 if (fd < 0 && (errno == EINVAL || errno == EPROTOTYPE))
464 fd = socket (domain, type, protocol);
468 int errsv = get_socket_errno ();
470 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
471 _("Unable to create socket: %s"), socket_strerror (errsv));
480 /* We always want to set close-on-exec to protect users. If you
481 need to so some weird inheritance to exec you can re-enable this
482 using lower level hacks with g_socket_get_fd(). */
483 flags = fcntl (fd, F_GETFD, 0);
485 (flags & FD_CLOEXEC) == 0)
488 fcntl (fd, F_SETFD, flags);
497 g_socket_create_socket (GSocketFamily family,
506 case G_SOCKET_TYPE_STREAM:
507 native_type = SOCK_STREAM;
510 case G_SOCKET_TYPE_DATAGRAM:
511 native_type = SOCK_DGRAM;
514 case G_SOCKET_TYPE_SEQPACKET:
515 native_type = SOCK_SEQPACKET;
519 g_assert_not_reached ();
524 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
525 _("Unable to create socket: %s"), _("Unknown family was specified"));
531 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
532 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
536 return g_socket (family, native_type, protocol, error);
540 g_socket_constructed (GObject *object)
542 GSocket *socket = G_SOCKET (object);
544 if (socket->priv->fd >= 0)
545 /* create socket->priv info from the fd */
546 g_socket_details_from_fd (socket);
549 /* create the fd from socket->priv info */
550 socket->priv->fd = g_socket_create_socket (socket->priv->family,
552 socket->priv->protocol,
553 &socket->priv->construct_error);
555 if (socket->priv->fd != -1)
558 GError *error = NULL;
563 /* Always use native nonblocking sockets, as Windows sets sockets to
564 * nonblocking automatically in certain operations. This way we make
565 * things work the same on all platforms.
568 if (!g_unix_set_fd_nonblocking (socket->priv->fd, TRUE, &error))
570 g_warning ("Error setting socket nonblocking: %s", error->message);
571 g_clear_error (&error);
576 if (ioctlsocket (socket->priv->fd, FIONBIO, &arg) == SOCKET_ERROR)
578 int errsv = get_socket_errno ();
579 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
584 /* See note about SIGPIPE below. */
585 g_socket_set_option (socket, SOL_SOCKET, SO_NOSIGPIPE, TRUE, NULL);
591 g_socket_get_property (GObject *object,
596 GSocket *socket = G_SOCKET (object);
597 GSocketAddress *address;
602 g_value_set_enum (value, socket->priv->family);
606 g_value_set_enum (value, socket->priv->type);
610 g_value_set_enum (value, socket->priv->protocol);
614 g_value_set_int (value, socket->priv->fd);
618 g_value_set_boolean (value, socket->priv->blocking);
621 case PROP_LISTEN_BACKLOG:
622 g_value_set_int (value, socket->priv->listen_backlog);
626 g_value_set_boolean (value, socket->priv->keepalive);
629 case PROP_LOCAL_ADDRESS:
630 address = g_socket_get_local_address (socket, NULL);
631 g_value_take_object (value, address);
634 case PROP_REMOTE_ADDRESS:
635 address = g_socket_get_remote_address (socket, NULL);
636 g_value_take_object (value, address);
640 g_value_set_uint (value, socket->priv->timeout);
644 g_value_set_uint (value, g_socket_get_ttl (socket));
648 g_value_set_boolean (value, g_socket_get_broadcast (socket));
651 case PROP_MULTICAST_LOOPBACK:
652 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
655 case PROP_MULTICAST_TTL:
656 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
660 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
665 g_socket_set_property (GObject *object,
670 GSocket *socket = G_SOCKET (object);
675 socket->priv->family = g_value_get_enum (value);
679 socket->priv->type = g_value_get_enum (value);
683 socket->priv->protocol = g_value_get_enum (value);
687 socket->priv->fd = g_value_get_int (value);
691 g_socket_set_blocking (socket, g_value_get_boolean (value));
694 case PROP_LISTEN_BACKLOG:
695 g_socket_set_listen_backlog (socket, g_value_get_int (value));
699 g_socket_set_keepalive (socket, g_value_get_boolean (value));
703 g_socket_set_timeout (socket, g_value_get_uint (value));
707 g_socket_set_ttl (socket, g_value_get_uint (value));
711 g_socket_set_broadcast (socket, g_value_get_boolean (value));
714 case PROP_MULTICAST_LOOPBACK:
715 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
718 case PROP_MULTICAST_TTL:
719 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
723 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
728 g_socket_finalize (GObject *object)
730 GSocket *socket = G_SOCKET (object);
733 g_clear_error (&socket->priv->construct_error);
735 if (socket->priv->fd != -1 &&
736 !socket->priv->closed)
737 g_socket_close (socket, NULL);
739 if (socket->priv->remote_address)
740 g_object_unref (socket->priv->remote_address);
743 if (socket->priv->event != WSA_INVALID_EVENT)
745 WSACloseEvent (socket->priv->event);
746 socket->priv->event = WSA_INVALID_EVENT;
749 g_assert (socket->priv->requested_conditions == NULL);
750 g_mutex_clear (&socket->priv->win32_source_lock);
753 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
755 if (socket->priv->recv_addr_cache[i].addr)
757 g_object_unref (socket->priv->recv_addr_cache[i].addr);
758 g_free (socket->priv->recv_addr_cache[i].native);
762 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
763 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
767 g_socket_class_init (GSocketClass *klass)
769 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
772 /* There is no portable, thread-safe way to avoid having the process
773 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
774 * forced to simply ignore the signal process-wide.
776 * Even if we ignore it though, gdb will still stop if the app
777 * receives a SIGPIPE, which can be confusing and annoying. So when
778 * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
779 * prevent the signal from occurring at all.
781 signal (SIGPIPE, SIG_IGN);
784 gobject_class->finalize = g_socket_finalize;
785 gobject_class->constructed = g_socket_constructed;
786 gobject_class->set_property = g_socket_set_property;
787 gobject_class->get_property = g_socket_get_property;
789 g_object_class_install_property (gobject_class, PROP_FAMILY,
790 g_param_spec_enum ("family",
792 P_("The sockets address family"),
793 G_TYPE_SOCKET_FAMILY,
794 G_SOCKET_FAMILY_INVALID,
795 G_PARAM_CONSTRUCT_ONLY |
797 G_PARAM_STATIC_STRINGS));
799 g_object_class_install_property (gobject_class, PROP_TYPE,
800 g_param_spec_enum ("type",
802 P_("The sockets type"),
804 G_SOCKET_TYPE_STREAM,
805 G_PARAM_CONSTRUCT_ONLY |
807 G_PARAM_STATIC_STRINGS));
809 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
810 g_param_spec_enum ("protocol",
811 P_("Socket protocol"),
812 P_("The id of the protocol to use, or -1 for unknown"),
813 G_TYPE_SOCKET_PROTOCOL,
814 G_SOCKET_PROTOCOL_UNKNOWN,
815 G_PARAM_CONSTRUCT_ONLY |
817 G_PARAM_STATIC_STRINGS));
819 g_object_class_install_property (gobject_class, PROP_FD,
820 g_param_spec_int ("fd",
821 P_("File descriptor"),
822 P_("The sockets file descriptor"),
826 G_PARAM_CONSTRUCT_ONLY |
828 G_PARAM_STATIC_STRINGS));
830 g_object_class_install_property (gobject_class, PROP_BLOCKING,
831 g_param_spec_boolean ("blocking",
833 P_("Whether or not I/O on this socket is blocking"),
836 G_PARAM_STATIC_STRINGS));
838 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
839 g_param_spec_int ("listen-backlog",
840 P_("Listen backlog"),
841 P_("Outstanding connections in the listen queue"),
846 G_PARAM_STATIC_STRINGS));
848 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
849 g_param_spec_boolean ("keepalive",
850 P_("Keep connection alive"),
851 P_("Keep connection alive by sending periodic pings"),
854 G_PARAM_STATIC_STRINGS));
856 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
857 g_param_spec_object ("local-address",
859 P_("The local address the socket is bound to"),
860 G_TYPE_SOCKET_ADDRESS,
862 G_PARAM_STATIC_STRINGS));
864 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
865 g_param_spec_object ("remote-address",
866 P_("Remote address"),
867 P_("The remote address the socket is connected to"),
868 G_TYPE_SOCKET_ADDRESS,
870 G_PARAM_STATIC_STRINGS));
875 * The timeout in seconds on socket I/O
879 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
880 g_param_spec_uint ("timeout",
882 P_("The timeout in seconds on socket I/O"),
887 G_PARAM_STATIC_STRINGS));
892 * Whether the socket should allow sending to broadcast addresses.
896 g_object_class_install_property (gobject_class, PROP_BROADCAST,
897 g_param_spec_boolean ("broadcast",
899 P_("Whether to allow sending to broadcast addresses"),
902 G_PARAM_STATIC_STRINGS));
907 * Time-to-live for outgoing unicast packets
911 g_object_class_install_property (gobject_class, PROP_TTL,
912 g_param_spec_uint ("ttl",
914 P_("Time-to-live of outgoing unicast packets"),
917 G_PARAM_STATIC_STRINGS));
920 * GSocket:multicast-loopback:
922 * Whether outgoing multicast packets loop back to the local host.
926 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
927 g_param_spec_boolean ("multicast-loopback",
928 P_("Multicast loopback"),
929 P_("Whether outgoing multicast packets loop back to the local host"),
932 G_PARAM_STATIC_STRINGS));
935 * GSocket:multicast-ttl:
937 * Time-to-live out outgoing multicast packets
941 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
942 g_param_spec_uint ("multicast-ttl",
944 P_("Time-to-live of outgoing multicast packets"),
947 G_PARAM_STATIC_STRINGS));
951 g_socket_initable_iface_init (GInitableIface *iface)
953 iface->init = g_socket_initable_init;
957 g_socket_init (GSocket *socket)
959 socket->priv = g_socket_get_instance_private (socket);
961 socket->priv->fd = -1;
962 socket->priv->blocking = TRUE;
963 socket->priv->listen_backlog = 10;
964 socket->priv->construct_error = NULL;
966 socket->priv->event = WSA_INVALID_EVENT;
967 g_mutex_init (&socket->priv->win32_source_lock);
972 g_socket_initable_init (GInitable *initable,
973 GCancellable *cancellable,
978 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
980 socket = G_SOCKET (initable);
982 if (cancellable != NULL)
984 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
985 _("Cancellable initialization not supported"));
989 socket->priv->inited = TRUE;
991 if (socket->priv->construct_error)
994 *error = g_error_copy (socket->priv->construct_error);
1004 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1005 * @type: the socket type to use.
1006 * @protocol: the id of the protocol to use, or 0 for default.
1007 * @error: #GError for error reporting, or %NULL to ignore.
1009 * Creates a new #GSocket with the defined family, type and protocol.
1010 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1011 * for the family and type is used.
1013 * The @protocol is a family and type specific int that specifies what
1014 * kind of protocol to use. #GSocketProtocol lists several common ones.
1015 * Many families only support one protocol, and use 0 for this, others
1016 * support several and using 0 means to use the default protocol for
1017 * the family and type.
1019 * The protocol id is passed directly to the operating
1020 * system, so you can use protocols not listed in #GSocketProtocol if you
1021 * know the protocol number used for it.
1023 * Returns: a #GSocket or %NULL on error.
1024 * Free the returned object with g_object_unref().
1029 g_socket_new (GSocketFamily family,
1031 GSocketProtocol protocol,
1034 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1038 "protocol", protocol,
1043 * g_socket_new_from_fd:
1044 * @fd: a native socket file descriptor.
1045 * @error: #GError for error reporting, or %NULL to ignore.
1047 * Creates a new #GSocket from a native file descriptor
1048 * or winsock SOCKET handle.
1050 * This reads all the settings from the file descriptor so that
1051 * all properties should work. Note that the file descriptor
1052 * will be set to non-blocking mode, independent on the blocking
1053 * mode of the #GSocket.
1055 * Returns: a #GSocket or %NULL on error.
1056 * Free the returned object with g_object_unref().
1061 g_socket_new_from_fd (gint fd,
1064 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1071 * g_socket_set_blocking:
1072 * @socket: a #GSocket.
1073 * @blocking: Whether to use blocking I/O or not.
1075 * Sets the blocking mode of the socket. In blocking mode
1076 * all operations block until they succeed or there is an error. In
1077 * non-blocking mode all functions return results immediately or
1078 * with a %G_IO_ERROR_WOULD_BLOCK error.
1080 * All sockets are created in blocking mode. However, note that the
1081 * platform level socket is always non-blocking, and blocking mode
1082 * is a GSocket level feature.
1087 g_socket_set_blocking (GSocket *socket,
1090 g_return_if_fail (G_IS_SOCKET (socket));
1092 blocking = !!blocking;
1094 if (socket->priv->blocking == blocking)
1097 socket->priv->blocking = blocking;
1098 g_object_notify (G_OBJECT (socket), "blocking");
1102 * g_socket_get_blocking:
1103 * @socket: a #GSocket.
1105 * Gets the blocking mode of the socket. For details on blocking I/O,
1106 * see g_socket_set_blocking().
1108 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1113 g_socket_get_blocking (GSocket *socket)
1115 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1117 return socket->priv->blocking;
1121 * g_socket_set_keepalive:
1122 * @socket: a #GSocket.
1123 * @keepalive: Value for the keepalive flag
1125 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1126 * this flag is set on a socket, the system will attempt to verify that the
1127 * remote socket endpoint is still present if a sufficiently long period of
1128 * time passes with no data being exchanged. If the system is unable to
1129 * verify the presence of the remote endpoint, it will automatically close
1132 * This option is only functional on certain kinds of sockets. (Notably,
1133 * %G_SOCKET_PROTOCOL_TCP sockets.)
1135 * The exact time between pings is system- and protocol-dependent, but will
1136 * normally be at least two hours. Most commonly, you would set this flag
1137 * on a server socket if you want to allow clients to remain idle for long
1138 * periods of time, but also want to ensure that connections are eventually
1139 * garbage-collected if clients crash or become unreachable.
1144 g_socket_set_keepalive (GSocket *socket,
1147 GError *error = NULL;
1149 g_return_if_fail (G_IS_SOCKET (socket));
1151 keepalive = !!keepalive;
1152 if (socket->priv->keepalive == keepalive)
1155 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1158 g_warning ("error setting keepalive: %s", error->message);
1159 g_error_free (error);
1163 socket->priv->keepalive = keepalive;
1164 g_object_notify (G_OBJECT (socket), "keepalive");
1168 * g_socket_get_keepalive:
1169 * @socket: a #GSocket.
1171 * Gets the keepalive mode of the socket. For details on this,
1172 * see g_socket_set_keepalive().
1174 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1179 g_socket_get_keepalive (GSocket *socket)
1181 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1183 return socket->priv->keepalive;
1187 * g_socket_get_listen_backlog:
1188 * @socket: a #GSocket.
1190 * Gets the listen backlog setting of the socket. For details on this,
1191 * see g_socket_set_listen_backlog().
1193 * Returns: the maximum number of pending connections.
1198 g_socket_get_listen_backlog (GSocket *socket)
1200 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1202 return socket->priv->listen_backlog;
1206 * g_socket_set_listen_backlog:
1207 * @socket: a #GSocket.
1208 * @backlog: the maximum number of pending connections.
1210 * Sets the maximum number of outstanding connections allowed
1211 * when listening on this socket. If more clients than this are
1212 * connecting to the socket and the application is not handling them
1213 * on time then the new connections will be refused.
1215 * Note that this must be called before g_socket_listen() and has no
1216 * effect if called after that.
1221 g_socket_set_listen_backlog (GSocket *socket,
1224 g_return_if_fail (G_IS_SOCKET (socket));
1225 g_return_if_fail (!socket->priv->listening);
1227 if (backlog != socket->priv->listen_backlog)
1229 socket->priv->listen_backlog = backlog;
1230 g_object_notify (G_OBJECT (socket), "listen-backlog");
1235 * g_socket_get_timeout:
1236 * @socket: a #GSocket.
1238 * Gets the timeout setting of the socket. For details on this, see
1239 * g_socket_set_timeout().
1241 * Returns: the timeout in seconds
1246 g_socket_get_timeout (GSocket *socket)
1248 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1250 return socket->priv->timeout;
1254 * g_socket_set_timeout:
1255 * @socket: a #GSocket.
1256 * @timeout: the timeout for @socket, in seconds, or 0 for none
1258 * Sets the time in seconds after which I/O operations on @socket will
1259 * time out if they have not yet completed.
1261 * On a blocking socket, this means that any blocking #GSocket
1262 * operation will time out after @timeout seconds of inactivity,
1263 * returning %G_IO_ERROR_TIMED_OUT.
1265 * On a non-blocking socket, calls to g_socket_condition_wait() will
1266 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1267 * created with g_socket_create_source() will trigger after
1268 * @timeout seconds of inactivity, with the requested condition
1269 * set, at which point calling g_socket_receive(), g_socket_send(),
1270 * g_socket_check_connect_result(), etc, will fail with
1271 * %G_IO_ERROR_TIMED_OUT.
1273 * If @timeout is 0 (the default), operations will never time out
1276 * Note that if an I/O operation is interrupted by a signal, this may
1277 * cause the timeout to be reset.
1282 g_socket_set_timeout (GSocket *socket,
1285 g_return_if_fail (G_IS_SOCKET (socket));
1287 if (timeout != socket->priv->timeout)
1289 socket->priv->timeout = timeout;
1290 g_object_notify (G_OBJECT (socket), "timeout");
1296 * @socket: a #GSocket.
1298 * Gets the unicast time-to-live setting on @socket; see
1299 * g_socket_set_ttl() for more details.
1301 * Returns: the time-to-live setting on @socket
1306 g_socket_get_ttl (GSocket *socket)
1308 GError *error = NULL;
1311 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1313 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1315 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1318 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1320 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1324 g_return_val_if_reached (0);
1328 g_warning ("error getting unicast ttl: %s", error->message);
1329 g_error_free (error);
1338 * @socket: a #GSocket.
1339 * @ttl: the time-to-live value for all unicast packets on @socket
1341 * Sets the time-to-live for outgoing unicast packets on @socket.
1342 * By default the platform-specific default value is used.
1347 g_socket_set_ttl (GSocket *socket,
1350 GError *error = NULL;
1352 g_return_if_fail (G_IS_SOCKET (socket));
1354 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1356 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1359 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1361 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1363 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1367 g_return_if_reached ();
1371 g_warning ("error setting unicast ttl: %s", error->message);
1372 g_error_free (error);
1376 g_object_notify (G_OBJECT (socket), "ttl");
1380 * g_socket_get_broadcast:
1381 * @socket: a #GSocket.
1383 * Gets the broadcast setting on @socket; if %TRUE,
1384 * it is possible to send packets to broadcast
1387 * Returns: the broadcast setting on @socket
1392 g_socket_get_broadcast (GSocket *socket)
1394 GError *error = NULL;
1397 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1399 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1402 g_warning ("error getting broadcast: %s", error->message);
1403 g_error_free (error);
1411 * g_socket_set_broadcast:
1412 * @socket: a #GSocket.
1413 * @broadcast: whether @socket should allow sending to broadcast
1416 * Sets whether @socket should allow sending to broadcast addresses.
1417 * This is %FALSE by default.
1422 g_socket_set_broadcast (GSocket *socket,
1425 GError *error = NULL;
1427 g_return_if_fail (G_IS_SOCKET (socket));
1429 broadcast = !!broadcast;
1431 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1434 g_warning ("error setting broadcast: %s", error->message);
1435 g_error_free (error);
1439 g_object_notify (G_OBJECT (socket), "broadcast");
1443 * g_socket_get_multicast_loopback:
1444 * @socket: a #GSocket.
1446 * Gets the multicast loopback setting on @socket; if %TRUE (the
1447 * default), outgoing multicast packets will be looped back to
1448 * multicast listeners on the same host.
1450 * Returns: the multicast loopback setting on @socket
1455 g_socket_get_multicast_loopback (GSocket *socket)
1457 GError *error = NULL;
1460 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1462 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1464 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1467 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1469 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1473 g_return_val_if_reached (FALSE);
1477 g_warning ("error getting multicast loopback: %s", error->message);
1478 g_error_free (error);
1486 * g_socket_set_multicast_loopback:
1487 * @socket: a #GSocket.
1488 * @loopback: whether @socket should receive messages sent to its
1489 * multicast groups from the local host
1491 * Sets whether outgoing multicast packets will be received by sockets
1492 * listening on that multicast address on the same host. This is %TRUE
1498 g_socket_set_multicast_loopback (GSocket *socket,
1501 GError *error = NULL;
1503 g_return_if_fail (G_IS_SOCKET (socket));
1505 loopback = !!loopback;
1507 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1509 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1512 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1514 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1516 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1520 g_return_if_reached ();
1524 g_warning ("error setting multicast loopback: %s", error->message);
1525 g_error_free (error);
1529 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1533 * g_socket_get_multicast_ttl:
1534 * @socket: a #GSocket.
1536 * Gets the multicast time-to-live setting on @socket; see
1537 * g_socket_set_multicast_ttl() for more details.
1539 * Returns: the multicast time-to-live setting on @socket
1544 g_socket_get_multicast_ttl (GSocket *socket)
1546 GError *error = NULL;
1549 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1551 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1553 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1556 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1558 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1562 g_return_val_if_reached (FALSE);
1566 g_warning ("error getting multicast ttl: %s", error->message);
1567 g_error_free (error);
1575 * g_socket_set_multicast_ttl:
1576 * @socket: a #GSocket.
1577 * @ttl: the time-to-live value for all multicast datagrams on @socket
1579 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1580 * By default, this is 1, meaning that multicast packets will not leave
1581 * the local network.
1586 g_socket_set_multicast_ttl (GSocket *socket,
1589 GError *error = NULL;
1591 g_return_if_fail (G_IS_SOCKET (socket));
1593 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1595 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1598 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1600 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1602 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1606 g_return_if_reached ();
1610 g_warning ("error setting multicast ttl: %s", error->message);
1611 g_error_free (error);
1615 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1619 * g_socket_get_family:
1620 * @socket: a #GSocket.
1622 * Gets the socket family of the socket.
1624 * Returns: a #GSocketFamily
1629 g_socket_get_family (GSocket *socket)
1631 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1633 return socket->priv->family;
1637 * g_socket_get_socket_type:
1638 * @socket: a #GSocket.
1640 * Gets the socket type of the socket.
1642 * Returns: a #GSocketType
1647 g_socket_get_socket_type (GSocket *socket)
1649 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1651 return socket->priv->type;
1655 * g_socket_get_protocol:
1656 * @socket: a #GSocket.
1658 * Gets the socket protocol id the socket was created with.
1659 * In case the protocol is unknown, -1 is returned.
1661 * Returns: a protocol id, or -1 if unknown
1666 g_socket_get_protocol (GSocket *socket)
1668 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1670 return socket->priv->protocol;
1675 * @socket: a #GSocket.
1677 * Returns the underlying OS socket object. On unix this
1678 * is a socket file descriptor, and on Windows this is
1679 * a Winsock2 SOCKET handle. This may be useful for
1680 * doing platform specific or otherwise unusual operations
1683 * Returns: the file descriptor of the socket.
1688 g_socket_get_fd (GSocket *socket)
1690 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1692 return socket->priv->fd;
1696 * g_socket_get_local_address:
1697 * @socket: a #GSocket.
1698 * @error: #GError for error reporting, or %NULL to ignore.
1700 * Try to get the local address of a bound socket. This is only
1701 * useful if the socket has been bound to a local address,
1702 * either explicitly or implicitly when connecting.
1704 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1705 * Free the returned object with g_object_unref().
1710 g_socket_get_local_address (GSocket *socket,
1713 struct sockaddr_storage buffer;
1714 guint len = sizeof (buffer);
1716 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1718 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1720 int errsv = get_socket_errno ();
1721 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1722 _("could not get local address: %s"), socket_strerror (errsv));
1726 return g_socket_address_new_from_native (&buffer, len);
1730 * g_socket_get_remote_address:
1731 * @socket: a #GSocket.
1732 * @error: #GError for error reporting, or %NULL to ignore.
1734 * Try to get the remove address of a connected socket. This is only
1735 * useful for connection oriented sockets that have been connected.
1737 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1738 * Free the returned object with g_object_unref().
1743 g_socket_get_remote_address (GSocket *socket,
1746 struct sockaddr_storage buffer;
1747 guint len = sizeof (buffer);
1749 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1751 if (socket->priv->connect_pending)
1753 if (!g_socket_check_connect_result (socket, error))
1756 socket->priv->connect_pending = FALSE;
1759 if (!socket->priv->remote_address)
1761 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1763 int errsv = get_socket_errno ();
1764 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1765 _("could not get remote address: %s"), socket_strerror (errsv));
1769 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1772 return g_object_ref (socket->priv->remote_address);
1776 * g_socket_is_connected:
1777 * @socket: a #GSocket.
1779 * Check whether the socket is connected. This is only useful for
1780 * connection-oriented sockets.
1782 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1787 g_socket_is_connected (GSocket *socket)
1789 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1791 return socket->priv->connected;
1796 * @socket: a #GSocket.
1797 * @error: #GError for error reporting, or %NULL to ignore.
1799 * Marks the socket as a server socket, i.e. a socket that is used
1800 * to accept incoming requests using g_socket_accept().
1802 * Before calling this the socket must be bound to a local address using
1805 * To set the maximum amount of outstanding clients, use
1806 * g_socket_set_listen_backlog().
1808 * Returns: %TRUE on success, %FALSE on error.
1813 g_socket_listen (GSocket *socket,
1816 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1818 if (!check_socket (socket, error))
1821 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1823 int errsv = get_socket_errno ();
1825 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1826 _("could not listen: %s"), socket_strerror (errsv));
1830 socket->priv->listening = TRUE;
1837 * @socket: a #GSocket.
1838 * @address: a #GSocketAddress specifying the local address.
1839 * @allow_reuse: whether to allow reusing this address
1840 * @error: #GError for error reporting, or %NULL to ignore.
1842 * When a socket is created it is attached to an address family, but it
1843 * doesn't have an address in this family. g_socket_bind() assigns the
1844 * address (sometimes called name) of the socket.
1846 * It is generally required to bind to a local address before you can
1847 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1848 * In certain situations, you may also want to bind a socket that will be
1849 * used to initiate connections, though this is not normally required.
1851 * If @socket is a TCP socket, then @allow_reuse controls the setting
1852 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
1853 * server sockets (sockets that you will eventually call
1854 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
1855 * set this flag on a server socket may cause g_socket_bind() to return
1856 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
1857 * immediately restarted.)
1859 * If @socket is a UDP socket, then @allow_reuse determines whether or
1860 * not other UDP sockets can be bound to the same address at the same
1861 * time. In particular, you can have several UDP sockets bound to the
1862 * same address, and they will all receive all of the multicast and
1863 * broadcast packets sent to that address. (The behavior of unicast
1864 * UDP packets to an address with multiple listeners is not defined.)
1866 * Returns: %TRUE on success, %FALSE on error.
1871 g_socket_bind (GSocket *socket,
1872 GSocketAddress *address,
1873 gboolean reuse_address,
1876 struct sockaddr_storage addr;
1877 gboolean so_reuseaddr;
1879 gboolean so_reuseport;
1882 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1884 if (!check_socket (socket, error))
1887 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1890 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
1891 * sockets, but has nasty side effects we don't want for TCP
1894 * On other platforms, we set SO_REUSEPORT, if it exists, for
1895 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
1896 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
1897 * the desired semantics on UDP (as it does on Linux, although
1898 * Linux has SO_REUSEPORT too as of 3.9).
1902 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1904 so_reuseaddr = !!reuse_address;
1908 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1911 /* Ignore errors here, the only likely error is "not supported", and
1912 * this is a "best effort" thing mainly.
1914 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
1916 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
1919 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1920 g_socket_address_get_native_size (address)) < 0)
1922 int errsv = get_socket_errno ();
1924 G_IO_ERROR, socket_io_error_from_errno (errsv),
1925 _("Error binding to address: %s"), socket_strerror (errsv));
1932 #if !defined(HAVE_IF_NAMETOINDEX) && defined(G_OS_WIN32)
1934 if_nametoindex (const gchar *iface)
1936 PIP_ADAPTER_ADDRESSES addresses = NULL, p;
1937 gulong addresses_len = 0;
1941 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, NULL, &addresses_len);
1942 if (res != NO_ERROR && res != ERROR_BUFFER_OVERFLOW)
1944 if (res == ERROR_NO_DATA)
1951 addresses = g_malloc (addresses_len);
1952 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, addresses, &addresses_len);
1954 if (res != NO_ERROR)
1957 if (res == ERROR_NO_DATA)
1967 if (strcmp (p->AdapterName, iface) == 0)
1983 #define HAVE_IF_NAMETOINDEX 1
1987 g_socket_multicast_group_operation (GSocket *socket,
1988 GInetAddress *group,
1989 gboolean source_specific,
1991 gboolean join_group,
1994 const guint8 *native_addr;
1995 gint optname, result;
1997 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1998 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
1999 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2001 if (!check_socket (socket, error))
2004 native_addr = g_inet_address_to_bytes (group);
2005 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2007 #ifdef HAVE_IP_MREQN
2008 struct ip_mreqn mc_req;
2010 struct ip_mreq mc_req;
2013 memset (&mc_req, 0, sizeof (mc_req));
2014 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2016 #ifdef HAVE_IP_MREQN
2018 mc_req.imr_ifindex = if_nametoindex (iface);
2020 mc_req.imr_ifindex = 0; /* Pick any. */
2021 #elif defined(G_OS_WIN32)
2023 mc_req.imr_interface.s_addr = g_htonl (if_nametoindex (iface));
2025 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2027 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2030 if (source_specific)
2032 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2033 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2035 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2037 _("Error joining multicast group: %s") :
2038 _("Error leaving multicast group: %s"),
2039 _("No support for source-specific multicast"));
2044 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2045 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2046 &mc_req, sizeof (mc_req));
2048 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2050 struct ipv6_mreq mc_req_ipv6;
2052 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2053 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2054 #ifdef HAVE_IF_NAMETOINDEX
2056 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2059 mc_req_ipv6.ipv6mr_interface = 0;
2061 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2062 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2063 &mc_req_ipv6, sizeof (mc_req_ipv6));
2066 g_return_val_if_reached (FALSE);
2070 int errsv = get_socket_errno ();
2072 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2074 _("Error joining multicast group: %s") :
2075 _("Error leaving multicast group: %s"),
2076 socket_strerror (errsv));
2084 * g_socket_join_multicast_group:
2085 * @socket: a #GSocket.
2086 * @group: a #GInetAddress specifying the group address to join.
2087 * @iface: (allow-none): Name of the interface to use, or %NULL
2088 * @source_specific: %TRUE if source-specific multicast should be used
2089 * @error: #GError for error reporting, or %NULL to ignore.
2091 * Registers @socket to receive multicast messages sent to @group.
2092 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2093 * been bound to an appropriate interface and port with
2096 * If @iface is %NULL, the system will automatically pick an interface
2097 * to bind to based on @group.
2099 * If @source_specific is %TRUE, source-specific multicast as defined
2100 * in RFC 4604 is used. Note that on older platforms this may fail
2101 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2103 * Returns: %TRUE on success, %FALSE on error.
2108 g_socket_join_multicast_group (GSocket *socket,
2109 GInetAddress *group,
2110 gboolean source_specific,
2114 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2118 * g_socket_leave_multicast_group:
2119 * @socket: a #GSocket.
2120 * @group: a #GInetAddress specifying the group address to leave.
2121 * @iface: (allow-none): Interface used
2122 * @source_specific: %TRUE if source-specific multicast was used
2123 * @error: #GError for error reporting, or %NULL to ignore.
2125 * Removes @socket from the multicast group defined by @group, @iface,
2126 * and @source_specific (which must all have the same values they had
2127 * when you joined the group).
2129 * @socket remains bound to its address and port, and can still receive
2130 * unicast messages after calling this.
2132 * Returns: %TRUE on success, %FALSE on error.
2137 g_socket_leave_multicast_group (GSocket *socket,
2138 GInetAddress *group,
2139 gboolean source_specific,
2143 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2147 * g_socket_speaks_ipv4:
2148 * @socket: a #GSocket
2150 * Checks if a socket is capable of speaking IPv4.
2152 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2153 * and under some combinations of circumstances IPv6 sockets are also
2154 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2157 * No other types of sockets are currently considered as being capable
2160 * Returns: %TRUE if this socket can be used with IPv4.
2165 g_socket_speaks_ipv4 (GSocket *socket)
2167 switch (socket->priv->family)
2169 case G_SOCKET_FAMILY_IPV4:
2172 case G_SOCKET_FAMILY_IPV6:
2173 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2177 if (!g_socket_get_option (socket,
2178 IPPROTO_IPV6, IPV6_V6ONLY,
2195 * @socket: a #GSocket.
2196 * @cancellable: (allow-none): a %GCancellable or %NULL
2197 * @error: #GError for error reporting, or %NULL to ignore.
2199 * Accept incoming connections on a connection-based socket. This removes
2200 * the first outstanding connection request from the listening socket and
2201 * creates a #GSocket object for it.
2203 * The @socket must be bound to a local address with g_socket_bind() and
2204 * must be listening for incoming connections (g_socket_listen()).
2206 * If there are no outstanding connections then the operation will block
2207 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2208 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2210 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2211 * Free the returned object with g_object_unref().
2216 g_socket_accept (GSocket *socket,
2217 GCancellable *cancellable,
2220 GSocket *new_socket;
2223 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2225 if (!check_socket (socket, error))
2228 if (!check_timeout (socket, error))
2233 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2235 int errsv = get_socket_errno ();
2240 #ifdef WSAEWOULDBLOCK
2241 if (errsv == WSAEWOULDBLOCK)
2243 if (errsv == EWOULDBLOCK ||
2247 win32_unset_event_mask (socket, FD_ACCEPT);
2249 if (socket->priv->blocking)
2251 if (!g_socket_condition_wait (socket,
2252 G_IO_IN, cancellable, error))
2259 g_set_error (error, G_IO_ERROR,
2260 socket_io_error_from_errno (errsv),
2261 _("Error accepting connection: %s"), socket_strerror (errsv));
2267 win32_unset_event_mask (socket, FD_ACCEPT);
2271 /* The socket inherits the accepting sockets event mask and even object,
2272 we need to remove that */
2273 WSAEventSelect (ret, NULL, 0);
2279 /* We always want to set close-on-exec to protect users. If you
2280 need to so some weird inheritance to exec you can re-enable this
2281 using lower level hacks with g_socket_get_fd(). */
2282 flags = fcntl (ret, F_GETFD, 0);
2284 (flags & FD_CLOEXEC) == 0)
2286 flags |= FD_CLOEXEC;
2287 fcntl (ret, F_SETFD, flags);
2292 new_socket = g_socket_new_from_fd (ret, error);
2293 if (new_socket == NULL)
2302 new_socket->priv->protocol = socket->priv->protocol;
2309 * @socket: a #GSocket.
2310 * @address: a #GSocketAddress specifying the remote address.
2311 * @cancellable: (allow-none): a %GCancellable or %NULL
2312 * @error: #GError for error reporting, or %NULL to ignore.
2314 * Connect the socket to the specified remote address.
2316 * For connection oriented socket this generally means we attempt to make
2317 * a connection to the @address. For a connection-less socket it sets
2318 * the default address for g_socket_send() and discards all incoming datagrams
2319 * from other sources.
2321 * Generally connection oriented sockets can only connect once, but
2322 * connection-less sockets can connect multiple times to change the
2325 * If the connect call needs to do network I/O it will block, unless
2326 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2327 * and the user can be notified of the connection finishing by waiting
2328 * for the G_IO_OUT condition. The result of the connection must then be
2329 * checked with g_socket_check_connect_result().
2331 * Returns: %TRUE if connected, %FALSE on error.
2336 g_socket_connect (GSocket *socket,
2337 GSocketAddress *address,
2338 GCancellable *cancellable,
2341 struct sockaddr_storage buffer;
2343 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2345 if (!check_socket (socket, error))
2348 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2351 if (socket->priv->remote_address)
2352 g_object_unref (socket->priv->remote_address);
2353 socket->priv->remote_address = g_object_ref (address);
2357 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2358 g_socket_address_get_native_size (address)) < 0)
2360 int errsv = get_socket_errno ();
2366 if (errsv == EINPROGRESS)
2368 if (errsv == WSAEWOULDBLOCK)
2371 win32_unset_event_mask (socket, FD_CONNECT);
2373 if (socket->priv->blocking)
2375 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2377 if (g_socket_check_connect_result (socket, error))
2383 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2384 _("Connection in progress"));
2385 socket->priv->connect_pending = TRUE;
2389 g_set_error_literal (error, G_IO_ERROR,
2390 socket_io_error_from_errno (errsv),
2391 socket_strerror (errsv));
2398 win32_unset_event_mask (socket, FD_CONNECT);
2400 socket->priv->connected = TRUE;
2406 * g_socket_check_connect_result:
2407 * @socket: a #GSocket
2408 * @error: #GError for error reporting, or %NULL to ignore.
2410 * Checks and resets the pending connect error for the socket.
2411 * This is used to check for errors when g_socket_connect() is
2412 * used in non-blocking mode.
2414 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2419 g_socket_check_connect_result (GSocket *socket,
2424 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2426 if (!check_socket (socket, error))
2429 if (!check_timeout (socket, error))
2432 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
2434 g_prefix_error (error, _("Unable to get pending error: "));
2440 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2441 socket_strerror (value));
2442 if (socket->priv->remote_address)
2444 g_object_unref (socket->priv->remote_address);
2445 socket->priv->remote_address = NULL;
2450 socket->priv->connected = TRUE;
2455 * g_socket_get_available_bytes:
2456 * @socket: a #GSocket
2458 * Get the amount of data pending in the OS input buffer.
2460 * If @socket is a UDP or SCTP socket, this will return the size of
2461 * just the next packet, even if additional packets are buffered after
2464 * Note that on Windows, this function is rather inefficient in the
2465 * UDP case, and so if you know any plausible upper bound on the size
2466 * of the incoming packet, it is better to just do a
2467 * g_socket_receive() with a buffer of that size, rather than calling
2468 * g_socket_get_available_bytes() first and then doing a receive of
2469 * exactly the right size.
2471 * Returns: the number of bytes that can be read from the socket
2472 * without blocking or truncating, or -1 on error.
2477 g_socket_get_available_bytes (GSocket *socket)
2480 const gint bufsize = 64 * 1024;
2481 static guchar *buf = NULL;
2487 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2489 #if defined (SO_NREAD)
2490 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
2492 #elif !defined (G_OS_WIN32)
2493 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2496 if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
2498 if (G_UNLIKELY (g_once_init_enter (&buf)))
2499 g_once_init_leave (&buf, g_malloc (bufsize));
2501 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
2502 if (avail == -1 && get_socket_errno () == WSAEWOULDBLOCK)
2507 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
2517 * @socket: a #GSocket
2518 * @buffer: (array length=size) (element-type guint8): a buffer to
2519 * read data into (which should be at least @size bytes long).
2520 * @size: the number of bytes you want to read from the socket
2521 * @cancellable: (allow-none): a %GCancellable or %NULL
2522 * @error: #GError for error reporting, or %NULL to ignore.
2524 * Receive data (up to @size bytes) from a socket. This is mainly used by
2525 * connection-oriented sockets; it is identical to g_socket_receive_from()
2526 * with @address set to %NULL.
2528 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2529 * g_socket_receive() will always read either 0 or 1 complete messages from
2530 * the socket. If the received message is too large to fit in @buffer, then
2531 * the data beyond @size bytes will be discarded, without any explicit
2532 * indication that this has occurred.
2534 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2535 * number of bytes, up to @size. If more than @size bytes have been
2536 * received, the additional data will be returned in future calls to
2537 * g_socket_receive().
2539 * If the socket is in blocking mode the call will block until there
2540 * is some data to receive, the connection is closed, or there is an
2541 * error. If there is no data available and the socket is in
2542 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2543 * returned. To be notified when data is available, wait for the
2544 * %G_IO_IN condition.
2546 * On error -1 is returned and @error is set accordingly.
2548 * Returns: Number of bytes read, or 0 if the connection was closed by
2549 * the peer, or -1 on error
2554 g_socket_receive (GSocket *socket,
2557 GCancellable *cancellable,
2560 return g_socket_receive_with_blocking (socket, buffer, size,
2561 socket->priv->blocking,
2562 cancellable, error);
2566 * g_socket_receive_with_blocking:
2567 * @socket: a #GSocket
2568 * @buffer: (array length=size) (element-type guint8): a buffer to
2569 * read data into (which should be at least @size bytes long).
2570 * @size: the number of bytes you want to read from the socket
2571 * @blocking: whether to do blocking or non-blocking I/O
2572 * @cancellable: (allow-none): a %GCancellable or %NULL
2573 * @error: #GError for error reporting, or %NULL to ignore.
2575 * This behaves exactly the same as g_socket_receive(), except that
2576 * the choice of blocking or non-blocking behavior is determined by
2577 * the @blocking argument rather than by @socket's properties.
2579 * Returns: Number of bytes read, or 0 if the connection was closed by
2580 * the peer, or -1 on error
2585 g_socket_receive_with_blocking (GSocket *socket,
2589 GCancellable *cancellable,
2594 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2596 if (!check_socket (socket, error))
2599 if (!check_timeout (socket, error))
2602 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2607 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2609 int errsv = get_socket_errno ();
2614 #ifdef WSAEWOULDBLOCK
2615 if (errsv == WSAEWOULDBLOCK)
2617 if (errsv == EWOULDBLOCK ||
2621 win32_unset_event_mask (socket, FD_READ);
2625 if (!g_socket_condition_wait (socket,
2626 G_IO_IN, cancellable, error))
2633 win32_unset_event_mask (socket, FD_READ);
2635 g_set_error (error, G_IO_ERROR,
2636 socket_io_error_from_errno (errsv),
2637 _("Error receiving data: %s"), socket_strerror (errsv));
2641 win32_unset_event_mask (socket, FD_READ);
2650 * g_socket_receive_from:
2651 * @socket: a #GSocket
2652 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2654 * @buffer: (array length=size) (element-type guint8): a buffer to
2655 * read data into (which should be at least @size bytes long).
2656 * @size: the number of bytes you want to read from the socket
2657 * @cancellable: (allow-none): a %GCancellable or %NULL
2658 * @error: #GError for error reporting, or %NULL to ignore.
2660 * Receive data (up to @size bytes) from a socket.
2662 * If @address is non-%NULL then @address will be set equal to the
2663 * source address of the received packet.
2664 * @address is owned by the caller.
2666 * See g_socket_receive() for additional information.
2668 * Returns: Number of bytes read, or 0 if the connection was closed by
2669 * the peer, or -1 on error
2674 g_socket_receive_from (GSocket *socket,
2675 GSocketAddress **address,
2678 GCancellable *cancellable,
2686 return g_socket_receive_message (socket,
2694 /* See the comment about SIGPIPE above. */
2696 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2698 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2703 * @socket: a #GSocket
2704 * @buffer: (array length=size) (element-type guint8): the buffer
2705 * containing the data to send.
2706 * @size: the number of bytes to send
2707 * @cancellable: (allow-none): a %GCancellable or %NULL
2708 * @error: #GError for error reporting, or %NULL to ignore.
2710 * Tries to send @size bytes from @buffer on the socket. This is
2711 * mainly used by connection-oriented sockets; it is identical to
2712 * g_socket_send_to() with @address set to %NULL.
2714 * If the socket is in blocking mode the call will block until there is
2715 * space for the data in the socket queue. If there is no space available
2716 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2717 * will be returned. To be notified when space is available, wait for the
2718 * %G_IO_OUT condition. Note though that you may still receive
2719 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2720 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2721 * very common due to the way the underlying APIs work.)
2723 * On error -1 is returned and @error is set accordingly.
2725 * Returns: Number of bytes written (which may be less than @size), or -1
2731 g_socket_send (GSocket *socket,
2732 const gchar *buffer,
2734 GCancellable *cancellable,
2737 return g_socket_send_with_blocking (socket, buffer, size,
2738 socket->priv->blocking,
2739 cancellable, error);
2743 * g_socket_send_with_blocking:
2744 * @socket: a #GSocket
2745 * @buffer: (array length=size) (element-type guint8): the buffer
2746 * containing the data to send.
2747 * @size: the number of bytes to send
2748 * @blocking: whether to do blocking or non-blocking I/O
2749 * @cancellable: (allow-none): a %GCancellable or %NULL
2750 * @error: #GError for error reporting, or %NULL to ignore.
2752 * This behaves exactly the same as g_socket_send(), except that
2753 * the choice of blocking or non-blocking behavior is determined by
2754 * the @blocking argument rather than by @socket's properties.
2756 * Returns: Number of bytes written (which may be less than @size), or -1
2762 g_socket_send_with_blocking (GSocket *socket,
2763 const gchar *buffer,
2766 GCancellable *cancellable,
2771 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2773 if (!check_socket (socket, error))
2776 if (!check_timeout (socket, error))
2779 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2784 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2786 int errsv = get_socket_errno ();
2791 #ifdef WSAEWOULDBLOCK
2792 if (errsv == WSAEWOULDBLOCK)
2794 if (errsv == EWOULDBLOCK ||
2798 win32_unset_event_mask (socket, FD_WRITE);
2802 if (!g_socket_condition_wait (socket,
2803 G_IO_OUT, cancellable, error))
2810 g_set_error (error, G_IO_ERROR,
2811 socket_io_error_from_errno (errsv),
2812 _("Error sending data: %s"), socket_strerror (errsv));
2823 * @socket: a #GSocket
2824 * @address: (allow-none): a #GSocketAddress, or %NULL
2825 * @buffer: (array length=size) (element-type guint8): the buffer
2826 * containing the data to send.
2827 * @size: the number of bytes to send
2828 * @cancellable: (allow-none): a %GCancellable or %NULL
2829 * @error: #GError for error reporting, or %NULL to ignore.
2831 * Tries to send @size bytes from @buffer to @address. If @address is
2832 * %NULL then the message is sent to the default receiver (set by
2833 * g_socket_connect()).
2835 * See g_socket_send() for additional information.
2837 * Returns: Number of bytes written (which may be less than @size), or -1
2843 g_socket_send_to (GSocket *socket,
2844 GSocketAddress *address,
2845 const gchar *buffer,
2847 GCancellable *cancellable,
2855 return g_socket_send_message (socket,
2865 * g_socket_shutdown:
2866 * @socket: a #GSocket
2867 * @shutdown_read: whether to shut down the read side
2868 * @shutdown_write: whether to shut down the write side
2869 * @error: #GError for error reporting, or %NULL to ignore.
2871 * Shut down part of a full-duplex connection.
2873 * If @shutdown_read is %TRUE then the receiving side of the connection
2874 * is shut down, and further reading is disallowed.
2876 * If @shutdown_write is %TRUE then the sending side of the connection
2877 * is shut down, and further writing is disallowed.
2879 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2881 * One example where this is used is graceful disconnect for TCP connections
2882 * where you close the sending side, then wait for the other side to close
2883 * the connection, thus ensuring that the other side saw all sent data.
2885 * Returns: %TRUE on success, %FALSE on error
2890 g_socket_shutdown (GSocket *socket,
2891 gboolean shutdown_read,
2892 gboolean shutdown_write,
2897 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2899 if (!check_socket (socket, error))
2903 if (!shutdown_read && !shutdown_write)
2907 if (shutdown_read && shutdown_write)
2909 else if (shutdown_read)
2914 if (shutdown_read && shutdown_write)
2916 else if (shutdown_read)
2922 if (shutdown (socket->priv->fd, how) != 0)
2924 int errsv = get_socket_errno ();
2925 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2926 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2930 if (shutdown_read && shutdown_write)
2931 socket->priv->connected = FALSE;
2938 * @socket: a #GSocket
2939 * @error: #GError for error reporting, or %NULL to ignore.
2941 * Closes the socket, shutting down any active connection.
2943 * Closing a socket does not wait for all outstanding I/O operations
2944 * to finish, so the caller should not rely on them to be guaranteed
2945 * to complete even if the close returns with no error.
2947 * Once the socket is closed, all other operations will return
2948 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2951 * Sockets will be automatically closed when the last reference
2952 * is dropped, but you might want to call this function to make sure
2953 * resources are released as early as possible.
2955 * Beware that due to the way that TCP works, it is possible for
2956 * recently-sent data to be lost if either you close a socket while the
2957 * %G_IO_IN condition is set, or else if the remote connection tries to
2958 * send something to you after you close the socket but before it has
2959 * finished reading all of the data you sent. There is no easy generic
2960 * way to avoid this problem; the easiest fix is to design the network
2961 * protocol such that the client will never send data "out of turn".
2962 * Another solution is for the server to half-close the connection by
2963 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2964 * and then wait for the client to notice this and close its side of the
2965 * connection, after which the server can safely call g_socket_close().
2966 * (This is what #GTcpConnection does if you call
2967 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2968 * only works if the client will close its connection after the server
2971 * Returns: %TRUE on success, %FALSE on error
2976 g_socket_close (GSocket *socket,
2981 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2983 if (socket->priv->closed)
2984 return TRUE; /* Multiple close not an error */
2986 if (!check_socket (socket, error))
2992 res = closesocket (socket->priv->fd);
2994 res = close (socket->priv->fd);
2998 int errsv = get_socket_errno ();
3003 g_set_error (error, G_IO_ERROR,
3004 socket_io_error_from_errno (errsv),
3005 _("Error closing socket: %s"),
3006 socket_strerror (errsv));
3012 socket->priv->connected = FALSE;
3013 socket->priv->closed = TRUE;
3014 if (socket->priv->remote_address)
3016 g_object_unref (socket->priv->remote_address);
3017 socket->priv->remote_address = NULL;
3024 * g_socket_is_closed:
3025 * @socket: a #GSocket
3027 * Checks whether a socket is closed.
3029 * Returns: %TRUE if socket is closed, %FALSE otherwise
3034 g_socket_is_closed (GSocket *socket)
3036 return socket->priv->closed;
3040 /* Broken source, used on errors */
3042 broken_dispatch (GSource *source,
3043 GSourceFunc callback,
3049 static GSourceFuncs broken_funcs =
3058 network_events_for_condition (GIOCondition condition)
3062 if (condition & G_IO_IN)
3063 event_mask |= (FD_READ | FD_ACCEPT);
3064 if (condition & G_IO_OUT)
3065 event_mask |= (FD_WRITE | FD_CONNECT);
3066 event_mask |= FD_CLOSE;
3072 ensure_event (GSocket *socket)
3074 if (socket->priv->event == WSA_INVALID_EVENT)
3075 socket->priv->event = WSACreateEvent();
3079 update_select_events (GSocket *socket)
3086 ensure_event (socket);
3089 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3092 event_mask |= network_events_for_condition (*ptr);
3095 if (event_mask != socket->priv->selected_events)
3097 /* If no events selected, disable event so we can unset
3100 if (event_mask == 0)
3103 event = socket->priv->event;
3105 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3106 socket->priv->selected_events = event_mask;
3111 add_condition_watch (GSocket *socket,
3112 GIOCondition *condition)
3114 g_mutex_lock (&socket->priv->win32_source_lock);
3115 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3117 socket->priv->requested_conditions =
3118 g_list_prepend (socket->priv->requested_conditions, condition);
3120 update_select_events (socket);
3121 g_mutex_unlock (&socket->priv->win32_source_lock);
3125 remove_condition_watch (GSocket *socket,
3126 GIOCondition *condition)
3128 g_mutex_lock (&socket->priv->win32_source_lock);
3129 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3131 socket->priv->requested_conditions =
3132 g_list_remove (socket->priv->requested_conditions, condition);
3134 update_select_events (socket);
3135 g_mutex_unlock (&socket->priv->win32_source_lock);
3139 update_condition (GSocket *socket)
3141 WSANETWORKEVENTS events;
3142 GIOCondition condition;
3144 if (WSAEnumNetworkEvents (socket->priv->fd,
3145 socket->priv->event,
3148 socket->priv->current_events |= events.lNetworkEvents;
3149 if (events.lNetworkEvents & FD_WRITE &&
3150 events.iErrorCode[FD_WRITE_BIT] != 0)
3151 socket->priv->current_errors |= FD_WRITE;
3152 if (events.lNetworkEvents & FD_CONNECT &&
3153 events.iErrorCode[FD_CONNECT_BIT] != 0)
3154 socket->priv->current_errors |= FD_CONNECT;
3158 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3159 condition |= G_IO_IN;
3161 if (socket->priv->current_events & FD_CLOSE)
3163 int r, errsv, buffer;
3165 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3167 errsv = get_socket_errno ();
3170 (r < 0 && errsv == WSAENOTCONN))
3171 condition |= G_IO_IN;
3173 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3174 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3175 condition |= G_IO_HUP;
3177 condition |= G_IO_ERR;
3180 if (socket->priv->closed)
3181 condition |= G_IO_HUP;
3183 /* Never report both G_IO_OUT and HUP, these are
3184 mutually exclusive (can't write to a closed socket) */
3185 if ((condition & G_IO_HUP) == 0 &&
3186 socket->priv->current_events & FD_WRITE)
3188 if (socket->priv->current_errors & FD_WRITE)
3189 condition |= G_IO_ERR;
3191 condition |= G_IO_OUT;
3195 if (socket->priv->current_events & FD_CONNECT)
3197 if (socket->priv->current_errors & FD_CONNECT)
3198 condition |= (G_IO_HUP | G_IO_ERR);
3200 condition |= G_IO_OUT;
3216 GIOCondition condition;
3221 socket_source_prepare_win32 (GSource *source,
3224 GSocketSource *socket_source = (GSocketSource *)source;
3228 return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3232 socket_source_check_win32 (GSource *source)
3236 return socket_source_prepare_win32 (source, &timeout);
3241 socket_source_dispatch (GSource *source,
3242 GSourceFunc callback,
3245 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3246 GSocketSource *socket_source = (GSocketSource *)source;
3247 GSocket *socket = socket_source->socket;
3253 events = update_condition (socket_source->socket);
3255 events = g_source_query_unix_fd (source, socket_source->fd_tag);
3258 timeout = g_source_get_ready_time (source);
3259 if (timeout >= 0 && timeout < g_source_get_time (source))
3261 socket->priv->timed_out = TRUE;
3262 events |= (G_IO_IN | G_IO_OUT);
3265 ret = (*func) (socket, events & socket_source->condition, user_data);
3267 if (socket->priv->timeout)
3268 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3270 g_source_set_ready_time (source, -1);
3276 socket_source_finalize (GSource *source)
3278 GSocketSource *socket_source = (GSocketSource *)source;
3281 socket = socket_source->socket;
3284 remove_condition_watch (socket, &socket_source->condition);
3287 g_object_unref (socket);
3291 socket_source_closure_callback (GSocket *socket,
3292 GIOCondition condition,
3295 GClosure *closure = data;
3297 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3298 GValue result_value = G_VALUE_INIT;
3301 g_value_init (&result_value, G_TYPE_BOOLEAN);
3303 g_value_init (¶ms[0], G_TYPE_SOCKET);
3304 g_value_set_object (¶ms[0], socket);
3305 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
3306 g_value_set_flags (¶ms[1], condition);
3308 g_closure_invoke (closure, &result_value, 2, params, NULL);
3310 result = g_value_get_boolean (&result_value);
3311 g_value_unset (&result_value);
3312 g_value_unset (¶ms[0]);
3313 g_value_unset (¶ms[1]);
3318 static GSourceFuncs socket_source_funcs =
3321 socket_source_prepare_win32,
3322 socket_source_check_win32,
3324 NULL, NULL, /* check, prepare */
3326 socket_source_dispatch,
3327 socket_source_finalize,
3328 (GSourceFunc)socket_source_closure_callback,
3332 socket_source_new (GSocket *socket,
3333 GIOCondition condition,
3334 GCancellable *cancellable)
3337 GSocketSource *socket_source;
3340 ensure_event (socket);
3342 if (socket->priv->event == WSA_INVALID_EVENT)
3344 g_warning ("Failed to create WSAEvent");
3345 return g_source_new (&broken_funcs, sizeof (GSource));
3349 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
3351 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3352 g_source_set_name (source, "GSocket");
3353 socket_source = (GSocketSource *)source;
3355 socket_source->socket = g_object_ref (socket);
3356 socket_source->condition = condition;
3360 GSource *cancellable_source;
3362 cancellable_source = g_cancellable_source_new (cancellable);
3363 g_source_add_child_source (source, cancellable_source);
3364 g_source_set_dummy_callback (cancellable_source);
3365 g_source_unref (cancellable_source);
3369 add_condition_watch (socket, &socket_source->condition);
3370 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3371 socket_source->pollfd.events = condition;
3372 socket_source->pollfd.revents = 0;
3373 g_source_add_poll (source, &socket_source->pollfd);
3375 socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
3378 if (socket->priv->timeout)
3379 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3381 g_source_set_ready_time (source, -1);
3387 * g_socket_create_source: (skip)
3388 * @socket: a #GSocket
3389 * @condition: a #GIOCondition mask to monitor
3390 * @cancellable: (allow-none): a %GCancellable or %NULL
3392 * Creates a #GSource that can be attached to a %GMainContext to monitor
3393 * for the availability of the specified @condition on the socket. The #GSource
3394 * keeps a reference to the @socket.
3396 * The callback on the source is of the #GSocketSourceFunc type.
3398 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3399 * these conditions will always be reported output if they are true.
3401 * @cancellable if not %NULL can be used to cancel the source, which will
3402 * cause the source to trigger, reporting the current condition (which
3403 * is likely 0 unless cancellation happened at the same time as a
3404 * condition change). You can check for this in the callback using
3405 * g_cancellable_is_cancelled().
3407 * If @socket has a timeout set, and it is reached before @condition
3408 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3409 * %G_IO_OUT depending on @condition. However, @socket will have been
3410 * marked as having had a timeout, and so the next #GSocket I/O method
3411 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3413 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3418 g_socket_create_source (GSocket *socket,
3419 GIOCondition condition,
3420 GCancellable *cancellable)
3422 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3424 return socket_source_new (socket, condition, cancellable);
3428 * g_socket_condition_check:
3429 * @socket: a #GSocket
3430 * @condition: a #GIOCondition mask to check
3432 * Checks on the readiness of @socket to perform operations.
3433 * The operations specified in @condition are checked for and masked
3434 * against the currently-satisfied conditions on @socket. The result
3437 * Note that on Windows, it is possible for an operation to return
3438 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3439 * g_socket_condition_check() has claimed that the socket is ready for
3440 * writing. Rather than calling g_socket_condition_check() and then
3441 * writing to the socket if it succeeds, it is generally better to
3442 * simply try writing to the socket right away, and try again later if
3443 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3445 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3446 * these conditions will always be set in the output if they are true.
3448 * This call never blocks.
3450 * Returns: the @GIOCondition mask of the current state
3455 g_socket_condition_check (GSocket *socket,
3456 GIOCondition condition)
3458 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3460 if (!check_socket (socket, NULL))
3465 GIOCondition current_condition;
3467 condition |= G_IO_ERR | G_IO_HUP;
3469 add_condition_watch (socket, &condition);
3470 current_condition = update_condition (socket);
3471 remove_condition_watch (socket, &condition);
3472 return condition & current_condition;
3478 poll_fd.fd = socket->priv->fd;
3479 poll_fd.events = condition;
3480 poll_fd.revents = 0;
3483 result = g_poll (&poll_fd, 1, 0);
3484 while (result == -1 && get_socket_errno () == EINTR);
3486 return poll_fd.revents;
3492 * g_socket_condition_wait:
3493 * @socket: a #GSocket
3494 * @condition: a #GIOCondition mask to wait for
3495 * @cancellable: (allow-none): a #GCancellable, or %NULL
3496 * @error: a #GError pointer, or %NULL
3498 * Waits for @condition to become true on @socket. When the condition
3499 * is met, %TRUE is returned.
3501 * If @cancellable is cancelled before the condition is met, or if the
3502 * socket has a timeout set and it is reached before the condition is
3503 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3504 * the appropriate value (%G_IO_ERROR_CANCELLED or
3505 * %G_IO_ERROR_TIMED_OUT).
3507 * See also g_socket_condition_timed_wait().
3509 * Returns: %TRUE if the condition was met, %FALSE otherwise
3514 g_socket_condition_wait (GSocket *socket,
3515 GIOCondition condition,
3516 GCancellable *cancellable,
3519 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3521 return g_socket_condition_timed_wait (socket, condition, -1,
3522 cancellable, error);
3526 * g_socket_condition_timed_wait:
3527 * @socket: a #GSocket
3528 * @condition: a #GIOCondition mask to wait for
3529 * @timeout: the maximum time (in microseconds) to wait, or -1
3530 * @cancellable: (allow-none): a #GCancellable, or %NULL
3531 * @error: a #GError pointer, or %NULL
3533 * Waits for up to @timeout microseconds for @condition to become true
3534 * on @socket. If the condition is met, %TRUE is returned.
3536 * If @cancellable is cancelled before the condition is met, or if
3537 * @timeout (or the socket's #GSocket:timeout) is reached before the
3538 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3539 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3540 * %G_IO_ERROR_TIMED_OUT).
3542 * If you don't want a timeout, use g_socket_condition_wait().
3543 * (Alternatively, you can pass -1 for @timeout.)
3545 * Note that although @timeout is in microseconds for consistency with
3546 * other GLib APIs, this function actually only has millisecond
3547 * resolution, and the behavior is undefined if @timeout is not an
3548 * exact number of milliseconds.
3550 * Returns: %TRUE if the condition was met, %FALSE otherwise
3555 g_socket_condition_timed_wait (GSocket *socket,
3556 GIOCondition condition,
3558 GCancellable *cancellable,
3563 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3565 if (!check_socket (socket, error))
3568 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3571 if (socket->priv->timeout &&
3572 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3573 timeout = socket->priv->timeout * 1000;
3574 else if (timeout != -1)
3575 timeout = timeout / 1000;
3577 start_time = g_get_monotonic_time ();
3581 GIOCondition current_condition;
3587 /* Always check these */
3588 condition |= G_IO_ERR | G_IO_HUP;
3590 add_condition_watch (socket, &condition);
3593 events[num_events++] = socket->priv->event;
3595 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3596 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3599 timeout = WSA_INFINITE;
3601 current_condition = update_condition (socket);
3602 while ((condition & current_condition) == 0)
3604 res = WSAWaitForMultipleEvents (num_events, events,
3605 FALSE, timeout, FALSE);
3606 if (res == WSA_WAIT_FAILED)
3608 int errsv = get_socket_errno ();
3610 g_set_error (error, G_IO_ERROR,
3611 socket_io_error_from_errno (errsv),
3612 _("Waiting for socket condition: %s"),
3613 socket_strerror (errsv));
3616 else if (res == WSA_WAIT_TIMEOUT)
3618 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3619 _("Socket I/O timed out"));
3623 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3626 current_condition = update_condition (socket);
3628 if (timeout != WSA_INFINITE)
3630 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3635 remove_condition_watch (socket, &condition);
3637 g_cancellable_release_fd (cancellable);
3639 return (condition & current_condition) != 0;
3647 poll_fd[0].fd = socket->priv->fd;
3648 poll_fd[0].events = condition;
3651 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3656 result = g_poll (poll_fd, num, timeout);
3657 if (result != -1 || errno != EINTR)
3662 timeout -= (g_get_monotonic_time () - start_time) / 1000;
3669 g_cancellable_release_fd (cancellable);
3673 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3674 _("Socket I/O timed out"));
3678 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3684 * g_socket_send_message:
3685 * @socket: a #GSocket
3686 * @address: (allow-none): a #GSocketAddress, or %NULL
3687 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3688 * @num_vectors: the number of elements in @vectors, or -1
3689 * @messages: (array length=num_messages) (allow-none): a pointer to an
3690 * array of #GSocketControlMessages, or %NULL.
3691 * @num_messages: number of elements in @messages, or -1.
3692 * @flags: an int containing #GSocketMsgFlags flags
3693 * @cancellable: (allow-none): a %GCancellable or %NULL
3694 * @error: #GError for error reporting, or %NULL to ignore.
3696 * Send data to @address on @socket. This is the most complicated and
3697 * fully-featured version of this call. For easier use, see
3698 * g_socket_send() and g_socket_send_to().
3700 * If @address is %NULL then the message is sent to the default receiver
3701 * (set by g_socket_connect()).
3703 * @vectors must point to an array of #GOutputVector structs and
3704 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3705 * then @vectors is assumed to be terminated by a #GOutputVector with a
3706 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3707 * that the sent data will be gathered from. Using multiple
3708 * #GOutputVectors is more memory-efficient than manually copying
3709 * data from multiple sources into a single buffer, and more
3710 * network-efficient than making multiple calls to g_socket_send().
3712 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3713 * #GSocketControlMessage instances. These correspond to the control
3714 * messages to be sent on the socket.
3715 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3718 * @flags modify how the message is sent. The commonly available arguments
3719 * for this are available in the #GSocketMsgFlags enum, but the
3720 * values there are the same as the system values, and the flags
3721 * are passed in as-is, so you can pass in system-specific flags too.
3723 * If the socket is in blocking mode the call will block until there is
3724 * space for the data in the socket queue. If there is no space available
3725 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3726 * will be returned. To be notified when space is available, wait for the
3727 * %G_IO_OUT condition. Note though that you may still receive
3728 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3729 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3730 * very common due to the way the underlying APIs work.)
3732 * On error -1 is returned and @error is set accordingly.
3734 * Returns: Number of bytes written (which may be less than @size), or -1
3740 g_socket_send_message (GSocket *socket,
3741 GSocketAddress *address,
3742 GOutputVector *vectors,
3744 GSocketControlMessage **messages,
3747 GCancellable *cancellable,
3750 GOutputVector one_vector;
3753 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3754 g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), -1);
3755 g_return_val_if_fail (num_vectors == 0 || vectors != NULL, -1);
3756 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
3757 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
3758 g_return_val_if_fail (error == NULL || *error == NULL, -1);
3760 if (!check_socket (socket, error))
3763 if (!check_timeout (socket, error))
3766 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3769 if (num_vectors == -1)
3771 for (num_vectors = 0;
3772 vectors[num_vectors].buffer != NULL;
3777 if (num_messages == -1)
3779 for (num_messages = 0;
3780 messages != NULL && messages[num_messages] != NULL;
3785 if (num_vectors == 0)
3789 one_vector.buffer = &zero;
3790 one_vector.size = 1;
3792 vectors = &one_vector;
3805 msg.msg_namelen = g_socket_address_get_native_size (address);
3806 msg.msg_name = g_alloca (msg.msg_namelen);
3807 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3812 msg.msg_name = NULL;
3813 msg.msg_namelen = 0;
3818 /* this entire expression will be evaluated at compile time */
3819 if (sizeof *msg.msg_iov == sizeof *vectors &&
3820 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3821 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3822 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3823 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3824 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3825 G_STRUCT_OFFSET (GOutputVector, size))
3826 /* ABI is compatible */
3828 msg.msg_iov = (struct iovec *) vectors;
3829 msg.msg_iovlen = num_vectors;
3832 /* ABI is incompatible */
3836 msg.msg_iov = g_newa (struct iovec, num_vectors);
3837 for (i = 0; i < num_vectors; i++)
3839 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3840 msg.msg_iov[i].iov_len = vectors[i].size;
3842 msg.msg_iovlen = num_vectors;
3848 struct cmsghdr *cmsg;
3851 msg.msg_controllen = 0;
3852 for (i = 0; i < num_messages; i++)
3853 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3855 if (msg.msg_controllen == 0)
3856 msg.msg_control = NULL;
3859 msg.msg_control = g_alloca (msg.msg_controllen);
3860 memset (msg.msg_control, '\0', msg.msg_controllen);
3863 cmsg = CMSG_FIRSTHDR (&msg);
3864 for (i = 0; i < num_messages; i++)
3866 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3867 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3868 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3869 g_socket_control_message_serialize (messages[i],
3871 cmsg = CMSG_NXTHDR (&msg, cmsg);
3873 g_assert (cmsg == NULL);
3878 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3881 int errsv = get_socket_errno ();
3886 if (socket->priv->blocking &&
3887 (errsv == EWOULDBLOCK ||
3890 if (!g_socket_condition_wait (socket,
3891 G_IO_OUT, cancellable, error))
3897 g_set_error (error, G_IO_ERROR,
3898 socket_io_error_from_errno (errsv),
3899 _("Error sending message: %s"), socket_strerror (errsv));
3910 struct sockaddr_storage addr;
3917 /* Win32 doesn't support control messages.
3918 Actually this is possible for raw and datagram sockets
3919 via WSASendMessage on Vista or later, but that doesn't
3921 if (num_messages != 0)
3923 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3924 _("GSocketControlMessage not supported on Windows"));
3929 bufs = g_newa (WSABUF, num_vectors);
3930 for (i = 0; i < num_vectors; i++)
3932 bufs[i].buf = (char *)vectors[i].buffer;
3933 bufs[i].len = (gulong)vectors[i].size;
3937 addrlen = 0; /* Avoid warning */
3940 addrlen = g_socket_address_get_native_size (address);
3941 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3948 result = WSASendTo (socket->priv->fd,
3951 (const struct sockaddr *)&addr, addrlen,
3954 result = WSASend (socket->priv->fd,
3961 int errsv = get_socket_errno ();
3963 if (errsv == WSAEINTR)
3966 if (errsv == WSAEWOULDBLOCK)
3968 win32_unset_event_mask (socket, FD_WRITE);
3970 if (socket->priv->blocking)
3972 if (!g_socket_condition_wait (socket,
3973 G_IO_OUT, cancellable, error))
3980 g_set_error (error, G_IO_ERROR,
3981 socket_io_error_from_errno (errsv),
3982 _("Error sending message: %s"), socket_strerror (errsv));
3995 * g_socket_send_messages:
3996 * @socket: a #GSocket
3997 * @messages: (array length=num_messages): an array of #GOutputMessage structs
3998 * @num_messages: the number of elements in @messages
3999 * @flags: an int containing #GSocketMsgFlags flags
4000 * @cancellable: (allow-none): a %GCancellable or %NULL
4001 * @error: #GError for error reporting, or %NULL to ignore.
4003 * Send multiple data messages from @socket in one go. This is the most
4004 * complicated and fully-featured version of this call. For easier use, see
4005 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
4007 * @messages must point to an array of #GOutputMessage structs and
4008 * @num_messages must be the length of this array. Each #GOutputMessage
4009 * contains an address to send the data to, and a pointer to an array of
4010 * #GOutputVector structs to describe the buffers that the data to be sent
4011 * for each message will be gathered from. Using multiple #GOutputVectors is
4012 * more memory-efficient than manually copying data from multiple sources
4013 * into a single buffer, and more network-efficient than making multiple
4014 * calls to g_socket_send(). Sending multiple messages in one go avoids the
4015 * overhead of making a lot of syscalls in scenarios where a lot of data
4016 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
4017 * or where the same data needs to be sent to multiple recipients.
4019 * @flags modify how the message is sent. The commonly available arguments
4020 * for this are available in the #GSocketMsgFlags enum, but the
4021 * values there are the same as the system values, and the flags
4022 * are passed in as-is, so you can pass in system-specific flags too.
4024 * If the socket is in blocking mode the call will block until there is
4025 * space for all the data in the socket queue. If there is no space available
4026 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4027 * will be returned if no data was written at all, otherwise the number of
4028 * messages sent will be returned. To be notified when space is available,
4029 * wait for the %G_IO_OUT condition. Note though that you may still receive
4030 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4031 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4032 * very common due to the way the underlying APIs work.)
4034 * On error -1 is returned and @error is set accordingly.
4036 * Returns: number of messages sent, or -1 on error. Note that the number of
4037 * messages sent may be smaller than @num_messages if the socket is
4038 * non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
4039 * in which case the caller may re-try to send the remaining messages.
4044 g_socket_send_messages (GSocket *socket,
4045 GOutputMessage *messages,
4048 GCancellable *cancellable,
4051 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4052 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
4053 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
4054 g_return_val_if_fail (error == NULL || *error == NULL, -1);
4056 if (!check_socket (socket, error))
4059 if (!check_timeout (socket, error))
4062 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4065 if (num_messages == 0)
4068 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
4070 struct mmsghdr *msgvec;
4071 gint i, num_sent, result, max_sent;
4074 #define MAX_NUM_MESSAGES UIO_MAXIOV
4076 #define MAX_NUM_MESSAGES 1024
4079 if (num_messages > MAX_NUM_MESSAGES)
4080 num_messages = MAX_NUM_MESSAGES;
4082 msgvec = g_newa (struct mmsghdr, num_messages);
4084 for (i = 0; i < num_messages; ++i)
4086 GOutputMessage *msg = &messages[i];
4087 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
4089 msgvec[i].msg_len = 0;
4091 msg_hdr->msg_flags = 0;
4094 if (i > 0 && msg->address == messages[i-1].address)
4096 msg_hdr->msg_name = msgvec[i-1].msg_hdr.msg_name;
4097 msg_hdr->msg_namelen = msgvec[i-1].msg_hdr.msg_namelen;
4099 else if (msg->address)
4101 msg_hdr->msg_namelen = g_socket_address_get_native_size (msg->address);
4102 msg_hdr->msg_name = g_alloca (msg_hdr->msg_namelen);
4103 if (!g_socket_address_to_native (msg->address, msg_hdr->msg_name, msg_hdr->msg_namelen, error))
4108 msg_hdr->msg_name = NULL;
4109 msg_hdr->msg_namelen = 0;
4114 /* this entire expression will be evaluated at compile time */
4115 if (sizeof (struct iovec) == sizeof (GOutputVector) &&
4116 sizeof msg_hdr->msg_iov->iov_base == sizeof msg->vectors->buffer &&
4117 G_STRUCT_OFFSET (struct iovec, iov_base) ==
4118 G_STRUCT_OFFSET (GOutputVector, buffer) &&
4119 sizeof msg_hdr->msg_iov->iov_len == sizeof msg->vectors->size &&
4120 G_STRUCT_OFFSET (struct iovec, iov_len) ==
4121 G_STRUCT_OFFSET (GOutputVector, size))
4122 /* ABI is compatible */
4124 msg_hdr->msg_iov = (struct iovec *) msg->vectors;
4125 msg_hdr->msg_iovlen = msg->num_vectors;
4128 /* ABI is incompatible */
4132 msg_hdr->msg_iov = g_newa (struct iovec, msg->num_vectors);
4133 for (j = 0; j < msg->num_vectors; j++)
4135 msg_hdr->msg_iov[j].iov_base = (void *) msg->vectors[j].buffer;
4136 msg_hdr->msg_iov[j].iov_len = msg->vectors[j].size;
4138 msg_hdr->msg_iovlen = msg->num_vectors;
4144 struct cmsghdr *cmsg;
4147 msg_hdr->msg_controllen = 0;
4148 for (j = 0; j < msg->num_control_messages; j++)
4149 msg_hdr->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (msg->control_messages[j]));
4151 if (msg_hdr->msg_controllen == 0)
4152 msg_hdr->msg_control = NULL;
4155 msg_hdr->msg_control = g_alloca (msg_hdr->msg_controllen);
4156 memset (msg_hdr->msg_control, '\0', msg_hdr->msg_controllen);
4159 cmsg = CMSG_FIRSTHDR (msg_hdr);
4160 for (j = 0; j < msg->num_control_messages; j++)
4162 GSocketControlMessage *cm = msg->control_messages[j];
4164 cmsg->cmsg_level = g_socket_control_message_get_level (cm);
4165 cmsg->cmsg_type = g_socket_control_message_get_msg_type (cm);
4166 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (cm));
4167 g_socket_control_message_serialize (cm, CMSG_DATA (cmsg));
4168 cmsg = CMSG_NXTHDR (msg_hdr, cmsg);
4170 g_assert (cmsg == NULL);
4174 num_sent = result = 0;
4175 max_sent = num_messages;
4176 while (num_sent < num_messages)
4180 if (socket->priv->blocking &&
4181 !g_socket_condition_wait (socket,
4182 G_IO_OUT, cancellable, error))
4185 ret = sendmmsg (socket->priv->fd, msgvec + num_sent, num_messages - num_sent,
4186 flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4190 int errsv = get_socket_errno ();
4195 if (socket->priv->blocking &&
4196 (errsv == EWOULDBLOCK ||
4201 (errsv == EWOULDBLOCK ||
4204 max_sent = num_sent;
4208 g_set_error (error, G_IO_ERROR,
4209 socket_io_error_from_errno (errsv),
4210 _("Error sending message: %s"), socket_strerror (errsv));
4212 /* we have to iterate over all messages below now, because we don't
4213 * know where between num_sent and num_messages the error occured */
4214 max_sent = num_messages;
4224 for (i = 0; i < max_sent; ++i)
4225 messages[i].bytes_sent = msgvec[i].msg_len;
4234 for (i = 0; i < num_messages; ++i)
4236 GOutputMessage *msg = &messages[i];
4237 GError *msg_error = NULL;
4239 result = g_socket_send_message (socket, msg->address,
4240 msg->vectors, msg->num_vectors,
4241 msg->control_messages,
4242 msg->num_control_messages,
4243 flags, cancellable, &msg_error);
4247 /* if we couldn't send all messages, just return how many we did
4248 * manage to send, provided we managed to send at least one */
4249 if (msg_error->code == G_IO_ERROR_WOULD_BLOCK && i > 0)
4251 g_error_free (msg_error);
4256 g_propagate_error (error, msg_error);
4261 msg->bytes_sent = result;
4269 static GSocketAddress *
4270 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
4272 GSocketAddress *saddr;
4274 guint64 oldest_time = G_MAXUINT64;
4275 gint oldest_index = 0;
4277 if (native_len <= 0)
4281 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
4283 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
4284 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
4285 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
4290 if (tmp_native_len != native_len)
4293 if (memcmp (tmp_native, native, native_len) == 0)
4295 saddr = g_object_ref (tmp);
4296 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
4300 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
4302 oldest_time = socket->priv->recv_addr_cache[i].last_used;
4307 saddr = g_socket_address_new_from_native (native, native_len);
4309 if (socket->priv->recv_addr_cache[oldest_index].addr)
4311 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
4312 g_free (socket->priv->recv_addr_cache[oldest_index].native);
4315 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
4316 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
4317 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
4318 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
4324 * g_socket_receive_message:
4325 * @socket: a #GSocket
4326 * @address: (out) (allow-none): a pointer to a #GSocketAddress
4328 * @vectors: (array length=num_vectors): an array of #GInputVector structs
4329 * @num_vectors: the number of elements in @vectors, or -1
4330 * @messages: (array length=num_messages) (allow-none): a pointer which
4331 * may be filled with an array of #GSocketControlMessages, or %NULL
4332 * @num_messages: a pointer which will be filled with the number of
4333 * elements in @messages, or %NULL
4334 * @flags: a pointer to an int containing #GSocketMsgFlags flags
4335 * @cancellable: (allow-none): a %GCancellable or %NULL
4336 * @error: a #GError pointer, or %NULL
4338 * Receive data from a socket. This is the most complicated and
4339 * fully-featured version of this call. For easier use, see
4340 * g_socket_receive() and g_socket_receive_from().
4342 * If @address is non-%NULL then @address will be set equal to the
4343 * source address of the received packet.
4344 * @address is owned by the caller.
4346 * @vector must point to an array of #GInputVector structs and
4347 * @num_vectors must be the length of this array. These structs
4348 * describe the buffers that received data will be scattered into.
4349 * If @num_vectors is -1, then @vectors is assumed to be terminated
4350 * by a #GInputVector with a %NULL buffer pointer.
4352 * As a special case, if @num_vectors is 0 (in which case, @vectors
4353 * may of course be %NULL), then a single byte is received and
4354 * discarded. This is to facilitate the common practice of sending a
4355 * single '\0' byte for the purposes of transferring ancillary data.
4357 * @messages, if non-%NULL, will be set to point to a newly-allocated
4358 * array of #GSocketControlMessage instances or %NULL if no such
4359 * messages was received. These correspond to the control messages
4360 * received from the kernel, one #GSocketControlMessage per message
4361 * from the kernel. This array is %NULL-terminated and must be freed
4362 * by the caller using g_free() after calling g_object_unref() on each
4363 * element. If @messages is %NULL, any control messages received will
4366 * @num_messages, if non-%NULL, will be set to the number of control
4367 * messages received.
4369 * If both @messages and @num_messages are non-%NULL, then
4370 * @num_messages gives the number of #GSocketControlMessage instances
4371 * in @messages (ie: not including the %NULL terminator).
4373 * @flags is an in/out parameter. The commonly available arguments
4374 * for this are available in the #GSocketMsgFlags enum, but the
4375 * values there are the same as the system values, and the flags
4376 * are passed in as-is, so you can pass in system-specific flags too
4377 * (and g_socket_receive_message() may pass system-specific flags out).
4379 * As with g_socket_receive(), data may be discarded if @socket is
4380 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
4381 * provide enough buffer space to read a complete message. You can pass
4382 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
4383 * removing it from the receive queue, but there is no portable way to find
4384 * out the length of the message other than by reading it into a
4385 * sufficiently-large buffer.
4387 * If the socket is in blocking mode the call will block until there
4388 * is some data to receive, the connection is closed, or there is an
4389 * error. If there is no data available and the socket is in
4390 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
4391 * returned. To be notified when data is available, wait for the
4392 * %G_IO_IN condition.
4394 * On error -1 is returned and @error is set accordingly.
4396 * Returns: Number of bytes read, or 0 if the connection was closed by
4397 * the peer, or -1 on error
4402 g_socket_receive_message (GSocket *socket,
4403 GSocketAddress **address,
4404 GInputVector *vectors,
4406 GSocketControlMessage ***messages,
4409 GCancellable *cancellable,
4412 GInputVector one_vector;
4415 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4417 if (!check_socket (socket, error))
4420 if (!check_timeout (socket, error))
4423 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4426 if (num_vectors == -1)
4428 for (num_vectors = 0;
4429 vectors[num_vectors].buffer != NULL;
4434 if (num_vectors == 0)
4436 one_vector.buffer = &one_byte;
4437 one_vector.size = 1;
4439 vectors = &one_vector;
4446 struct sockaddr_storage one_sockaddr;
4451 msg.msg_name = &one_sockaddr;
4452 msg.msg_namelen = sizeof (struct sockaddr_storage);
4456 msg.msg_name = NULL;
4457 msg.msg_namelen = 0;
4461 /* this entire expression will be evaluated at compile time */
4462 if (sizeof *msg.msg_iov == sizeof *vectors &&
4463 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4464 G_STRUCT_OFFSET (struct iovec, iov_base) ==
4465 G_STRUCT_OFFSET (GInputVector, buffer) &&
4466 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4467 G_STRUCT_OFFSET (struct iovec, iov_len) ==
4468 G_STRUCT_OFFSET (GInputVector, size))
4469 /* ABI is compatible */
4471 msg.msg_iov = (struct iovec *) vectors;
4472 msg.msg_iovlen = num_vectors;
4475 /* ABI is incompatible */
4479 msg.msg_iov = g_newa (struct iovec, num_vectors);
4480 for (i = 0; i < num_vectors; i++)
4482 msg.msg_iov[i].iov_base = vectors[i].buffer;
4483 msg.msg_iov[i].iov_len = vectors[i].size;
4485 msg.msg_iovlen = num_vectors;
4489 msg.msg_control = g_alloca (2048);
4490 msg.msg_controllen = 2048;
4494 msg.msg_flags = *flags;
4498 /* We always set the close-on-exec flag so we don't leak file
4499 * descriptors into child processes. Note that gunixfdmessage.c
4500 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4502 #ifdef MSG_CMSG_CLOEXEC
4503 msg.msg_flags |= MSG_CMSG_CLOEXEC;
4509 if (socket->priv->blocking &&
4510 !g_socket_condition_wait (socket,
4511 G_IO_IN, cancellable, error))
4514 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4515 #ifdef MSG_CMSG_CLOEXEC
4516 if (result < 0 && get_socket_errno () == EINVAL)
4518 /* We must be running on an old kernel. Call without the flag. */
4519 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4520 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4526 int errsv = get_socket_errno ();
4531 if (socket->priv->blocking &&
4532 (errsv == EWOULDBLOCK ||
4536 g_set_error (error, G_IO_ERROR,
4537 socket_io_error_from_errno (errsv),
4538 _("Error receiving message: %s"), socket_strerror (errsv));
4545 /* decode address */
4546 if (address != NULL)
4548 *address = cache_recv_address (socket, msg.msg_name, msg.msg_namelen);
4551 /* decode control messages */
4553 GPtrArray *my_messages = NULL;
4554 struct cmsghdr *cmsg;
4556 if (msg.msg_controllen >= sizeof (struct cmsghdr))
4558 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4560 GSocketControlMessage *message;
4562 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4564 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4566 if (message == NULL)
4567 /* We've already spewed about the problem in the
4568 deserialization code, so just continue */
4571 if (messages == NULL)
4573 /* we have to do it this way if the user ignores the
4574 * messages so that we will close any received fds.
4576 g_object_unref (message);
4580 if (my_messages == NULL)
4581 my_messages = g_ptr_array_new ();
4582 g_ptr_array_add (my_messages, message);
4588 *num_messages = my_messages != NULL ? my_messages->len : 0;
4592 if (my_messages == NULL)
4598 g_ptr_array_add (my_messages, NULL);
4599 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4604 g_assert (my_messages == NULL);
4608 /* capture the flags */
4610 *flags = msg.msg_flags;
4616 struct sockaddr_storage addr;
4618 DWORD bytes_received;
4625 bufs = g_newa (WSABUF, num_vectors);
4626 for (i = 0; i < num_vectors; i++)
4628 bufs[i].buf = (char *)vectors[i].buffer;
4629 bufs[i].len = (gulong)vectors[i].size;
4641 addrlen = sizeof addr;
4643 result = WSARecvFrom (socket->priv->fd,
4645 &bytes_received, &win_flags,
4646 (struct sockaddr *)&addr, &addrlen,
4649 result = WSARecv (socket->priv->fd,
4651 &bytes_received, &win_flags,
4655 int errsv = get_socket_errno ();
4657 if (errsv == WSAEINTR)
4660 if (errsv == WSAEWOULDBLOCK)
4662 win32_unset_event_mask (socket, FD_READ);
4664 if (socket->priv->blocking)
4666 if (!g_socket_condition_wait (socket,
4667 G_IO_IN, cancellable, error))
4674 g_set_error (error, G_IO_ERROR,
4675 socket_io_error_from_errno (errsv),
4676 _("Error receiving message: %s"), socket_strerror (errsv));
4680 win32_unset_event_mask (socket, FD_READ);
4684 /* decode address */
4685 if (address != NULL)
4687 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
4690 /* capture the flags */
4694 if (messages != NULL)
4696 if (num_messages != NULL)
4699 return bytes_received;
4705 * g_socket_get_credentials:
4706 * @socket: a #GSocket.
4707 * @error: #GError for error reporting, or %NULL to ignore.
4709 * Returns the credentials of the foreign process connected to this
4710 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4713 * If this operation isn't supported on the OS, the method fails with
4714 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4715 * by reading the %SO_PEERCRED option on the underlying socket.
4717 * Other ways to obtain credentials from a foreign peer includes the
4718 * #GUnixCredentialsMessage type and
4719 * g_unix_connection_send_credentials() /
4720 * g_unix_connection_receive_credentials() functions.
4722 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4723 * that must be freed with g_object_unref().
4728 g_socket_get_credentials (GSocket *socket,
4733 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4734 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4738 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
4742 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
4743 socklen_t optlen = sizeof (native_creds_buf);
4745 if (getsockopt (socket->priv->fd,
4751 ret = g_credentials_new ();
4752 g_credentials_set_native (ret,
4753 G_CREDENTIALS_NATIVE_TYPE,
4757 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
4759 struct unpcbid cred;
4760 socklen_t optlen = sizeof (cred);
4762 if (getsockopt (socket->priv->fd,
4768 ret = g_credentials_new ();
4769 g_credentials_set_native (ret,
4770 G_CREDENTIALS_NATIVE_TYPE,
4774 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
4776 ucred_t *ucred = NULL;
4778 if (getpeerucred (socket->priv->fd, &ucred) == 0)
4780 ret = g_credentials_new ();
4781 g_credentials_set_native (ret,
4782 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
4788 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
4793 int errsv = get_socket_errno ();
4797 socket_io_error_from_errno (errsv),
4798 _("Unable to read socket credentials: %s"),
4799 socket_strerror (errsv));
4804 g_set_error_literal (error,
4806 G_IO_ERROR_NOT_SUPPORTED,
4807 _("g_socket_get_credentials not implemented for this OS"));
4814 * g_socket_get_option:
4815 * @socket: a #GSocket
4816 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
4817 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
4818 * @value: (out): return location for the option value
4819 * @error: #GError for error reporting, or %NULL to ignore.
4821 * Gets the value of an integer-valued option on @socket, as with
4822 * getsockopt(). (If you need to fetch a non-integer-valued option,
4823 * you will need to call getsockopt() directly.)
4825 * The [<gio/gnetworking.h>][gio-gnetworking.h]
4826 * header pulls in system headers that will define most of the
4827 * standard/portable socket options. For unusual socket protocols or
4828 * platform-dependent options, you may need to include additional
4831 * Note that even for socket options that are a single byte in size,
4832 * @value is still a pointer to a #gint variable, not a #guchar;
4833 * g_socket_get_option() will handle the conversion internally.
4835 * Returns: success or failure. On failure, @error will be set, and
4836 * the system error value (`errno` or WSAGetLastError()) will still
4837 * be set to the result of the getsockopt() call.
4842 g_socket_get_option (GSocket *socket,
4850 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4853 size = sizeof (gint);
4854 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
4856 int errsv = get_socket_errno ();
4858 g_set_error_literal (error,
4860 socket_io_error_from_errno (errsv),
4861 socket_strerror (errsv));
4863 /* Reset errno in case the caller wants to look at it */
4869 #if G_BYTE_ORDER == G_BIG_ENDIAN
4870 /* If the returned value is smaller than an int then we need to
4871 * slide it over into the low-order bytes of *value.
4873 if (size != sizeof (gint))
4874 *value = *value >> (8 * (sizeof (gint) - size));
4881 * g_socket_set_option:
4882 * @socket: a #GSocket
4883 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
4884 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
4885 * @value: the value to set the option to
4886 * @error: #GError for error reporting, or %NULL to ignore.
4888 * Sets the value of an integer-valued option on @socket, as with
4889 * setsockopt(). (If you need to set a non-integer-valued option,
4890 * you will need to call setsockopt() directly.)
4892 * The [<gio/gnetworking.h>][gio-gnetworking.h]
4893 * header pulls in system headers that will define most of the
4894 * standard/portable socket options. For unusual socket protocols or
4895 * platform-dependent options, you may need to include additional
4898 * Returns: success or failure. On failure, @error will be set, and
4899 * the system error value (`errno` or WSAGetLastError()) will still
4900 * be set to the result of the setsockopt() call.
4905 g_socket_set_option (GSocket *socket,
4913 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4915 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
4918 #if !defined (__linux__) && !defined (G_OS_WIN32)
4919 /* Linux and Windows let you set a single-byte value from an int,
4920 * but most other platforms don't.
4922 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
4924 #if G_BYTE_ORDER == G_BIG_ENDIAN
4925 value = value << (8 * (sizeof (gint) - 1));
4927 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
4932 errsv = get_socket_errno ();
4934 g_set_error_literal (error,
4936 socket_io_error_from_errno (errsv),
4937 socket_strerror (errsv));