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"
68 /* For Windows XP runtime compatibility, but use the system's if_nametoindex() if available */
69 #include "gwin32networking.h"
74 * @short_description: Low-level socket object
76 * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
78 * A #GSocket is a low-level networking primitive. It is a more or less
79 * direct mapping of the BSD socket API in a portable GObject based API.
80 * It supports both the UNIX socket implementations and winsock2 on Windows.
82 * #GSocket is the platform independent base upon which the higher level
83 * network primitives are based. Applications are not typically meant to
84 * use it directly, but rather through classes like #GSocketClient,
85 * #GSocketService and #GSocketConnection. However there may be cases where
86 * direct use of #GSocket is useful.
88 * #GSocket implements the #GInitable interface, so if it is manually constructed
89 * by e.g. g_object_new() you must call g_initable_init() and check the
90 * results before using the object. This is done automatically in
91 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
94 * Sockets operate in two general modes, blocking or non-blocking. When
95 * in blocking mode all operations block until the requested operation
96 * is finished or there is an error. In non-blocking mode all calls that
97 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
98 * To know when a call would successfully run you can call g_socket_condition_check(),
99 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
100 * attach it to a #GMainContext to get callbacks when I/O is possible.
101 * Note that all sockets are always set to non blocking mode in the system, and
102 * blocking mode is emulated in GSocket.
104 * When working in non-blocking mode applications should always be able to
105 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
106 * function said that I/O was possible. This can easily happen in case
107 * of a race condition in the application, but it can also happen for other
108 * reasons. For instance, on Windows a socket is always seen as writable
109 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
111 * #GSockets can be either connection oriented or datagram based.
112 * For connection oriented types you must first establish a connection by
113 * either connecting to an address or accepting a connection from another
114 * address. For connectionless socket types the target/source address is
115 * specified or received in each I/O operation.
117 * All socket file descriptors are set to be close-on-exec.
119 * Note that creating a #GSocket causes the signal %SIGPIPE to be
120 * ignored for the remainder of the program. If you are writing a
121 * command-line utility that uses #GSocket, you may need to take into
122 * account the fact that your program will not automatically be killed
123 * if it tries to write to %stdout after it has been closed.
125 * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
126 * a #GSocket concurrently from multiple threads, you must implement your own
132 static void g_socket_initable_iface_init (GInitableIface *iface);
133 static gboolean g_socket_initable_init (GInitable *initable,
134 GCancellable *cancellable,
152 PROP_MULTICAST_LOOPBACK,
156 /* Size of the receiver cache for g_socket_receive_from() */
157 #define RECV_ADDR_CACHE_SIZE 8
159 struct _GSocketPrivate
161 GSocketFamily family;
163 GSocketProtocol protocol;
167 GError *construct_error;
168 GSocketAddress *remote_address;
176 guint connect_pending : 1;
182 GList *requested_conditions; /* list of requested GIOCondition * */
183 GMutex win32_source_lock;
187 GSocketAddress *addr;
188 struct sockaddr *native;
191 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
194 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
195 G_ADD_PRIVATE (GSocket)
196 g_networking_init ();
197 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
198 g_socket_initable_iface_init));
201 get_socket_errno (void)
206 return WSAGetLastError ();
211 socket_io_error_from_errno (int err)
214 return g_io_error_from_win32_error (err);
216 return g_io_error_from_errno (err);
221 socket_strerror (int err)
224 return g_strerror (err);
229 msg = g_win32_error_message (err);
231 msg_ret = g_intern_string (msg);
239 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
241 _win32_unset_event_mask (GSocket *socket, int mask)
243 socket->priv->current_events &= ~mask;
244 socket->priv->current_errors &= ~mask;
247 #define win32_unset_event_mask(_socket, _mask)
250 /* Windows has broken prototypes... */
252 #define getsockopt(sockfd, level, optname, optval, optlen) \
253 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
254 #define setsockopt(sockfd, level, optname, optval, optlen) \
255 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
256 #define getsockname(sockfd, addr, addrlen) \
257 getsockname (sockfd, addr, (int *)addrlen)
258 #define getpeername(sockfd, addr, addrlen) \
259 getpeername (sockfd, addr, (int *)addrlen)
260 #define recv(sockfd, buf, len, flags) \
261 recv (sockfd, (gpointer)buf, len, flags)
265 check_socket (GSocket *socket,
268 if (!socket->priv->inited)
270 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
271 _("Invalid socket, not initialized"));
275 if (socket->priv->construct_error)
277 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
278 _("Invalid socket, initialization failed due to: %s"),
279 socket->priv->construct_error->message);
283 if (socket->priv->closed)
285 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
286 _("Socket is already closed"));
294 check_timeout (GSocket *socket,
297 if (socket->priv->timed_out)
299 socket->priv->timed_out = FALSE;
300 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
301 _("Socket I/O timed out"));
309 g_socket_details_from_fd (GSocket *socket)
311 struct sockaddr_storage address;
317 fd = socket->priv->fd;
318 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
320 errsv = get_socket_errno ();
332 /* programmer error */
333 g_error ("creating GSocket from fd %d: %s\n",
334 fd, socket_strerror (errsv));
345 socket->priv->type = G_SOCKET_TYPE_STREAM;
349 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
353 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
357 socket->priv->type = G_SOCKET_TYPE_INVALID;
361 addrlen = sizeof address;
362 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
364 errsv = get_socket_errno ();
370 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
371 sizeof address.ss_family <= addrlen);
372 family = address.ss_family;
376 /* On Solaris, this happens if the socket is not yet connected.
377 * But we can use SO_DOMAIN as a workaround there.
380 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
382 errsv = get_socket_errno ();
386 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
394 case G_SOCKET_FAMILY_IPV4:
395 case G_SOCKET_FAMILY_IPV6:
396 socket->priv->family = address.ss_family;
397 switch (socket->priv->type)
399 case G_SOCKET_TYPE_STREAM:
400 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
403 case G_SOCKET_TYPE_DATAGRAM:
404 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
407 case G_SOCKET_TYPE_SEQPACKET:
408 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
416 case G_SOCKET_FAMILY_UNIX:
417 socket->priv->family = G_SOCKET_FAMILY_UNIX;
418 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
422 socket->priv->family = G_SOCKET_FAMILY_INVALID;
426 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
428 addrlen = sizeof address;
429 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
430 socket->priv->connected = TRUE;
433 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
435 socket->priv->keepalive = !!value;
439 /* Can't read, maybe not supported, assume FALSE */
440 socket->priv->keepalive = FALSE;
446 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
447 socket_io_error_from_errno (errsv),
448 _("creating GSocket from fd: %s"),
449 socket_strerror (errsv));
452 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
454 g_socket (gint domain,
462 fd = socket (domain, type | SOCK_CLOEXEC, protocol);
466 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
467 if (fd < 0 && (errno == EINVAL || errno == EPROTOTYPE))
469 fd = socket (domain, type, protocol);
473 int errsv = get_socket_errno ();
475 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
476 _("Unable to create socket: %s"), socket_strerror (errsv));
485 /* We always want to set close-on-exec to protect users. If you
486 need to so some weird inheritance to exec you can re-enable this
487 using lower level hacks with g_socket_get_fd(). */
488 flags = fcntl (fd, F_GETFD, 0);
490 (flags & FD_CLOEXEC) == 0)
493 fcntl (fd, F_SETFD, flags);
502 g_socket_create_socket (GSocketFamily family,
511 case G_SOCKET_TYPE_STREAM:
512 native_type = SOCK_STREAM;
515 case G_SOCKET_TYPE_DATAGRAM:
516 native_type = SOCK_DGRAM;
519 case G_SOCKET_TYPE_SEQPACKET:
520 native_type = SOCK_SEQPACKET;
524 g_assert_not_reached ();
529 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
530 _("Unable to create socket: %s"), _("Unknown family was specified"));
536 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
537 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
541 return g_socket (family, native_type, protocol, error);
545 g_socket_constructed (GObject *object)
547 GSocket *socket = G_SOCKET (object);
549 if (socket->priv->fd >= 0)
550 /* create socket->priv info from the fd */
551 g_socket_details_from_fd (socket);
554 /* create the fd from socket->priv info */
555 socket->priv->fd = g_socket_create_socket (socket->priv->family,
557 socket->priv->protocol,
558 &socket->priv->construct_error);
560 if (socket->priv->fd != -1)
563 GError *error = NULL;
568 /* Always use native nonblocking sockets, as Windows sets sockets to
569 * nonblocking automatically in certain operations. This way we make
570 * things work the same on all platforms.
573 if (!g_unix_set_fd_nonblocking (socket->priv->fd, TRUE, &error))
575 g_warning ("Error setting socket nonblocking: %s", error->message);
576 g_clear_error (&error);
581 if (ioctlsocket (socket->priv->fd, FIONBIO, &arg) == SOCKET_ERROR)
583 int errsv = get_socket_errno ();
584 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
589 /* See note about SIGPIPE below. */
590 g_socket_set_option (socket, SOL_SOCKET, SO_NOSIGPIPE, TRUE, NULL);
596 g_socket_get_property (GObject *object,
601 GSocket *socket = G_SOCKET (object);
602 GSocketAddress *address;
607 g_value_set_enum (value, socket->priv->family);
611 g_value_set_enum (value, socket->priv->type);
615 g_value_set_enum (value, socket->priv->protocol);
619 g_value_set_int (value, socket->priv->fd);
623 g_value_set_boolean (value, socket->priv->blocking);
626 case PROP_LISTEN_BACKLOG:
627 g_value_set_int (value, socket->priv->listen_backlog);
631 g_value_set_boolean (value, socket->priv->keepalive);
634 case PROP_LOCAL_ADDRESS:
635 address = g_socket_get_local_address (socket, NULL);
636 g_value_take_object (value, address);
639 case PROP_REMOTE_ADDRESS:
640 address = g_socket_get_remote_address (socket, NULL);
641 g_value_take_object (value, address);
645 g_value_set_uint (value, socket->priv->timeout);
649 g_value_set_uint (value, g_socket_get_ttl (socket));
653 g_value_set_boolean (value, g_socket_get_broadcast (socket));
656 case PROP_MULTICAST_LOOPBACK:
657 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
660 case PROP_MULTICAST_TTL:
661 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
665 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
670 g_socket_set_property (GObject *object,
675 GSocket *socket = G_SOCKET (object);
680 socket->priv->family = g_value_get_enum (value);
684 socket->priv->type = g_value_get_enum (value);
688 socket->priv->protocol = g_value_get_enum (value);
692 socket->priv->fd = g_value_get_int (value);
696 g_socket_set_blocking (socket, g_value_get_boolean (value));
699 case PROP_LISTEN_BACKLOG:
700 g_socket_set_listen_backlog (socket, g_value_get_int (value));
704 g_socket_set_keepalive (socket, g_value_get_boolean (value));
708 g_socket_set_timeout (socket, g_value_get_uint (value));
712 g_socket_set_ttl (socket, g_value_get_uint (value));
716 g_socket_set_broadcast (socket, g_value_get_boolean (value));
719 case PROP_MULTICAST_LOOPBACK:
720 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
723 case PROP_MULTICAST_TTL:
724 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
728 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
733 g_socket_finalize (GObject *object)
735 GSocket *socket = G_SOCKET (object);
738 g_clear_error (&socket->priv->construct_error);
740 if (socket->priv->fd != -1 &&
741 !socket->priv->closed)
742 g_socket_close (socket, NULL);
744 if (socket->priv->remote_address)
745 g_object_unref (socket->priv->remote_address);
748 if (socket->priv->event != WSA_INVALID_EVENT)
750 WSACloseEvent (socket->priv->event);
751 socket->priv->event = WSA_INVALID_EVENT;
754 g_assert (socket->priv->requested_conditions == NULL);
755 g_mutex_clear (&socket->priv->win32_source_lock);
758 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
760 if (socket->priv->recv_addr_cache[i].addr)
762 g_object_unref (socket->priv->recv_addr_cache[i].addr);
763 g_free (socket->priv->recv_addr_cache[i].native);
767 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
768 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
772 g_socket_class_init (GSocketClass *klass)
774 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
777 /* There is no portable, thread-safe way to avoid having the process
778 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
779 * forced to simply ignore the signal process-wide.
781 * Even if we ignore it though, gdb will still stop if the app
782 * receives a SIGPIPE, which can be confusing and annoying. So when
783 * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
784 * prevent the signal from occurring at all.
786 signal (SIGPIPE, SIG_IGN);
789 gobject_class->finalize = g_socket_finalize;
790 gobject_class->constructed = g_socket_constructed;
791 gobject_class->set_property = g_socket_set_property;
792 gobject_class->get_property = g_socket_get_property;
794 g_object_class_install_property (gobject_class, PROP_FAMILY,
795 g_param_spec_enum ("family",
797 P_("The sockets address family"),
798 G_TYPE_SOCKET_FAMILY,
799 G_SOCKET_FAMILY_INVALID,
800 G_PARAM_CONSTRUCT_ONLY |
802 G_PARAM_STATIC_STRINGS));
804 g_object_class_install_property (gobject_class, PROP_TYPE,
805 g_param_spec_enum ("type",
807 P_("The sockets type"),
809 G_SOCKET_TYPE_STREAM,
810 G_PARAM_CONSTRUCT_ONLY |
812 G_PARAM_STATIC_STRINGS));
814 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
815 g_param_spec_enum ("protocol",
816 P_("Socket protocol"),
817 P_("The id of the protocol to use, or -1 for unknown"),
818 G_TYPE_SOCKET_PROTOCOL,
819 G_SOCKET_PROTOCOL_UNKNOWN,
820 G_PARAM_CONSTRUCT_ONLY |
822 G_PARAM_STATIC_STRINGS));
824 g_object_class_install_property (gobject_class, PROP_FD,
825 g_param_spec_int ("fd",
826 P_("File descriptor"),
827 P_("The sockets file descriptor"),
831 G_PARAM_CONSTRUCT_ONLY |
833 G_PARAM_STATIC_STRINGS));
835 g_object_class_install_property (gobject_class, PROP_BLOCKING,
836 g_param_spec_boolean ("blocking",
838 P_("Whether or not I/O on this socket is blocking"),
841 G_PARAM_STATIC_STRINGS));
843 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
844 g_param_spec_int ("listen-backlog",
845 P_("Listen backlog"),
846 P_("Outstanding connections in the listen queue"),
851 G_PARAM_STATIC_STRINGS));
853 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
854 g_param_spec_boolean ("keepalive",
855 P_("Keep connection alive"),
856 P_("Keep connection alive by sending periodic pings"),
859 G_PARAM_STATIC_STRINGS));
861 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
862 g_param_spec_object ("local-address",
864 P_("The local address the socket is bound to"),
865 G_TYPE_SOCKET_ADDRESS,
867 G_PARAM_STATIC_STRINGS));
869 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
870 g_param_spec_object ("remote-address",
871 P_("Remote address"),
872 P_("The remote address the socket is connected to"),
873 G_TYPE_SOCKET_ADDRESS,
875 G_PARAM_STATIC_STRINGS));
880 * The timeout in seconds on socket I/O
884 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
885 g_param_spec_uint ("timeout",
887 P_("The timeout in seconds on socket I/O"),
892 G_PARAM_STATIC_STRINGS));
897 * Whether the socket should allow sending to broadcast addresses.
901 g_object_class_install_property (gobject_class, PROP_BROADCAST,
902 g_param_spec_boolean ("broadcast",
904 P_("Whether to allow sending to broadcast addresses"),
907 G_PARAM_STATIC_STRINGS));
912 * Time-to-live for outgoing unicast packets
916 g_object_class_install_property (gobject_class, PROP_TTL,
917 g_param_spec_uint ("ttl",
919 P_("Time-to-live of outgoing unicast packets"),
922 G_PARAM_STATIC_STRINGS));
925 * GSocket:multicast-loopback:
927 * Whether outgoing multicast packets loop back to the local host.
931 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
932 g_param_spec_boolean ("multicast-loopback",
933 P_("Multicast loopback"),
934 P_("Whether outgoing multicast packets loop back to the local host"),
937 G_PARAM_STATIC_STRINGS));
940 * GSocket:multicast-ttl:
942 * Time-to-live out outgoing multicast packets
946 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
947 g_param_spec_uint ("multicast-ttl",
949 P_("Time-to-live of outgoing multicast packets"),
952 G_PARAM_STATIC_STRINGS));
956 g_socket_initable_iface_init (GInitableIface *iface)
958 iface->init = g_socket_initable_init;
962 g_socket_init (GSocket *socket)
964 socket->priv = g_socket_get_instance_private (socket);
966 socket->priv->fd = -1;
967 socket->priv->blocking = TRUE;
968 socket->priv->listen_backlog = 10;
969 socket->priv->construct_error = NULL;
971 socket->priv->event = WSA_INVALID_EVENT;
972 g_mutex_init (&socket->priv->win32_source_lock);
977 g_socket_initable_init (GInitable *initable,
978 GCancellable *cancellable,
983 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
985 socket = G_SOCKET (initable);
987 if (cancellable != NULL)
989 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
990 _("Cancellable initialization not supported"));
994 socket->priv->inited = TRUE;
996 if (socket->priv->construct_error)
999 *error = g_error_copy (socket->priv->construct_error);
1009 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1010 * @type: the socket type to use.
1011 * @protocol: the id of the protocol to use, or 0 for default.
1012 * @error: #GError for error reporting, or %NULL to ignore.
1014 * Creates a new #GSocket with the defined family, type and protocol.
1015 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1016 * for the family and type is used.
1018 * The @protocol is a family and type specific int that specifies what
1019 * kind of protocol to use. #GSocketProtocol lists several common ones.
1020 * Many families only support one protocol, and use 0 for this, others
1021 * support several and using 0 means to use the default protocol for
1022 * the family and type.
1024 * The protocol id is passed directly to the operating
1025 * system, so you can use protocols not listed in #GSocketProtocol if you
1026 * know the protocol number used for it.
1028 * Returns: a #GSocket or %NULL on error.
1029 * Free the returned object with g_object_unref().
1034 g_socket_new (GSocketFamily family,
1036 GSocketProtocol protocol,
1039 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1043 "protocol", protocol,
1048 * g_socket_new_from_fd:
1049 * @fd: a native socket file descriptor.
1050 * @error: #GError for error reporting, or %NULL to ignore.
1052 * Creates a new #GSocket from a native file descriptor
1053 * or winsock SOCKET handle.
1055 * This reads all the settings from the file descriptor so that
1056 * all properties should work. Note that the file descriptor
1057 * will be set to non-blocking mode, independent on the blocking
1058 * mode of the #GSocket.
1060 * Returns: a #GSocket or %NULL on error.
1061 * Free the returned object with g_object_unref().
1066 g_socket_new_from_fd (gint fd,
1069 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1076 * g_socket_set_blocking:
1077 * @socket: a #GSocket.
1078 * @blocking: Whether to use blocking I/O or not.
1080 * Sets the blocking mode of the socket. In blocking mode
1081 * all operations block until they succeed or there is an error. In
1082 * non-blocking mode all functions return results immediately or
1083 * with a %G_IO_ERROR_WOULD_BLOCK error.
1085 * All sockets are created in blocking mode. However, note that the
1086 * platform level socket is always non-blocking, and blocking mode
1087 * is a GSocket level feature.
1092 g_socket_set_blocking (GSocket *socket,
1095 g_return_if_fail (G_IS_SOCKET (socket));
1097 blocking = !!blocking;
1099 if (socket->priv->blocking == blocking)
1102 socket->priv->blocking = blocking;
1103 g_object_notify (G_OBJECT (socket), "blocking");
1107 * g_socket_get_blocking:
1108 * @socket: a #GSocket.
1110 * Gets the blocking mode of the socket. For details on blocking I/O,
1111 * see g_socket_set_blocking().
1113 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1118 g_socket_get_blocking (GSocket *socket)
1120 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1122 return socket->priv->blocking;
1126 * g_socket_set_keepalive:
1127 * @socket: a #GSocket.
1128 * @keepalive: Value for the keepalive flag
1130 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1131 * this flag is set on a socket, the system will attempt to verify that the
1132 * remote socket endpoint is still present if a sufficiently long period of
1133 * time passes with no data being exchanged. If the system is unable to
1134 * verify the presence of the remote endpoint, it will automatically close
1137 * This option is only functional on certain kinds of sockets. (Notably,
1138 * %G_SOCKET_PROTOCOL_TCP sockets.)
1140 * The exact time between pings is system- and protocol-dependent, but will
1141 * normally be at least two hours. Most commonly, you would set this flag
1142 * on a server socket if you want to allow clients to remain idle for long
1143 * periods of time, but also want to ensure that connections are eventually
1144 * garbage-collected if clients crash or become unreachable.
1149 g_socket_set_keepalive (GSocket *socket,
1152 GError *error = NULL;
1154 g_return_if_fail (G_IS_SOCKET (socket));
1156 keepalive = !!keepalive;
1157 if (socket->priv->keepalive == keepalive)
1160 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1163 g_warning ("error setting keepalive: %s", error->message);
1164 g_error_free (error);
1168 socket->priv->keepalive = keepalive;
1169 g_object_notify (G_OBJECT (socket), "keepalive");
1173 * g_socket_get_keepalive:
1174 * @socket: a #GSocket.
1176 * Gets the keepalive mode of the socket. For details on this,
1177 * see g_socket_set_keepalive().
1179 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1184 g_socket_get_keepalive (GSocket *socket)
1186 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1188 return socket->priv->keepalive;
1192 * g_socket_get_listen_backlog:
1193 * @socket: a #GSocket.
1195 * Gets the listen backlog setting of the socket. For details on this,
1196 * see g_socket_set_listen_backlog().
1198 * Returns: the maximum number of pending connections.
1203 g_socket_get_listen_backlog (GSocket *socket)
1205 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1207 return socket->priv->listen_backlog;
1211 * g_socket_set_listen_backlog:
1212 * @socket: a #GSocket.
1213 * @backlog: the maximum number of pending connections.
1215 * Sets the maximum number of outstanding connections allowed
1216 * when listening on this socket. If more clients than this are
1217 * connecting to the socket and the application is not handling them
1218 * on time then the new connections will be refused.
1220 * Note that this must be called before g_socket_listen() and has no
1221 * effect if called after that.
1226 g_socket_set_listen_backlog (GSocket *socket,
1229 g_return_if_fail (G_IS_SOCKET (socket));
1230 g_return_if_fail (!socket->priv->listening);
1232 if (backlog != socket->priv->listen_backlog)
1234 socket->priv->listen_backlog = backlog;
1235 g_object_notify (G_OBJECT (socket), "listen-backlog");
1240 * g_socket_get_timeout:
1241 * @socket: a #GSocket.
1243 * Gets the timeout setting of the socket. For details on this, see
1244 * g_socket_set_timeout().
1246 * Returns: the timeout in seconds
1251 g_socket_get_timeout (GSocket *socket)
1253 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1255 return socket->priv->timeout;
1259 * g_socket_set_timeout:
1260 * @socket: a #GSocket.
1261 * @timeout: the timeout for @socket, in seconds, or 0 for none
1263 * Sets the time in seconds after which I/O operations on @socket will
1264 * time out if they have not yet completed.
1266 * On a blocking socket, this means that any blocking #GSocket
1267 * operation will time out after @timeout seconds of inactivity,
1268 * returning %G_IO_ERROR_TIMED_OUT.
1270 * On a non-blocking socket, calls to g_socket_condition_wait() will
1271 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1272 * created with g_socket_create_source() will trigger after
1273 * @timeout seconds of inactivity, with the requested condition
1274 * set, at which point calling g_socket_receive(), g_socket_send(),
1275 * g_socket_check_connect_result(), etc, will fail with
1276 * %G_IO_ERROR_TIMED_OUT.
1278 * If @timeout is 0 (the default), operations will never time out
1281 * Note that if an I/O operation is interrupted by a signal, this may
1282 * cause the timeout to be reset.
1287 g_socket_set_timeout (GSocket *socket,
1290 g_return_if_fail (G_IS_SOCKET (socket));
1292 if (timeout != socket->priv->timeout)
1294 socket->priv->timeout = timeout;
1295 g_object_notify (G_OBJECT (socket), "timeout");
1301 * @socket: a #GSocket.
1303 * Gets the unicast time-to-live setting on @socket; see
1304 * g_socket_set_ttl() for more details.
1306 * Returns: the time-to-live setting on @socket
1311 g_socket_get_ttl (GSocket *socket)
1313 GError *error = NULL;
1316 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1318 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1320 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1323 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1325 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1329 g_return_val_if_reached (0);
1333 g_warning ("error getting unicast ttl: %s", error->message);
1334 g_error_free (error);
1343 * @socket: a #GSocket.
1344 * @ttl: the time-to-live value for all unicast packets on @socket
1346 * Sets the time-to-live for outgoing unicast packets on @socket.
1347 * By default the platform-specific default value is used.
1352 g_socket_set_ttl (GSocket *socket,
1355 GError *error = NULL;
1357 g_return_if_fail (G_IS_SOCKET (socket));
1359 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1361 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1364 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1366 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1368 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1372 g_return_if_reached ();
1376 g_warning ("error setting unicast ttl: %s", error->message);
1377 g_error_free (error);
1381 g_object_notify (G_OBJECT (socket), "ttl");
1385 * g_socket_get_broadcast:
1386 * @socket: a #GSocket.
1388 * Gets the broadcast setting on @socket; if %TRUE,
1389 * it is possible to send packets to broadcast
1392 * Returns: the broadcast setting on @socket
1397 g_socket_get_broadcast (GSocket *socket)
1399 GError *error = NULL;
1402 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1404 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1407 g_warning ("error getting broadcast: %s", error->message);
1408 g_error_free (error);
1416 * g_socket_set_broadcast:
1417 * @socket: a #GSocket.
1418 * @broadcast: whether @socket should allow sending to broadcast
1421 * Sets whether @socket should allow sending to broadcast addresses.
1422 * This is %FALSE by default.
1427 g_socket_set_broadcast (GSocket *socket,
1430 GError *error = NULL;
1432 g_return_if_fail (G_IS_SOCKET (socket));
1434 broadcast = !!broadcast;
1436 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1439 g_warning ("error setting broadcast: %s", error->message);
1440 g_error_free (error);
1444 g_object_notify (G_OBJECT (socket), "broadcast");
1448 * g_socket_get_multicast_loopback:
1449 * @socket: a #GSocket.
1451 * Gets the multicast loopback setting on @socket; if %TRUE (the
1452 * default), outgoing multicast packets will be looped back to
1453 * multicast listeners on the same host.
1455 * Returns: the multicast loopback setting on @socket
1460 g_socket_get_multicast_loopback (GSocket *socket)
1462 GError *error = NULL;
1465 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1467 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1469 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1472 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1474 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1478 g_return_val_if_reached (FALSE);
1482 g_warning ("error getting multicast loopback: %s", error->message);
1483 g_error_free (error);
1491 * g_socket_set_multicast_loopback:
1492 * @socket: a #GSocket.
1493 * @loopback: whether @socket should receive messages sent to its
1494 * multicast groups from the local host
1496 * Sets whether outgoing multicast packets will be received by sockets
1497 * listening on that multicast address on the same host. This is %TRUE
1503 g_socket_set_multicast_loopback (GSocket *socket,
1506 GError *error = NULL;
1508 g_return_if_fail (G_IS_SOCKET (socket));
1510 loopback = !!loopback;
1512 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1514 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1517 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1519 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1521 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1525 g_return_if_reached ();
1529 g_warning ("error setting multicast loopback: %s", error->message);
1530 g_error_free (error);
1534 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1538 * g_socket_get_multicast_ttl:
1539 * @socket: a #GSocket.
1541 * Gets the multicast time-to-live setting on @socket; see
1542 * g_socket_set_multicast_ttl() for more details.
1544 * Returns: the multicast time-to-live setting on @socket
1549 g_socket_get_multicast_ttl (GSocket *socket)
1551 GError *error = NULL;
1554 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1556 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1558 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1561 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1563 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1567 g_return_val_if_reached (FALSE);
1571 g_warning ("error getting multicast ttl: %s", error->message);
1572 g_error_free (error);
1580 * g_socket_set_multicast_ttl:
1581 * @socket: a #GSocket.
1582 * @ttl: the time-to-live value for all multicast datagrams on @socket
1584 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1585 * By default, this is 1, meaning that multicast packets will not leave
1586 * the local network.
1591 g_socket_set_multicast_ttl (GSocket *socket,
1594 GError *error = NULL;
1596 g_return_if_fail (G_IS_SOCKET (socket));
1598 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1600 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1603 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1605 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1607 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1611 g_return_if_reached ();
1615 g_warning ("error setting multicast ttl: %s", error->message);
1616 g_error_free (error);
1620 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1624 * g_socket_get_family:
1625 * @socket: a #GSocket.
1627 * Gets the socket family of the socket.
1629 * Returns: a #GSocketFamily
1634 g_socket_get_family (GSocket *socket)
1636 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1638 return socket->priv->family;
1642 * g_socket_get_socket_type:
1643 * @socket: a #GSocket.
1645 * Gets the socket type of the socket.
1647 * Returns: a #GSocketType
1652 g_socket_get_socket_type (GSocket *socket)
1654 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1656 return socket->priv->type;
1660 * g_socket_get_protocol:
1661 * @socket: a #GSocket.
1663 * Gets the socket protocol id the socket was created with.
1664 * In case the protocol is unknown, -1 is returned.
1666 * Returns: a protocol id, or -1 if unknown
1671 g_socket_get_protocol (GSocket *socket)
1673 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1675 return socket->priv->protocol;
1680 * @socket: a #GSocket.
1682 * Returns the underlying OS socket object. On unix this
1683 * is a socket file descriptor, and on Windows this is
1684 * a Winsock2 SOCKET handle. This may be useful for
1685 * doing platform specific or otherwise unusual operations
1688 * Returns: the file descriptor of the socket.
1693 g_socket_get_fd (GSocket *socket)
1695 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1697 return socket->priv->fd;
1701 * g_socket_get_local_address:
1702 * @socket: a #GSocket.
1703 * @error: #GError for error reporting, or %NULL to ignore.
1705 * Try to get the local address of a bound socket. This is only
1706 * useful if the socket has been bound to a local address,
1707 * either explicitly or implicitly when connecting.
1709 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1710 * Free the returned object with g_object_unref().
1715 g_socket_get_local_address (GSocket *socket,
1718 struct sockaddr_storage buffer;
1719 guint len = sizeof (buffer);
1721 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1723 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1725 int errsv = get_socket_errno ();
1726 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1727 _("could not get local address: %s"), socket_strerror (errsv));
1731 return g_socket_address_new_from_native (&buffer, len);
1735 * g_socket_get_remote_address:
1736 * @socket: a #GSocket.
1737 * @error: #GError for error reporting, or %NULL to ignore.
1739 * Try to get the remove address of a connected socket. This is only
1740 * useful for connection oriented sockets that have been connected.
1742 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1743 * Free the returned object with g_object_unref().
1748 g_socket_get_remote_address (GSocket *socket,
1751 struct sockaddr_storage buffer;
1752 guint len = sizeof (buffer);
1754 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1756 if (socket->priv->connect_pending)
1758 if (!g_socket_check_connect_result (socket, error))
1761 socket->priv->connect_pending = FALSE;
1764 if (!socket->priv->remote_address)
1766 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1768 int errsv = get_socket_errno ();
1769 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1770 _("could not get remote address: %s"), socket_strerror (errsv));
1774 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1777 return g_object_ref (socket->priv->remote_address);
1781 * g_socket_is_connected:
1782 * @socket: a #GSocket.
1784 * Check whether the socket is connected. This is only useful for
1785 * connection-oriented sockets.
1787 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1792 g_socket_is_connected (GSocket *socket)
1794 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1796 return socket->priv->connected;
1801 * @socket: a #GSocket.
1802 * @error: #GError for error reporting, or %NULL to ignore.
1804 * Marks the socket as a server socket, i.e. a socket that is used
1805 * to accept incoming requests using g_socket_accept().
1807 * Before calling this the socket must be bound to a local address using
1810 * To set the maximum amount of outstanding clients, use
1811 * g_socket_set_listen_backlog().
1813 * Returns: %TRUE on success, %FALSE on error.
1818 g_socket_listen (GSocket *socket,
1821 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1823 if (!check_socket (socket, error))
1826 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1828 int errsv = get_socket_errno ();
1830 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1831 _("could not listen: %s"), socket_strerror (errsv));
1835 socket->priv->listening = TRUE;
1842 * @socket: a #GSocket.
1843 * @address: a #GSocketAddress specifying the local address.
1844 * @allow_reuse: whether to allow reusing this address
1845 * @error: #GError for error reporting, or %NULL to ignore.
1847 * When a socket is created it is attached to an address family, but it
1848 * doesn't have an address in this family. g_socket_bind() assigns the
1849 * address (sometimes called name) of the socket.
1851 * It is generally required to bind to a local address before you can
1852 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1853 * In certain situations, you may also want to bind a socket that will be
1854 * used to initiate connections, though this is not normally required.
1856 * If @socket is a TCP socket, then @allow_reuse controls the setting
1857 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
1858 * server sockets (sockets that you will eventually call
1859 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
1860 * set this flag on a server socket may cause g_socket_bind() to return
1861 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
1862 * immediately restarted.)
1864 * If @socket is a UDP socket, then @allow_reuse determines whether or
1865 * not other UDP sockets can be bound to the same address at the same
1866 * time. In particular, you can have several UDP sockets bound to the
1867 * same address, and they will all receive all of the multicast and
1868 * broadcast packets sent to that address. (The behavior of unicast
1869 * UDP packets to an address with multiple listeners is not defined.)
1871 * Returns: %TRUE on success, %FALSE on error.
1876 g_socket_bind (GSocket *socket,
1877 GSocketAddress *address,
1878 gboolean reuse_address,
1881 struct sockaddr_storage addr;
1882 gboolean so_reuseaddr;
1884 gboolean so_reuseport;
1887 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1889 if (!check_socket (socket, error))
1892 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1895 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
1896 * sockets, but has nasty side effects we don't want for TCP
1899 * On other platforms, we set SO_REUSEPORT, if it exists, for
1900 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
1901 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
1902 * the desired semantics on UDP (as it does on Linux, although
1903 * Linux has SO_REUSEPORT too as of 3.9).
1907 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1909 so_reuseaddr = !!reuse_address;
1913 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1916 /* Ignore errors here, the only likely error is "not supported", and
1917 * this is a "best effort" thing mainly.
1919 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
1921 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
1924 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1925 g_socket_address_get_native_size (address)) < 0)
1927 int errsv = get_socket_errno ();
1929 G_IO_ERROR, socket_io_error_from_errno (errsv),
1930 _("Error binding to address: %s"), socket_strerror (errsv));
1937 #if !defined(HAVE_IF_NAMETOINDEX) && defined(G_OS_WIN32)
1939 if_nametoindex (const gchar *iface)
1941 PIP_ADAPTER_ADDRESSES addresses = NULL, p;
1942 gulong addresses_len = 0;
1946 if (ws2funcs.pIfNameToIndex != NULL)
1947 return ws2funcs.pIfNameToIndex (iface);
1949 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, NULL, &addresses_len);
1950 if (res != NO_ERROR && res != ERROR_BUFFER_OVERFLOW)
1952 if (res == ERROR_NO_DATA)
1959 addresses = g_malloc (addresses_len);
1960 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, addresses, &addresses_len);
1962 if (res != NO_ERROR)
1965 if (res == ERROR_NO_DATA)
1975 if (strcmp (p->AdapterName, iface) == 0)
1991 #define HAVE_IF_NAMETOINDEX 1
1995 g_socket_multicast_group_operation (GSocket *socket,
1996 GInetAddress *group,
1997 gboolean source_specific,
1999 gboolean join_group,
2002 const guint8 *native_addr;
2003 gint optname, result;
2005 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2006 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2007 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2009 if (!check_socket (socket, error))
2012 native_addr = g_inet_address_to_bytes (group);
2013 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2015 #ifdef HAVE_IP_MREQN
2016 struct ip_mreqn mc_req;
2018 struct ip_mreq mc_req;
2021 memset (&mc_req, 0, sizeof (mc_req));
2022 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2024 #ifdef HAVE_IP_MREQN
2026 mc_req.imr_ifindex = if_nametoindex (iface);
2028 mc_req.imr_ifindex = 0; /* Pick any. */
2029 #elif defined(G_OS_WIN32)
2031 mc_req.imr_interface.s_addr = g_htonl (if_nametoindex (iface));
2033 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2035 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2038 if (source_specific)
2040 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2041 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2043 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2045 _("Error joining multicast group: %s") :
2046 _("Error leaving multicast group: %s"),
2047 _("No support for source-specific multicast"));
2052 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2053 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2054 &mc_req, sizeof (mc_req));
2056 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2058 struct ipv6_mreq mc_req_ipv6;
2060 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2061 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2062 #ifdef HAVE_IF_NAMETOINDEX
2064 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2067 mc_req_ipv6.ipv6mr_interface = 0;
2069 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2070 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2071 &mc_req_ipv6, sizeof (mc_req_ipv6));
2074 g_return_val_if_reached (FALSE);
2078 int errsv = get_socket_errno ();
2080 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2082 _("Error joining multicast group: %s") :
2083 _("Error leaving multicast group: %s"),
2084 socket_strerror (errsv));
2092 * g_socket_join_multicast_group:
2093 * @socket: a #GSocket.
2094 * @group: a #GInetAddress specifying the group address to join.
2095 * @iface: (allow-none): Name of the interface to use, or %NULL
2096 * @source_specific: %TRUE if source-specific multicast should be used
2097 * @error: #GError for error reporting, or %NULL to ignore.
2099 * Registers @socket to receive multicast messages sent to @group.
2100 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2101 * been bound to an appropriate interface and port with
2104 * If @iface is %NULL, the system will automatically pick an interface
2105 * to bind to based on @group.
2107 * If @source_specific is %TRUE, source-specific multicast as defined
2108 * in RFC 4604 is used. Note that on older platforms this may fail
2109 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2111 * Returns: %TRUE on success, %FALSE on error.
2116 g_socket_join_multicast_group (GSocket *socket,
2117 GInetAddress *group,
2118 gboolean source_specific,
2122 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2126 * g_socket_leave_multicast_group:
2127 * @socket: a #GSocket.
2128 * @group: a #GInetAddress specifying the group address to leave.
2129 * @iface: (allow-none): Interface used
2130 * @source_specific: %TRUE if source-specific multicast was used
2131 * @error: #GError for error reporting, or %NULL to ignore.
2133 * Removes @socket from the multicast group defined by @group, @iface,
2134 * and @source_specific (which must all have the same values they had
2135 * when you joined the group).
2137 * @socket remains bound to its address and port, and can still receive
2138 * unicast messages after calling this.
2140 * Returns: %TRUE on success, %FALSE on error.
2145 g_socket_leave_multicast_group (GSocket *socket,
2146 GInetAddress *group,
2147 gboolean source_specific,
2151 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2155 * g_socket_speaks_ipv4:
2156 * @socket: a #GSocket
2158 * Checks if a socket is capable of speaking IPv4.
2160 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2161 * and under some combinations of circumstances IPv6 sockets are also
2162 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2165 * No other types of sockets are currently considered as being capable
2168 * Returns: %TRUE if this socket can be used with IPv4.
2173 g_socket_speaks_ipv4 (GSocket *socket)
2175 switch (socket->priv->family)
2177 case G_SOCKET_FAMILY_IPV4:
2180 case G_SOCKET_FAMILY_IPV6:
2181 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2185 if (!g_socket_get_option (socket,
2186 IPPROTO_IPV6, IPV6_V6ONLY,
2203 * @socket: a #GSocket.
2204 * @cancellable: (allow-none): a %GCancellable or %NULL
2205 * @error: #GError for error reporting, or %NULL to ignore.
2207 * Accept incoming connections on a connection-based socket. This removes
2208 * the first outstanding connection request from the listening socket and
2209 * creates a #GSocket object for it.
2211 * The @socket must be bound to a local address with g_socket_bind() and
2212 * must be listening for incoming connections (g_socket_listen()).
2214 * If there are no outstanding connections then the operation will block
2215 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2216 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2218 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2219 * Free the returned object with g_object_unref().
2224 g_socket_accept (GSocket *socket,
2225 GCancellable *cancellable,
2228 GSocket *new_socket;
2231 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2233 if (!check_socket (socket, error))
2236 if (!check_timeout (socket, error))
2241 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2243 int errsv = get_socket_errno ();
2248 #ifdef WSAEWOULDBLOCK
2249 if (errsv == WSAEWOULDBLOCK)
2251 if (errsv == EWOULDBLOCK ||
2255 win32_unset_event_mask (socket, FD_ACCEPT);
2257 if (socket->priv->blocking)
2259 if (!g_socket_condition_wait (socket,
2260 G_IO_IN, cancellable, error))
2267 g_set_error (error, G_IO_ERROR,
2268 socket_io_error_from_errno (errsv),
2269 _("Error accepting connection: %s"), socket_strerror (errsv));
2275 win32_unset_event_mask (socket, FD_ACCEPT);
2279 /* The socket inherits the accepting sockets event mask and even object,
2280 we need to remove that */
2281 WSAEventSelect (ret, NULL, 0);
2287 /* We always want to set close-on-exec to protect users. If you
2288 need to so some weird inheritance to exec you can re-enable this
2289 using lower level hacks with g_socket_get_fd(). */
2290 flags = fcntl (ret, F_GETFD, 0);
2292 (flags & FD_CLOEXEC) == 0)
2294 flags |= FD_CLOEXEC;
2295 fcntl (ret, F_SETFD, flags);
2300 new_socket = g_socket_new_from_fd (ret, error);
2301 if (new_socket == NULL)
2310 new_socket->priv->protocol = socket->priv->protocol;
2317 * @socket: a #GSocket.
2318 * @address: a #GSocketAddress specifying the remote address.
2319 * @cancellable: (allow-none): a %GCancellable or %NULL
2320 * @error: #GError for error reporting, or %NULL to ignore.
2322 * Connect the socket to the specified remote address.
2324 * For connection oriented socket this generally means we attempt to make
2325 * a connection to the @address. For a connection-less socket it sets
2326 * the default address for g_socket_send() and discards all incoming datagrams
2327 * from other sources.
2329 * Generally connection oriented sockets can only connect once, but
2330 * connection-less sockets can connect multiple times to change the
2333 * If the connect call needs to do network I/O it will block, unless
2334 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2335 * and the user can be notified of the connection finishing by waiting
2336 * for the G_IO_OUT condition. The result of the connection must then be
2337 * checked with g_socket_check_connect_result().
2339 * Returns: %TRUE if connected, %FALSE on error.
2344 g_socket_connect (GSocket *socket,
2345 GSocketAddress *address,
2346 GCancellable *cancellable,
2349 struct sockaddr_storage buffer;
2351 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2353 if (!check_socket (socket, error))
2356 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2359 if (socket->priv->remote_address)
2360 g_object_unref (socket->priv->remote_address);
2361 socket->priv->remote_address = g_object_ref (address);
2365 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2366 g_socket_address_get_native_size (address)) < 0)
2368 int errsv = get_socket_errno ();
2374 if (errsv == EINPROGRESS)
2376 if (errsv == WSAEWOULDBLOCK)
2379 win32_unset_event_mask (socket, FD_CONNECT);
2381 if (socket->priv->blocking)
2383 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2385 if (g_socket_check_connect_result (socket, error))
2391 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2392 _("Connection in progress"));
2393 socket->priv->connect_pending = TRUE;
2397 g_set_error_literal (error, G_IO_ERROR,
2398 socket_io_error_from_errno (errsv),
2399 socket_strerror (errsv));
2406 win32_unset_event_mask (socket, FD_CONNECT);
2408 socket->priv->connected = TRUE;
2414 * g_socket_check_connect_result:
2415 * @socket: a #GSocket
2416 * @error: #GError for error reporting, or %NULL to ignore.
2418 * Checks and resets the pending connect error for the socket.
2419 * This is used to check for errors when g_socket_connect() is
2420 * used in non-blocking mode.
2422 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2427 g_socket_check_connect_result (GSocket *socket,
2432 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2434 if (!check_socket (socket, error))
2437 if (!check_timeout (socket, error))
2440 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
2442 g_prefix_error (error, _("Unable to get pending error: "));
2448 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2449 socket_strerror (value));
2450 if (socket->priv->remote_address)
2452 g_object_unref (socket->priv->remote_address);
2453 socket->priv->remote_address = NULL;
2458 socket->priv->connected = TRUE;
2463 * g_socket_get_available_bytes:
2464 * @socket: a #GSocket
2466 * Get the amount of data pending in the OS input buffer.
2468 * If @socket is a UDP or SCTP socket, this will return the size of
2469 * just the next packet, even if additional packets are buffered after
2472 * Note that on Windows, this function is rather inefficient in the
2473 * UDP case, and so if you know any plausible upper bound on the size
2474 * of the incoming packet, it is better to just do a
2475 * g_socket_receive() with a buffer of that size, rather than calling
2476 * g_socket_get_available_bytes() first and then doing a receive of
2477 * exactly the right size.
2479 * Returns: the number of bytes that can be read from the socket
2480 * without blocking or truncating, or -1 on error.
2485 g_socket_get_available_bytes (GSocket *socket)
2488 const gint bufsize = 64 * 1024;
2489 static guchar *buf = NULL;
2495 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2497 #if defined (SO_NREAD)
2498 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
2500 #elif !defined (G_OS_WIN32)
2501 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2504 if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
2506 if (G_UNLIKELY (g_once_init_enter (&buf)))
2507 g_once_init_leave (&buf, g_malloc (bufsize));
2509 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
2510 if (avail == -1 && get_socket_errno () == WSAEWOULDBLOCK)
2515 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
2525 * @socket: a #GSocket
2526 * @buffer: (array length=size) (element-type guint8): a buffer to
2527 * read data into (which should be at least @size bytes long).
2528 * @size: the number of bytes you want to read from the socket
2529 * @cancellable: (allow-none): a %GCancellable or %NULL
2530 * @error: #GError for error reporting, or %NULL to ignore.
2532 * Receive data (up to @size bytes) from a socket. This is mainly used by
2533 * connection-oriented sockets; it is identical to g_socket_receive_from()
2534 * with @address set to %NULL.
2536 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2537 * g_socket_receive() will always read either 0 or 1 complete messages from
2538 * the socket. If the received message is too large to fit in @buffer, then
2539 * the data beyond @size bytes will be discarded, without any explicit
2540 * indication that this has occurred.
2542 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2543 * number of bytes, up to @size. If more than @size bytes have been
2544 * received, the additional data will be returned in future calls to
2545 * g_socket_receive().
2547 * If the socket is in blocking mode the call will block until there
2548 * is some data to receive, the connection is closed, or there is an
2549 * error. If there is no data available and the socket is in
2550 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2551 * returned. To be notified when data is available, wait for the
2552 * %G_IO_IN condition.
2554 * On error -1 is returned and @error is set accordingly.
2556 * Returns: Number of bytes read, or 0 if the connection was closed by
2557 * the peer, or -1 on error
2562 g_socket_receive (GSocket *socket,
2565 GCancellable *cancellable,
2568 return g_socket_receive_with_blocking (socket, buffer, size,
2569 socket->priv->blocking,
2570 cancellable, error);
2574 * g_socket_receive_with_blocking:
2575 * @socket: a #GSocket
2576 * @buffer: (array length=size) (element-type guint8): a buffer to
2577 * read data into (which should be at least @size bytes long).
2578 * @size: the number of bytes you want to read from the socket
2579 * @blocking: whether to do blocking or non-blocking I/O
2580 * @cancellable: (allow-none): a %GCancellable or %NULL
2581 * @error: #GError for error reporting, or %NULL to ignore.
2583 * This behaves exactly the same as g_socket_receive(), except that
2584 * the choice of blocking or non-blocking behavior is determined by
2585 * the @blocking argument rather than by @socket's properties.
2587 * Returns: Number of bytes read, or 0 if the connection was closed by
2588 * the peer, or -1 on error
2593 g_socket_receive_with_blocking (GSocket *socket,
2597 GCancellable *cancellable,
2602 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2604 if (!check_socket (socket, error))
2607 if (!check_timeout (socket, error))
2610 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2615 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2617 int errsv = get_socket_errno ();
2622 #ifdef WSAEWOULDBLOCK
2623 if (errsv == WSAEWOULDBLOCK)
2625 if (errsv == EWOULDBLOCK ||
2629 win32_unset_event_mask (socket, FD_READ);
2633 if (!g_socket_condition_wait (socket,
2634 G_IO_IN, cancellable, error))
2641 win32_unset_event_mask (socket, FD_READ);
2643 g_set_error (error, G_IO_ERROR,
2644 socket_io_error_from_errno (errsv),
2645 _("Error receiving data: %s"), socket_strerror (errsv));
2649 win32_unset_event_mask (socket, FD_READ);
2658 * g_socket_receive_from:
2659 * @socket: a #GSocket
2660 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2662 * @buffer: (array length=size) (element-type guint8): a buffer to
2663 * read data into (which should be at least @size bytes long).
2664 * @size: the number of bytes you want to read from the socket
2665 * @cancellable: (allow-none): a %GCancellable or %NULL
2666 * @error: #GError for error reporting, or %NULL to ignore.
2668 * Receive data (up to @size bytes) from a socket.
2670 * If @address is non-%NULL then @address will be set equal to the
2671 * source address of the received packet.
2672 * @address is owned by the caller.
2674 * See g_socket_receive() for additional information.
2676 * Returns: Number of bytes read, or 0 if the connection was closed by
2677 * the peer, or -1 on error
2682 g_socket_receive_from (GSocket *socket,
2683 GSocketAddress **address,
2686 GCancellable *cancellable,
2694 return g_socket_receive_message (socket,
2702 /* See the comment about SIGPIPE above. */
2704 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2706 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2711 * @socket: a #GSocket
2712 * @buffer: (array length=size) (element-type guint8): the buffer
2713 * containing the data to send.
2714 * @size: the number of bytes to send
2715 * @cancellable: (allow-none): a %GCancellable or %NULL
2716 * @error: #GError for error reporting, or %NULL to ignore.
2718 * Tries to send @size bytes from @buffer on the socket. This is
2719 * mainly used by connection-oriented sockets; it is identical to
2720 * g_socket_send_to() with @address set to %NULL.
2722 * If the socket is in blocking mode the call will block until there is
2723 * space for the data in the socket queue. If there is no space available
2724 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2725 * will be returned. To be notified when space is available, wait for the
2726 * %G_IO_OUT condition. Note though that you may still receive
2727 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2728 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2729 * very common due to the way the underlying APIs work.)
2731 * On error -1 is returned and @error is set accordingly.
2733 * Returns: Number of bytes written (which may be less than @size), or -1
2739 g_socket_send (GSocket *socket,
2740 const gchar *buffer,
2742 GCancellable *cancellable,
2745 return g_socket_send_with_blocking (socket, buffer, size,
2746 socket->priv->blocking,
2747 cancellable, error);
2751 * g_socket_send_with_blocking:
2752 * @socket: a #GSocket
2753 * @buffer: (array length=size) (element-type guint8): the buffer
2754 * containing the data to send.
2755 * @size: the number of bytes to send
2756 * @blocking: whether to do blocking or non-blocking I/O
2757 * @cancellable: (allow-none): a %GCancellable or %NULL
2758 * @error: #GError for error reporting, or %NULL to ignore.
2760 * This behaves exactly the same as g_socket_send(), except that
2761 * the choice of blocking or non-blocking behavior is determined by
2762 * the @blocking argument rather than by @socket's properties.
2764 * Returns: Number of bytes written (which may be less than @size), or -1
2770 g_socket_send_with_blocking (GSocket *socket,
2771 const gchar *buffer,
2774 GCancellable *cancellable,
2779 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2781 if (!check_socket (socket, error))
2784 if (!check_timeout (socket, error))
2787 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2792 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2794 int errsv = get_socket_errno ();
2799 #ifdef WSAEWOULDBLOCK
2800 if (errsv == WSAEWOULDBLOCK)
2802 if (errsv == EWOULDBLOCK ||
2806 win32_unset_event_mask (socket, FD_WRITE);
2810 if (!g_socket_condition_wait (socket,
2811 G_IO_OUT, cancellable, error))
2818 g_set_error (error, G_IO_ERROR,
2819 socket_io_error_from_errno (errsv),
2820 _("Error sending data: %s"), socket_strerror (errsv));
2831 * @socket: a #GSocket
2832 * @address: (allow-none): a #GSocketAddress, or %NULL
2833 * @buffer: (array length=size) (element-type guint8): the buffer
2834 * containing the data to send.
2835 * @size: the number of bytes to send
2836 * @cancellable: (allow-none): a %GCancellable or %NULL
2837 * @error: #GError for error reporting, or %NULL to ignore.
2839 * Tries to send @size bytes from @buffer to @address. If @address is
2840 * %NULL then the message is sent to the default receiver (set by
2841 * g_socket_connect()).
2843 * See g_socket_send() for additional information.
2845 * Returns: Number of bytes written (which may be less than @size), or -1
2851 g_socket_send_to (GSocket *socket,
2852 GSocketAddress *address,
2853 const gchar *buffer,
2855 GCancellable *cancellable,
2863 return g_socket_send_message (socket,
2873 * g_socket_shutdown:
2874 * @socket: a #GSocket
2875 * @shutdown_read: whether to shut down the read side
2876 * @shutdown_write: whether to shut down the write side
2877 * @error: #GError for error reporting, or %NULL to ignore.
2879 * Shut down part of a full-duplex connection.
2881 * If @shutdown_read is %TRUE then the receiving side of the connection
2882 * is shut down, and further reading is disallowed.
2884 * If @shutdown_write is %TRUE then the sending side of the connection
2885 * is shut down, and further writing is disallowed.
2887 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2889 * One example where this is used is graceful disconnect for TCP connections
2890 * where you close the sending side, then wait for the other side to close
2891 * the connection, thus ensuring that the other side saw all sent data.
2893 * Returns: %TRUE on success, %FALSE on error
2898 g_socket_shutdown (GSocket *socket,
2899 gboolean shutdown_read,
2900 gboolean shutdown_write,
2905 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2907 if (!check_socket (socket, error))
2911 if (!shutdown_read && !shutdown_write)
2915 if (shutdown_read && shutdown_write)
2917 else if (shutdown_read)
2922 if (shutdown_read && shutdown_write)
2924 else if (shutdown_read)
2930 if (shutdown (socket->priv->fd, how) != 0)
2932 int errsv = get_socket_errno ();
2933 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2934 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2938 if (shutdown_read && shutdown_write)
2939 socket->priv->connected = FALSE;
2946 * @socket: a #GSocket
2947 * @error: #GError for error reporting, or %NULL to ignore.
2949 * Closes the socket, shutting down any active connection.
2951 * Closing a socket does not wait for all outstanding I/O operations
2952 * to finish, so the caller should not rely on them to be guaranteed
2953 * to complete even if the close returns with no error.
2955 * Once the socket is closed, all other operations will return
2956 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2959 * Sockets will be automatically closed when the last reference
2960 * is dropped, but you might want to call this function to make sure
2961 * resources are released as early as possible.
2963 * Beware that due to the way that TCP works, it is possible for
2964 * recently-sent data to be lost if either you close a socket while the
2965 * %G_IO_IN condition is set, or else if the remote connection tries to
2966 * send something to you after you close the socket but before it has
2967 * finished reading all of the data you sent. There is no easy generic
2968 * way to avoid this problem; the easiest fix is to design the network
2969 * protocol such that the client will never send data "out of turn".
2970 * Another solution is for the server to half-close the connection by
2971 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2972 * and then wait for the client to notice this and close its side of the
2973 * connection, after which the server can safely call g_socket_close().
2974 * (This is what #GTcpConnection does if you call
2975 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2976 * only works if the client will close its connection after the server
2979 * Returns: %TRUE on success, %FALSE on error
2984 g_socket_close (GSocket *socket,
2989 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2991 if (socket->priv->closed)
2992 return TRUE; /* Multiple close not an error */
2994 if (!check_socket (socket, error))
3000 res = closesocket (socket->priv->fd);
3002 res = close (socket->priv->fd);
3006 int errsv = get_socket_errno ();
3011 g_set_error (error, G_IO_ERROR,
3012 socket_io_error_from_errno (errsv),
3013 _("Error closing socket: %s"),
3014 socket_strerror (errsv));
3020 socket->priv->connected = FALSE;
3021 socket->priv->closed = TRUE;
3022 if (socket->priv->remote_address)
3024 g_object_unref (socket->priv->remote_address);
3025 socket->priv->remote_address = NULL;
3032 * g_socket_is_closed:
3033 * @socket: a #GSocket
3035 * Checks whether a socket is closed.
3037 * Returns: %TRUE if socket is closed, %FALSE otherwise
3042 g_socket_is_closed (GSocket *socket)
3044 return socket->priv->closed;
3048 /* Broken source, used on errors */
3050 broken_dispatch (GSource *source,
3051 GSourceFunc callback,
3057 static GSourceFuncs broken_funcs =
3066 network_events_for_condition (GIOCondition condition)
3070 if (condition & G_IO_IN)
3071 event_mask |= (FD_READ | FD_ACCEPT);
3072 if (condition & G_IO_OUT)
3073 event_mask |= (FD_WRITE | FD_CONNECT);
3074 event_mask |= FD_CLOSE;
3080 ensure_event (GSocket *socket)
3082 if (socket->priv->event == WSA_INVALID_EVENT)
3083 socket->priv->event = WSACreateEvent();
3087 update_select_events (GSocket *socket)
3094 ensure_event (socket);
3097 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3100 event_mask |= network_events_for_condition (*ptr);
3103 if (event_mask != socket->priv->selected_events)
3105 /* If no events selected, disable event so we can unset
3108 if (event_mask == 0)
3111 event = socket->priv->event;
3113 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3114 socket->priv->selected_events = event_mask;
3119 add_condition_watch (GSocket *socket,
3120 GIOCondition *condition)
3122 g_mutex_lock (&socket->priv->win32_source_lock);
3123 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3125 socket->priv->requested_conditions =
3126 g_list_prepend (socket->priv->requested_conditions, condition);
3128 update_select_events (socket);
3129 g_mutex_unlock (&socket->priv->win32_source_lock);
3133 remove_condition_watch (GSocket *socket,
3134 GIOCondition *condition)
3136 g_mutex_lock (&socket->priv->win32_source_lock);
3137 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3139 socket->priv->requested_conditions =
3140 g_list_remove (socket->priv->requested_conditions, condition);
3142 update_select_events (socket);
3143 g_mutex_unlock (&socket->priv->win32_source_lock);
3147 update_condition (GSocket *socket)
3149 WSANETWORKEVENTS events;
3150 GIOCondition condition;
3152 if (WSAEnumNetworkEvents (socket->priv->fd,
3153 socket->priv->event,
3156 socket->priv->current_events |= events.lNetworkEvents;
3157 if (events.lNetworkEvents & FD_WRITE &&
3158 events.iErrorCode[FD_WRITE_BIT] != 0)
3159 socket->priv->current_errors |= FD_WRITE;
3160 if (events.lNetworkEvents & FD_CONNECT &&
3161 events.iErrorCode[FD_CONNECT_BIT] != 0)
3162 socket->priv->current_errors |= FD_CONNECT;
3166 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3167 condition |= G_IO_IN;
3169 if (socket->priv->current_events & FD_CLOSE)
3171 int r, errsv, buffer;
3173 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3175 errsv = get_socket_errno ();
3178 (r < 0 && errsv == WSAENOTCONN))
3179 condition |= G_IO_IN;
3181 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3182 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3183 condition |= G_IO_HUP;
3185 condition |= G_IO_ERR;
3188 if (socket->priv->closed)
3189 condition |= G_IO_HUP;
3191 /* Never report both G_IO_OUT and HUP, these are
3192 mutually exclusive (can't write to a closed socket) */
3193 if ((condition & G_IO_HUP) == 0 &&
3194 socket->priv->current_events & FD_WRITE)
3196 if (socket->priv->current_errors & FD_WRITE)
3197 condition |= G_IO_ERR;
3199 condition |= G_IO_OUT;
3203 if (socket->priv->current_events & FD_CONNECT)
3205 if (socket->priv->current_errors & FD_CONNECT)
3206 condition |= (G_IO_HUP | G_IO_ERR);
3208 condition |= G_IO_OUT;
3224 GIOCondition condition;
3229 socket_source_prepare_win32 (GSource *source,
3232 GSocketSource *socket_source = (GSocketSource *)source;
3236 return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3240 socket_source_check_win32 (GSource *source)
3244 return socket_source_prepare_win32 (source, &timeout);
3249 socket_source_dispatch (GSource *source,
3250 GSourceFunc callback,
3253 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3254 GSocketSource *socket_source = (GSocketSource *)source;
3255 GSocket *socket = socket_source->socket;
3261 events = update_condition (socket_source->socket);
3263 events = g_source_query_unix_fd (source, socket_source->fd_tag);
3266 timeout = g_source_get_ready_time (source);
3267 if (timeout >= 0 && timeout < g_source_get_time (source))
3269 socket->priv->timed_out = TRUE;
3270 events |= (G_IO_IN | G_IO_OUT);
3273 ret = (*func) (socket, events & socket_source->condition, user_data);
3275 if (socket->priv->timeout)
3276 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3278 g_source_set_ready_time (source, -1);
3284 socket_source_finalize (GSource *source)
3286 GSocketSource *socket_source = (GSocketSource *)source;
3289 socket = socket_source->socket;
3292 remove_condition_watch (socket, &socket_source->condition);
3295 g_object_unref (socket);
3299 socket_source_closure_callback (GSocket *socket,
3300 GIOCondition condition,
3303 GClosure *closure = data;
3305 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3306 GValue result_value = G_VALUE_INIT;
3309 g_value_init (&result_value, G_TYPE_BOOLEAN);
3311 g_value_init (¶ms[0], G_TYPE_SOCKET);
3312 g_value_set_object (¶ms[0], socket);
3313 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
3314 g_value_set_flags (¶ms[1], condition);
3316 g_closure_invoke (closure, &result_value, 2, params, NULL);
3318 result = g_value_get_boolean (&result_value);
3319 g_value_unset (&result_value);
3320 g_value_unset (¶ms[0]);
3321 g_value_unset (¶ms[1]);
3326 static GSourceFuncs socket_source_funcs =
3329 socket_source_prepare_win32,
3330 socket_source_check_win32,
3332 NULL, NULL, /* check, prepare */
3334 socket_source_dispatch,
3335 socket_source_finalize,
3336 (GSourceFunc)socket_source_closure_callback,
3340 socket_source_new (GSocket *socket,
3341 GIOCondition condition,
3342 GCancellable *cancellable)
3345 GSocketSource *socket_source;
3348 ensure_event (socket);
3350 if (socket->priv->event == WSA_INVALID_EVENT)
3352 g_warning ("Failed to create WSAEvent");
3353 return g_source_new (&broken_funcs, sizeof (GSource));
3357 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
3359 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3360 g_source_set_name (source, "GSocket");
3361 socket_source = (GSocketSource *)source;
3363 socket_source->socket = g_object_ref (socket);
3364 socket_source->condition = condition;
3368 GSource *cancellable_source;
3370 cancellable_source = g_cancellable_source_new (cancellable);
3371 g_source_add_child_source (source, cancellable_source);
3372 g_source_set_dummy_callback (cancellable_source);
3373 g_source_unref (cancellable_source);
3377 add_condition_watch (socket, &socket_source->condition);
3378 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3379 socket_source->pollfd.events = condition;
3380 socket_source->pollfd.revents = 0;
3381 g_source_add_poll (source, &socket_source->pollfd);
3383 socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
3386 if (socket->priv->timeout)
3387 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3389 g_source_set_ready_time (source, -1);
3395 * g_socket_create_source: (skip)
3396 * @socket: a #GSocket
3397 * @condition: a #GIOCondition mask to monitor
3398 * @cancellable: (allow-none): a %GCancellable or %NULL
3400 * Creates a #GSource that can be attached to a %GMainContext to monitor
3401 * for the availability of the specified @condition on the socket. The #GSource
3402 * keeps a reference to the @socket.
3404 * The callback on the source is of the #GSocketSourceFunc type.
3406 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3407 * these conditions will always be reported output if they are true.
3409 * @cancellable if not %NULL can be used to cancel the source, which will
3410 * cause the source to trigger, reporting the current condition (which
3411 * is likely 0 unless cancellation happened at the same time as a
3412 * condition change). You can check for this in the callback using
3413 * g_cancellable_is_cancelled().
3415 * If @socket has a timeout set, and it is reached before @condition
3416 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3417 * %G_IO_OUT depending on @condition. However, @socket will have been
3418 * marked as having had a timeout, and so the next #GSocket I/O method
3419 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3421 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3426 g_socket_create_source (GSocket *socket,
3427 GIOCondition condition,
3428 GCancellable *cancellable)
3430 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3432 return socket_source_new (socket, condition, cancellable);
3436 * g_socket_condition_check:
3437 * @socket: a #GSocket
3438 * @condition: a #GIOCondition mask to check
3440 * Checks on the readiness of @socket to perform operations.
3441 * The operations specified in @condition are checked for and masked
3442 * against the currently-satisfied conditions on @socket. The result
3445 * Note that on Windows, it is possible for an operation to return
3446 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3447 * g_socket_condition_check() has claimed that the socket is ready for
3448 * writing. Rather than calling g_socket_condition_check() and then
3449 * writing to the socket if it succeeds, it is generally better to
3450 * simply try writing to the socket right away, and try again later if
3451 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3453 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3454 * these conditions will always be set in the output if they are true.
3456 * This call never blocks.
3458 * Returns: the @GIOCondition mask of the current state
3463 g_socket_condition_check (GSocket *socket,
3464 GIOCondition condition)
3466 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3468 if (!check_socket (socket, NULL))
3473 GIOCondition current_condition;
3475 condition |= G_IO_ERR | G_IO_HUP;
3477 add_condition_watch (socket, &condition);
3478 current_condition = update_condition (socket);
3479 remove_condition_watch (socket, &condition);
3480 return condition & current_condition;
3486 poll_fd.fd = socket->priv->fd;
3487 poll_fd.events = condition;
3488 poll_fd.revents = 0;
3491 result = g_poll (&poll_fd, 1, 0);
3492 while (result == -1 && get_socket_errno () == EINTR);
3494 return poll_fd.revents;
3500 * g_socket_condition_wait:
3501 * @socket: a #GSocket
3502 * @condition: a #GIOCondition mask to wait for
3503 * @cancellable: (allow-none): a #GCancellable, or %NULL
3504 * @error: a #GError pointer, or %NULL
3506 * Waits for @condition to become true on @socket. When the condition
3507 * is met, %TRUE is returned.
3509 * If @cancellable is cancelled before the condition is met, or if the
3510 * socket has a timeout set and it is reached before the condition is
3511 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3512 * the appropriate value (%G_IO_ERROR_CANCELLED or
3513 * %G_IO_ERROR_TIMED_OUT).
3515 * See also g_socket_condition_timed_wait().
3517 * Returns: %TRUE if the condition was met, %FALSE otherwise
3522 g_socket_condition_wait (GSocket *socket,
3523 GIOCondition condition,
3524 GCancellable *cancellable,
3527 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3529 return g_socket_condition_timed_wait (socket, condition, -1,
3530 cancellable, error);
3534 * g_socket_condition_timed_wait:
3535 * @socket: a #GSocket
3536 * @condition: a #GIOCondition mask to wait for
3537 * @timeout: the maximum time (in microseconds) to wait, or -1
3538 * @cancellable: (allow-none): a #GCancellable, or %NULL
3539 * @error: a #GError pointer, or %NULL
3541 * Waits for up to @timeout microseconds for @condition to become true
3542 * on @socket. If the condition is met, %TRUE is returned.
3544 * If @cancellable is cancelled before the condition is met, or if
3545 * @timeout (or the socket's #GSocket:timeout) is reached before the
3546 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3547 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3548 * %G_IO_ERROR_TIMED_OUT).
3550 * If you don't want a timeout, use g_socket_condition_wait().
3551 * (Alternatively, you can pass -1 for @timeout.)
3553 * Note that although @timeout is in microseconds for consistency with
3554 * other GLib APIs, this function actually only has millisecond
3555 * resolution, and the behavior is undefined if @timeout is not an
3556 * exact number of milliseconds.
3558 * Returns: %TRUE if the condition was met, %FALSE otherwise
3563 g_socket_condition_timed_wait (GSocket *socket,
3564 GIOCondition condition,
3566 GCancellable *cancellable,
3571 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3573 if (!check_socket (socket, error))
3576 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3579 if (socket->priv->timeout &&
3580 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3581 timeout = socket->priv->timeout * 1000;
3582 else if (timeout != -1)
3583 timeout = timeout / 1000;
3585 start_time = g_get_monotonic_time ();
3589 GIOCondition current_condition;
3595 /* Always check these */
3596 condition |= G_IO_ERR | G_IO_HUP;
3598 add_condition_watch (socket, &condition);
3601 events[num_events++] = socket->priv->event;
3603 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3604 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3607 timeout = WSA_INFINITE;
3609 current_condition = update_condition (socket);
3610 while ((condition & current_condition) == 0)
3612 res = WSAWaitForMultipleEvents (num_events, events,
3613 FALSE, timeout, FALSE);
3614 if (res == WSA_WAIT_FAILED)
3616 int errsv = get_socket_errno ();
3618 g_set_error (error, G_IO_ERROR,
3619 socket_io_error_from_errno (errsv),
3620 _("Waiting for socket condition: %s"),
3621 socket_strerror (errsv));
3624 else if (res == WSA_WAIT_TIMEOUT)
3626 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3627 _("Socket I/O timed out"));
3631 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3634 current_condition = update_condition (socket);
3636 if (timeout != WSA_INFINITE)
3638 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3643 remove_condition_watch (socket, &condition);
3645 g_cancellable_release_fd (cancellable);
3647 return (condition & current_condition) != 0;
3655 poll_fd[0].fd = socket->priv->fd;
3656 poll_fd[0].events = condition;
3659 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3664 result = g_poll (poll_fd, num, timeout);
3665 if (result != -1 || errno != EINTR)
3670 timeout -= (g_get_monotonic_time () - start_time) / 1000;
3677 g_cancellable_release_fd (cancellable);
3681 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3682 _("Socket I/O timed out"));
3686 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3692 * g_socket_send_message:
3693 * @socket: a #GSocket
3694 * @address: (allow-none): a #GSocketAddress, or %NULL
3695 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3696 * @num_vectors: the number of elements in @vectors, or -1
3697 * @messages: (array length=num_messages) (allow-none): a pointer to an
3698 * array of #GSocketControlMessages, or %NULL.
3699 * @num_messages: number of elements in @messages, or -1.
3700 * @flags: an int containing #GSocketMsgFlags flags
3701 * @cancellable: (allow-none): a %GCancellable or %NULL
3702 * @error: #GError for error reporting, or %NULL to ignore.
3704 * Send data to @address on @socket. This is the most complicated and
3705 * fully-featured version of this call. For easier use, see
3706 * g_socket_send() and g_socket_send_to().
3708 * If @address is %NULL then the message is sent to the default receiver
3709 * (set by g_socket_connect()).
3711 * @vectors must point to an array of #GOutputVector structs and
3712 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3713 * then @vectors is assumed to be terminated by a #GOutputVector with a
3714 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3715 * that the sent data will be gathered from. Using multiple
3716 * #GOutputVectors is more memory-efficient than manually copying
3717 * data from multiple sources into a single buffer, and more
3718 * network-efficient than making multiple calls to g_socket_send().
3720 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3721 * #GSocketControlMessage instances. These correspond to the control
3722 * messages to be sent on the socket.
3723 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3726 * @flags modify how the message is sent. The commonly available arguments
3727 * for this are available in the #GSocketMsgFlags enum, but the
3728 * values there are the same as the system values, and the flags
3729 * are passed in as-is, so you can pass in system-specific flags too.
3731 * If the socket is in blocking mode the call will block until there is
3732 * space for the data in the socket queue. If there is no space available
3733 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3734 * will be returned. To be notified when space is available, wait for the
3735 * %G_IO_OUT condition. Note though that you may still receive
3736 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3737 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3738 * very common due to the way the underlying APIs work.)
3740 * On error -1 is returned and @error is set accordingly.
3742 * Returns: Number of bytes written (which may be less than @size), or -1
3748 g_socket_send_message (GSocket *socket,
3749 GSocketAddress *address,
3750 GOutputVector *vectors,
3752 GSocketControlMessage **messages,
3755 GCancellable *cancellable,
3758 GOutputVector one_vector;
3761 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3762 g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), -1);
3763 g_return_val_if_fail (num_vectors == 0 || vectors != NULL, -1);
3764 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
3765 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
3766 g_return_val_if_fail (error == NULL || *error == NULL, -1);
3768 if (!check_socket (socket, error))
3771 if (!check_timeout (socket, error))
3774 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3777 if (num_vectors == -1)
3779 for (num_vectors = 0;
3780 vectors[num_vectors].buffer != NULL;
3785 if (num_messages == -1)
3787 for (num_messages = 0;
3788 messages != NULL && messages[num_messages] != NULL;
3793 if (num_vectors == 0)
3797 one_vector.buffer = &zero;
3798 one_vector.size = 1;
3800 vectors = &one_vector;
3813 msg.msg_namelen = g_socket_address_get_native_size (address);
3814 msg.msg_name = g_alloca (msg.msg_namelen);
3815 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3820 msg.msg_name = NULL;
3821 msg.msg_namelen = 0;
3826 /* this entire expression will be evaluated at compile time */
3827 if (sizeof *msg.msg_iov == sizeof *vectors &&
3828 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3829 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3830 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3831 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3832 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3833 G_STRUCT_OFFSET (GOutputVector, size))
3834 /* ABI is compatible */
3836 msg.msg_iov = (struct iovec *) vectors;
3837 msg.msg_iovlen = num_vectors;
3840 /* ABI is incompatible */
3844 msg.msg_iov = g_newa (struct iovec, num_vectors);
3845 for (i = 0; i < num_vectors; i++)
3847 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3848 msg.msg_iov[i].iov_len = vectors[i].size;
3850 msg.msg_iovlen = num_vectors;
3856 struct cmsghdr *cmsg;
3859 msg.msg_controllen = 0;
3860 for (i = 0; i < num_messages; i++)
3861 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3863 if (msg.msg_controllen == 0)
3864 msg.msg_control = NULL;
3867 msg.msg_control = g_alloca (msg.msg_controllen);
3868 memset (msg.msg_control, '\0', msg.msg_controllen);
3871 cmsg = CMSG_FIRSTHDR (&msg);
3872 for (i = 0; i < num_messages; i++)
3874 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3875 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3876 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3877 g_socket_control_message_serialize (messages[i],
3879 cmsg = CMSG_NXTHDR (&msg, cmsg);
3881 g_assert (cmsg == NULL);
3886 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3889 int errsv = get_socket_errno ();
3894 if (socket->priv->blocking &&
3895 (errsv == EWOULDBLOCK ||
3898 if (!g_socket_condition_wait (socket,
3899 G_IO_OUT, cancellable, error))
3905 g_set_error (error, G_IO_ERROR,
3906 socket_io_error_from_errno (errsv),
3907 _("Error sending message: %s"), socket_strerror (errsv));
3918 struct sockaddr_storage addr;
3925 /* Win32 doesn't support control messages.
3926 Actually this is possible for raw and datagram sockets
3927 via WSASendMessage on Vista or later, but that doesn't
3929 if (num_messages != 0)
3931 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3932 _("GSocketControlMessage not supported on Windows"));
3937 bufs = g_newa (WSABUF, num_vectors);
3938 for (i = 0; i < num_vectors; i++)
3940 bufs[i].buf = (char *)vectors[i].buffer;
3941 bufs[i].len = (gulong)vectors[i].size;
3945 addrlen = 0; /* Avoid warning */
3948 addrlen = g_socket_address_get_native_size (address);
3949 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3956 result = WSASendTo (socket->priv->fd,
3959 (const struct sockaddr *)&addr, addrlen,
3962 result = WSASend (socket->priv->fd,
3969 int errsv = get_socket_errno ();
3971 if (errsv == WSAEINTR)
3974 if (errsv == WSAEWOULDBLOCK)
3976 win32_unset_event_mask (socket, FD_WRITE);
3978 if (socket->priv->blocking)
3980 if (!g_socket_condition_wait (socket,
3981 G_IO_OUT, cancellable, error))
3988 g_set_error (error, G_IO_ERROR,
3989 socket_io_error_from_errno (errsv),
3990 _("Error sending message: %s"), socket_strerror (errsv));
4003 * g_socket_send_messages:
4004 * @socket: a #GSocket
4005 * @messages: (array length=num_messages): an array of #GOutputMessage structs
4006 * @num_messages: the number of elements in @messages
4007 * @flags: an int containing #GSocketMsgFlags flags
4008 * @cancellable: (allow-none): a %GCancellable or %NULL
4009 * @error: #GError for error reporting, or %NULL to ignore.
4011 * Send multiple data messages from @socket in one go. This is the most
4012 * complicated and fully-featured version of this call. For easier use, see
4013 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
4015 * @messages must point to an array of #GOutputMessage structs and
4016 * @num_messages must be the length of this array. Each #GOutputMessage
4017 * contains an address to send the data to, and a pointer to an array of
4018 * #GOutputVector structs to describe the buffers that the data to be sent
4019 * for each message will be gathered from. Using multiple #GOutputVectors is
4020 * more memory-efficient than manually copying data from multiple sources
4021 * into a single buffer, and more network-efficient than making multiple
4022 * calls to g_socket_send(). Sending multiple messages in one go avoids the
4023 * overhead of making a lot of syscalls in scenarios where a lot of data
4024 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
4025 * or where the same data needs to be sent to multiple recipients.
4027 * @flags modify how the message is sent. The commonly available arguments
4028 * for this are available in the #GSocketMsgFlags enum, but the
4029 * values there are the same as the system values, and the flags
4030 * are passed in as-is, so you can pass in system-specific flags too.
4032 * If the socket is in blocking mode the call will block until there is
4033 * space for all the data in the socket queue. If there is no space available
4034 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4035 * will be returned if no data was written at all, otherwise the number of
4036 * messages sent will be returned. To be notified when space is available,
4037 * wait for the %G_IO_OUT condition. Note though that you may still receive
4038 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4039 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4040 * very common due to the way the underlying APIs work.)
4042 * On error -1 is returned and @error is set accordingly.
4044 * Returns: number of messages sent, or -1 on error. Note that the number of
4045 * messages sent may be smaller than @num_messages if the socket is
4046 * non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
4047 * in which case the caller may re-try to send the remaining messages.
4052 g_socket_send_messages (GSocket *socket,
4053 GOutputMessage *messages,
4056 GCancellable *cancellable,
4059 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4060 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
4061 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
4062 g_return_val_if_fail (error == NULL || *error == NULL, -1);
4064 if (!check_socket (socket, error))
4067 if (!check_timeout (socket, error))
4070 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4073 if (num_messages == 0)
4076 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
4078 struct mmsghdr *msgvec;
4079 gint i, num_sent, result, max_sent;
4082 #define MAX_NUM_MESSAGES UIO_MAXIOV
4084 #define MAX_NUM_MESSAGES 1024
4087 if (num_messages > MAX_NUM_MESSAGES)
4088 num_messages = MAX_NUM_MESSAGES;
4090 msgvec = g_newa (struct mmsghdr, num_messages);
4092 for (i = 0; i < num_messages; ++i)
4094 GOutputMessage *msg = &messages[i];
4095 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
4097 msgvec[i].msg_len = 0;
4099 msg_hdr->msg_flags = 0;
4102 if (i > 0 && msg->address == messages[i-1].address)
4104 msg_hdr->msg_name = msgvec[i-1].msg_hdr.msg_name;
4105 msg_hdr->msg_namelen = msgvec[i-1].msg_hdr.msg_namelen;
4107 else if (msg->address)
4109 msg_hdr->msg_namelen = g_socket_address_get_native_size (msg->address);
4110 msg_hdr->msg_name = g_alloca (msg_hdr->msg_namelen);
4111 if (!g_socket_address_to_native (msg->address, msg_hdr->msg_name, msg_hdr->msg_namelen, error))
4116 msg_hdr->msg_name = NULL;
4117 msg_hdr->msg_namelen = 0;
4122 /* this entire expression will be evaluated at compile time */
4123 if (sizeof (struct iovec) == sizeof (GOutputVector) &&
4124 sizeof msg_hdr->msg_iov->iov_base == sizeof msg->vectors->buffer &&
4125 G_STRUCT_OFFSET (struct iovec, iov_base) ==
4126 G_STRUCT_OFFSET (GOutputVector, buffer) &&
4127 sizeof msg_hdr->msg_iov->iov_len == sizeof msg->vectors->size &&
4128 G_STRUCT_OFFSET (struct iovec, iov_len) ==
4129 G_STRUCT_OFFSET (GOutputVector, size))
4130 /* ABI is compatible */
4132 msg_hdr->msg_iov = (struct iovec *) msg->vectors;
4133 msg_hdr->msg_iovlen = msg->num_vectors;
4136 /* ABI is incompatible */
4140 msg_hdr->msg_iov = g_newa (struct iovec, msg->num_vectors);
4141 for (j = 0; j < msg->num_vectors; j++)
4143 msg_hdr->msg_iov[j].iov_base = (void *) msg->vectors[j].buffer;
4144 msg_hdr->msg_iov[j].iov_len = msg->vectors[j].size;
4146 msg_hdr->msg_iovlen = msg->num_vectors;
4152 struct cmsghdr *cmsg;
4155 msg_hdr->msg_controllen = 0;
4156 for (j = 0; j < msg->num_control_messages; j++)
4157 msg_hdr->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (msg->control_messages[j]));
4159 if (msg_hdr->msg_controllen == 0)
4160 msg_hdr->msg_control = NULL;
4163 msg_hdr->msg_control = g_alloca (msg_hdr->msg_controllen);
4164 memset (msg_hdr->msg_control, '\0', msg_hdr->msg_controllen);
4167 cmsg = CMSG_FIRSTHDR (msg_hdr);
4168 for (j = 0; j < msg->num_control_messages; j++)
4170 GSocketControlMessage *cm = msg->control_messages[j];
4172 cmsg->cmsg_level = g_socket_control_message_get_level (cm);
4173 cmsg->cmsg_type = g_socket_control_message_get_msg_type (cm);
4174 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (cm));
4175 g_socket_control_message_serialize (cm, CMSG_DATA (cmsg));
4176 cmsg = CMSG_NXTHDR (msg_hdr, cmsg);
4178 g_assert (cmsg == NULL);
4182 num_sent = result = 0;
4183 max_sent = num_messages;
4184 while (num_sent < num_messages)
4188 if (socket->priv->blocking &&
4189 !g_socket_condition_wait (socket,
4190 G_IO_OUT, cancellable, error))
4193 ret = sendmmsg (socket->priv->fd, msgvec + num_sent, num_messages - num_sent,
4194 flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4198 int errsv = get_socket_errno ();
4203 if (socket->priv->blocking &&
4204 (errsv == EWOULDBLOCK ||
4209 (errsv == EWOULDBLOCK ||
4212 max_sent = num_sent;
4216 g_set_error (error, G_IO_ERROR,
4217 socket_io_error_from_errno (errsv),
4218 _("Error sending message: %s"), socket_strerror (errsv));
4220 /* we have to iterate over all messages below now, because we don't
4221 * know where between num_sent and num_messages the error occured */
4222 max_sent = num_messages;
4232 for (i = 0; i < max_sent; ++i)
4233 messages[i].bytes_sent = msgvec[i].msg_len;
4242 for (i = 0; i < num_messages; ++i)
4244 GOutputMessage *msg = &messages[i];
4245 GError *msg_error = NULL;
4247 result = g_socket_send_message (socket, msg->address,
4248 msg->vectors, msg->num_vectors,
4249 msg->control_messages,
4250 msg->num_control_messages,
4251 flags, cancellable, &msg_error);
4255 /* if we couldn't send all messages, just return how many we did
4256 * manage to send, provided we managed to send at least one */
4257 if (msg_error->code == G_IO_ERROR_WOULD_BLOCK && i > 0)
4259 g_error_free (msg_error);
4264 g_propagate_error (error, msg_error);
4269 msg->bytes_sent = result;
4277 static GSocketAddress *
4278 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
4280 GSocketAddress *saddr;
4282 guint64 oldest_time = G_MAXUINT64;
4283 gint oldest_index = 0;
4285 if (native_len <= 0)
4289 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
4291 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
4292 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
4293 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
4298 if (tmp_native_len != native_len)
4301 if (memcmp (tmp_native, native, native_len) == 0)
4303 saddr = g_object_ref (tmp);
4304 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
4308 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
4310 oldest_time = socket->priv->recv_addr_cache[i].last_used;
4315 saddr = g_socket_address_new_from_native (native, native_len);
4317 if (socket->priv->recv_addr_cache[oldest_index].addr)
4319 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
4320 g_free (socket->priv->recv_addr_cache[oldest_index].native);
4323 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
4324 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
4325 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
4326 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
4332 * g_socket_receive_message:
4333 * @socket: a #GSocket
4334 * @address: (out) (allow-none): a pointer to a #GSocketAddress
4336 * @vectors: (array length=num_vectors): an array of #GInputVector structs
4337 * @num_vectors: the number of elements in @vectors, or -1
4338 * @messages: (array length=num_messages) (allow-none): a pointer which
4339 * may be filled with an array of #GSocketControlMessages, or %NULL
4340 * @num_messages: a pointer which will be filled with the number of
4341 * elements in @messages, or %NULL
4342 * @flags: a pointer to an int containing #GSocketMsgFlags flags
4343 * @cancellable: (allow-none): a %GCancellable or %NULL
4344 * @error: a #GError pointer, or %NULL
4346 * Receive data from a socket. This is the most complicated and
4347 * fully-featured version of this call. For easier use, see
4348 * g_socket_receive() and g_socket_receive_from().
4350 * If @address is non-%NULL then @address will be set equal to the
4351 * source address of the received packet.
4352 * @address is owned by the caller.
4354 * @vector must point to an array of #GInputVector structs and
4355 * @num_vectors must be the length of this array. These structs
4356 * describe the buffers that received data will be scattered into.
4357 * If @num_vectors is -1, then @vectors is assumed to be terminated
4358 * by a #GInputVector with a %NULL buffer pointer.
4360 * As a special case, if @num_vectors is 0 (in which case, @vectors
4361 * may of course be %NULL), then a single byte is received and
4362 * discarded. This is to facilitate the common practice of sending a
4363 * single '\0' byte for the purposes of transferring ancillary data.
4365 * @messages, if non-%NULL, will be set to point to a newly-allocated
4366 * array of #GSocketControlMessage instances or %NULL if no such
4367 * messages was received. These correspond to the control messages
4368 * received from the kernel, one #GSocketControlMessage per message
4369 * from the kernel. This array is %NULL-terminated and must be freed
4370 * by the caller using g_free() after calling g_object_unref() on each
4371 * element. If @messages is %NULL, any control messages received will
4374 * @num_messages, if non-%NULL, will be set to the number of control
4375 * messages received.
4377 * If both @messages and @num_messages are non-%NULL, then
4378 * @num_messages gives the number of #GSocketControlMessage instances
4379 * in @messages (ie: not including the %NULL terminator).
4381 * @flags is an in/out parameter. The commonly available arguments
4382 * for this are available in the #GSocketMsgFlags enum, but the
4383 * values there are the same as the system values, and the flags
4384 * are passed in as-is, so you can pass in system-specific flags too
4385 * (and g_socket_receive_message() may pass system-specific flags out).
4387 * As with g_socket_receive(), data may be discarded if @socket is
4388 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
4389 * provide enough buffer space to read a complete message. You can pass
4390 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
4391 * removing it from the receive queue, but there is no portable way to find
4392 * out the length of the message other than by reading it into a
4393 * sufficiently-large buffer.
4395 * If the socket is in blocking mode the call will block until there
4396 * is some data to receive, the connection is closed, or there is an
4397 * error. If there is no data available and the socket is in
4398 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
4399 * returned. To be notified when data is available, wait for the
4400 * %G_IO_IN condition.
4402 * On error -1 is returned and @error is set accordingly.
4404 * Returns: Number of bytes read, or 0 if the connection was closed by
4405 * the peer, or -1 on error
4410 g_socket_receive_message (GSocket *socket,
4411 GSocketAddress **address,
4412 GInputVector *vectors,
4414 GSocketControlMessage ***messages,
4417 GCancellable *cancellable,
4420 GInputVector one_vector;
4423 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4425 if (!check_socket (socket, error))
4428 if (!check_timeout (socket, error))
4431 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4434 if (num_vectors == -1)
4436 for (num_vectors = 0;
4437 vectors[num_vectors].buffer != NULL;
4442 if (num_vectors == 0)
4444 one_vector.buffer = &one_byte;
4445 one_vector.size = 1;
4447 vectors = &one_vector;
4454 struct sockaddr_storage one_sockaddr;
4459 msg.msg_name = &one_sockaddr;
4460 msg.msg_namelen = sizeof (struct sockaddr_storage);
4464 msg.msg_name = NULL;
4465 msg.msg_namelen = 0;
4469 /* this entire expression will be evaluated at compile time */
4470 if (sizeof *msg.msg_iov == sizeof *vectors &&
4471 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4472 G_STRUCT_OFFSET (struct iovec, iov_base) ==
4473 G_STRUCT_OFFSET (GInputVector, buffer) &&
4474 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4475 G_STRUCT_OFFSET (struct iovec, iov_len) ==
4476 G_STRUCT_OFFSET (GInputVector, size))
4477 /* ABI is compatible */
4479 msg.msg_iov = (struct iovec *) vectors;
4480 msg.msg_iovlen = num_vectors;
4483 /* ABI is incompatible */
4487 msg.msg_iov = g_newa (struct iovec, num_vectors);
4488 for (i = 0; i < num_vectors; i++)
4490 msg.msg_iov[i].iov_base = vectors[i].buffer;
4491 msg.msg_iov[i].iov_len = vectors[i].size;
4493 msg.msg_iovlen = num_vectors;
4497 msg.msg_control = g_alloca (2048);
4498 msg.msg_controllen = 2048;
4502 msg.msg_flags = *flags;
4506 /* We always set the close-on-exec flag so we don't leak file
4507 * descriptors into child processes. Note that gunixfdmessage.c
4508 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4510 #ifdef MSG_CMSG_CLOEXEC
4511 msg.msg_flags |= MSG_CMSG_CLOEXEC;
4517 if (socket->priv->blocking &&
4518 !g_socket_condition_wait (socket,
4519 G_IO_IN, cancellable, error))
4522 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4523 #ifdef MSG_CMSG_CLOEXEC
4524 if (result < 0 && get_socket_errno () == EINVAL)
4526 /* We must be running on an old kernel. Call without the flag. */
4527 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4528 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4534 int errsv = get_socket_errno ();
4539 if (socket->priv->blocking &&
4540 (errsv == EWOULDBLOCK ||
4544 g_set_error (error, G_IO_ERROR,
4545 socket_io_error_from_errno (errsv),
4546 _("Error receiving message: %s"), socket_strerror (errsv));
4553 /* decode address */
4554 if (address != NULL)
4556 *address = cache_recv_address (socket, msg.msg_name, msg.msg_namelen);
4559 /* decode control messages */
4561 GPtrArray *my_messages = NULL;
4562 struct cmsghdr *cmsg;
4564 if (msg.msg_controllen >= sizeof (struct cmsghdr))
4566 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4568 GSocketControlMessage *message;
4570 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4572 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4574 if (message == NULL)
4575 /* We've already spewed about the problem in the
4576 deserialization code, so just continue */
4579 if (messages == NULL)
4581 /* we have to do it this way if the user ignores the
4582 * messages so that we will close any received fds.
4584 g_object_unref (message);
4588 if (my_messages == NULL)
4589 my_messages = g_ptr_array_new ();
4590 g_ptr_array_add (my_messages, message);
4596 *num_messages = my_messages != NULL ? my_messages->len : 0;
4600 if (my_messages == NULL)
4606 g_ptr_array_add (my_messages, NULL);
4607 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4612 g_assert (my_messages == NULL);
4616 /* capture the flags */
4618 *flags = msg.msg_flags;
4624 struct sockaddr_storage addr;
4626 DWORD bytes_received;
4633 bufs = g_newa (WSABUF, num_vectors);
4634 for (i = 0; i < num_vectors; i++)
4636 bufs[i].buf = (char *)vectors[i].buffer;
4637 bufs[i].len = (gulong)vectors[i].size;
4649 addrlen = sizeof addr;
4651 result = WSARecvFrom (socket->priv->fd,
4653 &bytes_received, &win_flags,
4654 (struct sockaddr *)&addr, &addrlen,
4657 result = WSARecv (socket->priv->fd,
4659 &bytes_received, &win_flags,
4663 int errsv = get_socket_errno ();
4665 if (errsv == WSAEINTR)
4668 if (errsv == WSAEWOULDBLOCK)
4670 win32_unset_event_mask (socket, FD_READ);
4672 if (socket->priv->blocking)
4674 if (!g_socket_condition_wait (socket,
4675 G_IO_IN, cancellable, error))
4682 g_set_error (error, G_IO_ERROR,
4683 socket_io_error_from_errno (errsv),
4684 _("Error receiving message: %s"), socket_strerror (errsv));
4688 win32_unset_event_mask (socket, FD_READ);
4692 /* decode address */
4693 if (address != NULL)
4695 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
4698 /* capture the flags */
4702 if (messages != NULL)
4704 if (num_messages != NULL)
4707 return bytes_received;
4713 * g_socket_get_credentials:
4714 * @socket: a #GSocket.
4715 * @error: #GError for error reporting, or %NULL to ignore.
4717 * Returns the credentials of the foreign process connected to this
4718 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4721 * If this operation isn't supported on the OS, the method fails with
4722 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4723 * by reading the %SO_PEERCRED option on the underlying socket.
4725 * Other ways to obtain credentials from a foreign peer includes the
4726 * #GUnixCredentialsMessage type and
4727 * g_unix_connection_send_credentials() /
4728 * g_unix_connection_receive_credentials() functions.
4730 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4731 * that must be freed with g_object_unref().
4736 g_socket_get_credentials (GSocket *socket,
4741 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4742 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4746 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
4750 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
4751 socklen_t optlen = sizeof (native_creds_buf);
4753 if (getsockopt (socket->priv->fd,
4759 ret = g_credentials_new ();
4760 g_credentials_set_native (ret,
4761 G_CREDENTIALS_NATIVE_TYPE,
4765 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
4767 struct unpcbid cred;
4768 socklen_t optlen = sizeof (cred);
4770 if (getsockopt (socket->priv->fd,
4776 ret = g_credentials_new ();
4777 g_credentials_set_native (ret,
4778 G_CREDENTIALS_NATIVE_TYPE,
4782 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
4784 ucred_t *ucred = NULL;
4786 if (getpeerucred (socket->priv->fd, &ucred) == 0)
4788 ret = g_credentials_new ();
4789 g_credentials_set_native (ret,
4790 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
4796 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
4801 int errsv = get_socket_errno ();
4805 socket_io_error_from_errno (errsv),
4806 _("Unable to read socket credentials: %s"),
4807 socket_strerror (errsv));
4812 g_set_error_literal (error,
4814 G_IO_ERROR_NOT_SUPPORTED,
4815 _("g_socket_get_credentials not implemented for this OS"));
4822 * g_socket_get_option:
4823 * @socket: a #GSocket
4824 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
4825 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
4826 * @value: (out): return location for the option value
4827 * @error: #GError for error reporting, or %NULL to ignore.
4829 * Gets the value of an integer-valued option on @socket, as with
4830 * getsockopt(). (If you need to fetch a non-integer-valued option,
4831 * you will need to call getsockopt() directly.)
4833 * The [<gio/gnetworking.h>][gio-gnetworking.h]
4834 * header pulls in system headers that will define most of the
4835 * standard/portable socket options. For unusual socket protocols or
4836 * platform-dependent options, you may need to include additional
4839 * Note that even for socket options that are a single byte in size,
4840 * @value is still a pointer to a #gint variable, not a #guchar;
4841 * g_socket_get_option() will handle the conversion internally.
4843 * Returns: success or failure. On failure, @error will be set, and
4844 * the system error value (`errno` or WSAGetLastError()) will still
4845 * be set to the result of the getsockopt() call.
4850 g_socket_get_option (GSocket *socket,
4858 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4861 size = sizeof (gint);
4862 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
4864 int errsv = get_socket_errno ();
4866 g_set_error_literal (error,
4868 socket_io_error_from_errno (errsv),
4869 socket_strerror (errsv));
4871 /* Reset errno in case the caller wants to look at it */
4877 #if G_BYTE_ORDER == G_BIG_ENDIAN
4878 /* If the returned value is smaller than an int then we need to
4879 * slide it over into the low-order bytes of *value.
4881 if (size != sizeof (gint))
4882 *value = *value >> (8 * (sizeof (gint) - size));
4889 * g_socket_set_option:
4890 * @socket: a #GSocket
4891 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
4892 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
4893 * @value: the value to set the option to
4894 * @error: #GError for error reporting, or %NULL to ignore.
4896 * Sets the value of an integer-valued option on @socket, as with
4897 * setsockopt(). (If you need to set a non-integer-valued option,
4898 * you will need to call setsockopt() directly.)
4900 * The [<gio/gnetworking.h>][gio-gnetworking.h]
4901 * header pulls in system headers that will define most of the
4902 * standard/portable socket options. For unusual socket protocols or
4903 * platform-dependent options, you may need to include additional
4906 * Returns: success or failure. On failure, @error will be set, and
4907 * the system error value (`errno` or WSAGetLastError()) will still
4908 * be set to the result of the setsockopt() call.
4913 g_socket_set_option (GSocket *socket,
4921 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4923 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
4926 #if !defined (__linux__) && !defined (G_OS_WIN32)
4927 /* Linux and Windows let you set a single-byte value from an int,
4928 * but most other platforms don't.
4930 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
4932 #if G_BYTE_ORDER == G_BIG_ENDIAN
4933 value = value << (8 * (sizeof (gint) - 1));
4935 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
4940 errsv = get_socket_errno ();
4942 g_set_error_literal (error,
4944 socket_io_error_from_errno (errsv),
4945 socket_strerror (errsv));