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 * On success, the returned #GSocket takes ownership of @fd. On failure, the
1061 * caller must close @fd themselves.
1063 * Returns: a #GSocket or %NULL on error.
1064 * Free the returned object with g_object_unref().
1069 g_socket_new_from_fd (gint fd,
1072 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1079 * g_socket_set_blocking:
1080 * @socket: a #GSocket.
1081 * @blocking: Whether to use blocking I/O or not.
1083 * Sets the blocking mode of the socket. In blocking mode
1084 * all operations block until they succeed or there is an error. In
1085 * non-blocking mode all functions return results immediately or
1086 * with a %G_IO_ERROR_WOULD_BLOCK error.
1088 * All sockets are created in blocking mode. However, note that the
1089 * platform level socket is always non-blocking, and blocking mode
1090 * is a GSocket level feature.
1095 g_socket_set_blocking (GSocket *socket,
1098 g_return_if_fail (G_IS_SOCKET (socket));
1100 blocking = !!blocking;
1102 if (socket->priv->blocking == blocking)
1105 socket->priv->blocking = blocking;
1106 g_object_notify (G_OBJECT (socket), "blocking");
1110 * g_socket_get_blocking:
1111 * @socket: a #GSocket.
1113 * Gets the blocking mode of the socket. For details on blocking I/O,
1114 * see g_socket_set_blocking().
1116 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1121 g_socket_get_blocking (GSocket *socket)
1123 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1125 return socket->priv->blocking;
1129 * g_socket_set_keepalive:
1130 * @socket: a #GSocket.
1131 * @keepalive: Value for the keepalive flag
1133 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1134 * this flag is set on a socket, the system will attempt to verify that the
1135 * remote socket endpoint is still present if a sufficiently long period of
1136 * time passes with no data being exchanged. If the system is unable to
1137 * verify the presence of the remote endpoint, it will automatically close
1140 * This option is only functional on certain kinds of sockets. (Notably,
1141 * %G_SOCKET_PROTOCOL_TCP sockets.)
1143 * The exact time between pings is system- and protocol-dependent, but will
1144 * normally be at least two hours. Most commonly, you would set this flag
1145 * on a server socket if you want to allow clients to remain idle for long
1146 * periods of time, but also want to ensure that connections are eventually
1147 * garbage-collected if clients crash or become unreachable.
1152 g_socket_set_keepalive (GSocket *socket,
1155 GError *error = NULL;
1157 g_return_if_fail (G_IS_SOCKET (socket));
1159 keepalive = !!keepalive;
1160 if (socket->priv->keepalive == keepalive)
1163 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1166 g_warning ("error setting keepalive: %s", error->message);
1167 g_error_free (error);
1171 socket->priv->keepalive = keepalive;
1172 g_object_notify (G_OBJECT (socket), "keepalive");
1176 * g_socket_get_keepalive:
1177 * @socket: a #GSocket.
1179 * Gets the keepalive mode of the socket. For details on this,
1180 * see g_socket_set_keepalive().
1182 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1187 g_socket_get_keepalive (GSocket *socket)
1189 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1191 return socket->priv->keepalive;
1195 * g_socket_get_listen_backlog:
1196 * @socket: a #GSocket.
1198 * Gets the listen backlog setting of the socket. For details on this,
1199 * see g_socket_set_listen_backlog().
1201 * Returns: the maximum number of pending connections.
1206 g_socket_get_listen_backlog (GSocket *socket)
1208 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1210 return socket->priv->listen_backlog;
1214 * g_socket_set_listen_backlog:
1215 * @socket: a #GSocket.
1216 * @backlog: the maximum number of pending connections.
1218 * Sets the maximum number of outstanding connections allowed
1219 * when listening on this socket. If more clients than this are
1220 * connecting to the socket and the application is not handling them
1221 * on time then the new connections will be refused.
1223 * Note that this must be called before g_socket_listen() and has no
1224 * effect if called after that.
1229 g_socket_set_listen_backlog (GSocket *socket,
1232 g_return_if_fail (G_IS_SOCKET (socket));
1233 g_return_if_fail (!socket->priv->listening);
1235 if (backlog != socket->priv->listen_backlog)
1237 socket->priv->listen_backlog = backlog;
1238 g_object_notify (G_OBJECT (socket), "listen-backlog");
1243 * g_socket_get_timeout:
1244 * @socket: a #GSocket.
1246 * Gets the timeout setting of the socket. For details on this, see
1247 * g_socket_set_timeout().
1249 * Returns: the timeout in seconds
1254 g_socket_get_timeout (GSocket *socket)
1256 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1258 return socket->priv->timeout;
1262 * g_socket_set_timeout:
1263 * @socket: a #GSocket.
1264 * @timeout: the timeout for @socket, in seconds, or 0 for none
1266 * Sets the time in seconds after which I/O operations on @socket will
1267 * time out if they have not yet completed.
1269 * On a blocking socket, this means that any blocking #GSocket
1270 * operation will time out after @timeout seconds of inactivity,
1271 * returning %G_IO_ERROR_TIMED_OUT.
1273 * On a non-blocking socket, calls to g_socket_condition_wait() will
1274 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1275 * created with g_socket_create_source() will trigger after
1276 * @timeout seconds of inactivity, with the requested condition
1277 * set, at which point calling g_socket_receive(), g_socket_send(),
1278 * g_socket_check_connect_result(), etc, will fail with
1279 * %G_IO_ERROR_TIMED_OUT.
1281 * If @timeout is 0 (the default), operations will never time out
1284 * Note that if an I/O operation is interrupted by a signal, this may
1285 * cause the timeout to be reset.
1290 g_socket_set_timeout (GSocket *socket,
1293 g_return_if_fail (G_IS_SOCKET (socket));
1295 if (timeout != socket->priv->timeout)
1297 socket->priv->timeout = timeout;
1298 g_object_notify (G_OBJECT (socket), "timeout");
1304 * @socket: a #GSocket.
1306 * Gets the unicast time-to-live setting on @socket; see
1307 * g_socket_set_ttl() for more details.
1309 * Returns: the time-to-live setting on @socket
1314 g_socket_get_ttl (GSocket *socket)
1316 GError *error = NULL;
1319 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1321 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1323 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1326 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1328 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1332 g_return_val_if_reached (0);
1336 g_warning ("error getting unicast ttl: %s", error->message);
1337 g_error_free (error);
1346 * @socket: a #GSocket.
1347 * @ttl: the time-to-live value for all unicast packets on @socket
1349 * Sets the time-to-live for outgoing unicast packets on @socket.
1350 * By default the platform-specific default value is used.
1355 g_socket_set_ttl (GSocket *socket,
1358 GError *error = NULL;
1360 g_return_if_fail (G_IS_SOCKET (socket));
1362 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1364 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1367 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1369 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1371 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1375 g_return_if_reached ();
1379 g_warning ("error setting unicast ttl: %s", error->message);
1380 g_error_free (error);
1384 g_object_notify (G_OBJECT (socket), "ttl");
1388 * g_socket_get_broadcast:
1389 * @socket: a #GSocket.
1391 * Gets the broadcast setting on @socket; if %TRUE,
1392 * it is possible to send packets to broadcast
1395 * Returns: the broadcast setting on @socket
1400 g_socket_get_broadcast (GSocket *socket)
1402 GError *error = NULL;
1405 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1407 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1410 g_warning ("error getting broadcast: %s", error->message);
1411 g_error_free (error);
1419 * g_socket_set_broadcast:
1420 * @socket: a #GSocket.
1421 * @broadcast: whether @socket should allow sending to broadcast
1424 * Sets whether @socket should allow sending to broadcast addresses.
1425 * This is %FALSE by default.
1430 g_socket_set_broadcast (GSocket *socket,
1433 GError *error = NULL;
1435 g_return_if_fail (G_IS_SOCKET (socket));
1437 broadcast = !!broadcast;
1439 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1442 g_warning ("error setting broadcast: %s", error->message);
1443 g_error_free (error);
1447 g_object_notify (G_OBJECT (socket), "broadcast");
1451 * g_socket_get_multicast_loopback:
1452 * @socket: a #GSocket.
1454 * Gets the multicast loopback setting on @socket; if %TRUE (the
1455 * default), outgoing multicast packets will be looped back to
1456 * multicast listeners on the same host.
1458 * Returns: the multicast loopback setting on @socket
1463 g_socket_get_multicast_loopback (GSocket *socket)
1465 GError *error = NULL;
1468 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1470 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1472 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1475 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1477 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1481 g_return_val_if_reached (FALSE);
1485 g_warning ("error getting multicast loopback: %s", error->message);
1486 g_error_free (error);
1494 * g_socket_set_multicast_loopback:
1495 * @socket: a #GSocket.
1496 * @loopback: whether @socket should receive messages sent to its
1497 * multicast groups from the local host
1499 * Sets whether outgoing multicast packets will be received by sockets
1500 * listening on that multicast address on the same host. This is %TRUE
1506 g_socket_set_multicast_loopback (GSocket *socket,
1509 GError *error = NULL;
1511 g_return_if_fail (G_IS_SOCKET (socket));
1513 loopback = !!loopback;
1515 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1517 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1520 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1522 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1524 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1528 g_return_if_reached ();
1532 g_warning ("error setting multicast loopback: %s", error->message);
1533 g_error_free (error);
1537 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1541 * g_socket_get_multicast_ttl:
1542 * @socket: a #GSocket.
1544 * Gets the multicast time-to-live setting on @socket; see
1545 * g_socket_set_multicast_ttl() for more details.
1547 * Returns: the multicast time-to-live setting on @socket
1552 g_socket_get_multicast_ttl (GSocket *socket)
1554 GError *error = NULL;
1557 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1559 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1561 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1564 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1566 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1570 g_return_val_if_reached (FALSE);
1574 g_warning ("error getting multicast ttl: %s", error->message);
1575 g_error_free (error);
1583 * g_socket_set_multicast_ttl:
1584 * @socket: a #GSocket.
1585 * @ttl: the time-to-live value for all multicast datagrams on @socket
1587 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1588 * By default, this is 1, meaning that multicast packets will not leave
1589 * the local network.
1594 g_socket_set_multicast_ttl (GSocket *socket,
1597 GError *error = NULL;
1599 g_return_if_fail (G_IS_SOCKET (socket));
1601 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1603 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1606 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1608 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1610 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1614 g_return_if_reached ();
1618 g_warning ("error setting multicast ttl: %s", error->message);
1619 g_error_free (error);
1623 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1627 * g_socket_get_family:
1628 * @socket: a #GSocket.
1630 * Gets the socket family of the socket.
1632 * Returns: a #GSocketFamily
1637 g_socket_get_family (GSocket *socket)
1639 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1641 return socket->priv->family;
1645 * g_socket_get_socket_type:
1646 * @socket: a #GSocket.
1648 * Gets the socket type of the socket.
1650 * Returns: a #GSocketType
1655 g_socket_get_socket_type (GSocket *socket)
1657 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1659 return socket->priv->type;
1663 * g_socket_get_protocol:
1664 * @socket: a #GSocket.
1666 * Gets the socket protocol id the socket was created with.
1667 * In case the protocol is unknown, -1 is returned.
1669 * Returns: a protocol id, or -1 if unknown
1674 g_socket_get_protocol (GSocket *socket)
1676 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1678 return socket->priv->protocol;
1683 * @socket: a #GSocket.
1685 * Returns the underlying OS socket object. On unix this
1686 * is a socket file descriptor, and on Windows this is
1687 * a Winsock2 SOCKET handle. This may be useful for
1688 * doing platform specific or otherwise unusual operations
1691 * Returns: the file descriptor of the socket.
1696 g_socket_get_fd (GSocket *socket)
1698 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1700 return socket->priv->fd;
1704 * g_socket_get_local_address:
1705 * @socket: a #GSocket.
1706 * @error: #GError for error reporting, or %NULL to ignore.
1708 * Try to get the local address of a bound socket. This is only
1709 * useful if the socket has been bound to a local address,
1710 * either explicitly or implicitly when connecting.
1712 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1713 * Free the returned object with g_object_unref().
1718 g_socket_get_local_address (GSocket *socket,
1721 struct sockaddr_storage buffer;
1722 guint len = sizeof (buffer);
1724 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1726 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1728 int errsv = get_socket_errno ();
1729 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1730 _("could not get local address: %s"), socket_strerror (errsv));
1734 return g_socket_address_new_from_native (&buffer, len);
1738 * g_socket_get_remote_address:
1739 * @socket: a #GSocket.
1740 * @error: #GError for error reporting, or %NULL to ignore.
1742 * Try to get the remove address of a connected socket. This is only
1743 * useful for connection oriented sockets that have been connected.
1745 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1746 * Free the returned object with g_object_unref().
1751 g_socket_get_remote_address (GSocket *socket,
1754 struct sockaddr_storage buffer;
1755 guint len = sizeof (buffer);
1757 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1759 if (socket->priv->connect_pending)
1761 if (!g_socket_check_connect_result (socket, error))
1764 socket->priv->connect_pending = FALSE;
1767 if (!socket->priv->remote_address)
1769 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1771 int errsv = get_socket_errno ();
1772 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1773 _("could not get remote address: %s"), socket_strerror (errsv));
1777 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1780 return g_object_ref (socket->priv->remote_address);
1784 * g_socket_is_connected:
1785 * @socket: a #GSocket.
1787 * Check whether the socket is connected. This is only useful for
1788 * connection-oriented sockets.
1790 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1795 g_socket_is_connected (GSocket *socket)
1797 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1799 return socket->priv->connected;
1804 * @socket: a #GSocket.
1805 * @error: #GError for error reporting, or %NULL to ignore.
1807 * Marks the socket as a server socket, i.e. a socket that is used
1808 * to accept incoming requests using g_socket_accept().
1810 * Before calling this the socket must be bound to a local address using
1813 * To set the maximum amount of outstanding clients, use
1814 * g_socket_set_listen_backlog().
1816 * Returns: %TRUE on success, %FALSE on error.
1821 g_socket_listen (GSocket *socket,
1824 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1826 if (!check_socket (socket, error))
1829 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1831 int errsv = get_socket_errno ();
1833 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1834 _("could not listen: %s"), socket_strerror (errsv));
1838 socket->priv->listening = TRUE;
1845 * @socket: a #GSocket.
1846 * @address: a #GSocketAddress specifying the local address.
1847 * @allow_reuse: whether to allow reusing this address
1848 * @error: #GError for error reporting, or %NULL to ignore.
1850 * When a socket is created it is attached to an address family, but it
1851 * doesn't have an address in this family. g_socket_bind() assigns the
1852 * address (sometimes called name) of the socket.
1854 * It is generally required to bind to a local address before you can
1855 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1856 * In certain situations, you may also want to bind a socket that will be
1857 * used to initiate connections, though this is not normally required.
1859 * If @socket is a TCP socket, then @allow_reuse controls the setting
1860 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
1861 * server sockets (sockets that you will eventually call
1862 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
1863 * set this flag on a server socket may cause g_socket_bind() to return
1864 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
1865 * immediately restarted.)
1867 * If @socket is a UDP socket, then @allow_reuse determines whether or
1868 * not other UDP sockets can be bound to the same address at the same
1869 * time. In particular, you can have several UDP sockets bound to the
1870 * same address, and they will all receive all of the multicast and
1871 * broadcast packets sent to that address. (The behavior of unicast
1872 * UDP packets to an address with multiple listeners is not defined.)
1874 * Returns: %TRUE on success, %FALSE on error.
1879 g_socket_bind (GSocket *socket,
1880 GSocketAddress *address,
1881 gboolean reuse_address,
1884 struct sockaddr_storage addr;
1885 gboolean so_reuseaddr;
1887 gboolean so_reuseport;
1890 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1892 if (!check_socket (socket, error))
1895 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1898 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
1899 * sockets, but has nasty side effects we don't want for TCP
1902 * On other platforms, we set SO_REUSEPORT, if it exists, for
1903 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
1904 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
1905 * the desired semantics on UDP (as it does on Linux, although
1906 * Linux has SO_REUSEPORT too as of 3.9).
1910 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1912 so_reuseaddr = !!reuse_address;
1916 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1919 /* Ignore errors here, the only likely error is "not supported", and
1920 * this is a "best effort" thing mainly.
1922 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
1924 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
1927 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1928 g_socket_address_get_native_size (address)) < 0)
1930 int errsv = get_socket_errno ();
1932 G_IO_ERROR, socket_io_error_from_errno (errsv),
1933 _("Error binding to address: %s"), socket_strerror (errsv));
1940 #if !defined(HAVE_IF_NAMETOINDEX) && defined(G_OS_WIN32)
1942 if_nametoindex (const gchar *iface)
1944 PIP_ADAPTER_ADDRESSES addresses = NULL, p;
1945 gulong addresses_len = 0;
1949 if (ws2funcs.pIfNameToIndex != NULL)
1950 return ws2funcs.pIfNameToIndex (iface);
1952 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, NULL, &addresses_len);
1953 if (res != NO_ERROR && res != ERROR_BUFFER_OVERFLOW)
1955 if (res == ERROR_NO_DATA)
1962 addresses = g_malloc (addresses_len);
1963 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, addresses, &addresses_len);
1965 if (res != NO_ERROR)
1968 if (res == ERROR_NO_DATA)
1978 if (strcmp (p->AdapterName, iface) == 0)
1994 #define HAVE_IF_NAMETOINDEX 1
1998 g_socket_multicast_group_operation (GSocket *socket,
1999 GInetAddress *group,
2000 gboolean source_specific,
2002 gboolean join_group,
2005 const guint8 *native_addr;
2006 gint optname, result;
2008 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2009 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2010 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2012 if (!check_socket (socket, error))
2015 native_addr = g_inet_address_to_bytes (group);
2016 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2018 #ifdef HAVE_IP_MREQN
2019 struct ip_mreqn mc_req;
2021 struct ip_mreq mc_req;
2024 memset (&mc_req, 0, sizeof (mc_req));
2025 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2027 #ifdef HAVE_IP_MREQN
2029 mc_req.imr_ifindex = if_nametoindex (iface);
2031 mc_req.imr_ifindex = 0; /* Pick any. */
2032 #elif defined(G_OS_WIN32)
2034 mc_req.imr_interface.s_addr = g_htonl (if_nametoindex (iface));
2036 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2038 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2041 if (source_specific)
2043 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2044 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2046 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2048 _("Error joining multicast group: %s") :
2049 _("Error leaving multicast group: %s"),
2050 _("No support for source-specific multicast"));
2055 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2056 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2057 &mc_req, sizeof (mc_req));
2059 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2061 struct ipv6_mreq mc_req_ipv6;
2063 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2064 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2065 #ifdef HAVE_IF_NAMETOINDEX
2067 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2070 mc_req_ipv6.ipv6mr_interface = 0;
2072 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2073 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2074 &mc_req_ipv6, sizeof (mc_req_ipv6));
2077 g_return_val_if_reached (FALSE);
2081 int errsv = get_socket_errno ();
2083 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2085 _("Error joining multicast group: %s") :
2086 _("Error leaving multicast group: %s"),
2087 socket_strerror (errsv));
2095 * g_socket_join_multicast_group:
2096 * @socket: a #GSocket.
2097 * @group: a #GInetAddress specifying the group address to join.
2098 * @iface: (allow-none): Name of the interface to use, or %NULL
2099 * @source_specific: %TRUE if source-specific multicast should be used
2100 * @error: #GError for error reporting, or %NULL to ignore.
2102 * Registers @socket to receive multicast messages sent to @group.
2103 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2104 * been bound to an appropriate interface and port with
2107 * If @iface is %NULL, the system will automatically pick an interface
2108 * to bind to based on @group.
2110 * If @source_specific is %TRUE, source-specific multicast as defined
2111 * in RFC 4604 is used. Note that on older platforms this may fail
2112 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2114 * Returns: %TRUE on success, %FALSE on error.
2119 g_socket_join_multicast_group (GSocket *socket,
2120 GInetAddress *group,
2121 gboolean source_specific,
2125 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2129 * g_socket_leave_multicast_group:
2130 * @socket: a #GSocket.
2131 * @group: a #GInetAddress specifying the group address to leave.
2132 * @iface: (allow-none): Interface used
2133 * @source_specific: %TRUE if source-specific multicast was used
2134 * @error: #GError for error reporting, or %NULL to ignore.
2136 * Removes @socket from the multicast group defined by @group, @iface,
2137 * and @source_specific (which must all have the same values they had
2138 * when you joined the group).
2140 * @socket remains bound to its address and port, and can still receive
2141 * unicast messages after calling this.
2143 * Returns: %TRUE on success, %FALSE on error.
2148 g_socket_leave_multicast_group (GSocket *socket,
2149 GInetAddress *group,
2150 gboolean source_specific,
2154 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2158 * g_socket_speaks_ipv4:
2159 * @socket: a #GSocket
2161 * Checks if a socket is capable of speaking IPv4.
2163 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2164 * and under some combinations of circumstances IPv6 sockets are also
2165 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2168 * No other types of sockets are currently considered as being capable
2171 * Returns: %TRUE if this socket can be used with IPv4.
2176 g_socket_speaks_ipv4 (GSocket *socket)
2178 switch (socket->priv->family)
2180 case G_SOCKET_FAMILY_IPV4:
2183 case G_SOCKET_FAMILY_IPV6:
2184 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2188 if (!g_socket_get_option (socket,
2189 IPPROTO_IPV6, IPV6_V6ONLY,
2206 * @socket: a #GSocket.
2207 * @cancellable: (allow-none): a %GCancellable or %NULL
2208 * @error: #GError for error reporting, or %NULL to ignore.
2210 * Accept incoming connections on a connection-based socket. This removes
2211 * the first outstanding connection request from the listening socket and
2212 * creates a #GSocket object for it.
2214 * The @socket must be bound to a local address with g_socket_bind() and
2215 * must be listening for incoming connections (g_socket_listen()).
2217 * If there are no outstanding connections then the operation will block
2218 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2219 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2221 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2222 * Free the returned object with g_object_unref().
2227 g_socket_accept (GSocket *socket,
2228 GCancellable *cancellable,
2231 GSocket *new_socket;
2234 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2236 if (!check_socket (socket, error))
2239 if (!check_timeout (socket, error))
2244 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2246 int errsv = get_socket_errno ();
2251 #ifdef WSAEWOULDBLOCK
2252 if (errsv == WSAEWOULDBLOCK)
2254 if (errsv == EWOULDBLOCK ||
2258 win32_unset_event_mask (socket, FD_ACCEPT);
2260 if (socket->priv->blocking)
2262 if (!g_socket_condition_wait (socket,
2263 G_IO_IN, cancellable, error))
2270 g_set_error (error, G_IO_ERROR,
2271 socket_io_error_from_errno (errsv),
2272 _("Error accepting connection: %s"), socket_strerror (errsv));
2278 win32_unset_event_mask (socket, FD_ACCEPT);
2282 /* The socket inherits the accepting sockets event mask and even object,
2283 we need to remove that */
2284 WSAEventSelect (ret, NULL, 0);
2290 /* We always want to set close-on-exec to protect users. If you
2291 need to so some weird inheritance to exec you can re-enable this
2292 using lower level hacks with g_socket_get_fd(). */
2293 flags = fcntl (ret, F_GETFD, 0);
2295 (flags & FD_CLOEXEC) == 0)
2297 flags |= FD_CLOEXEC;
2298 fcntl (ret, F_SETFD, flags);
2303 new_socket = g_socket_new_from_fd (ret, error);
2304 if (new_socket == NULL)
2313 new_socket->priv->protocol = socket->priv->protocol;
2320 * @socket: a #GSocket.
2321 * @address: a #GSocketAddress specifying the remote address.
2322 * @cancellable: (allow-none): a %GCancellable or %NULL
2323 * @error: #GError for error reporting, or %NULL to ignore.
2325 * Connect the socket to the specified remote address.
2327 * For connection oriented socket this generally means we attempt to make
2328 * a connection to the @address. For a connection-less socket it sets
2329 * the default address for g_socket_send() and discards all incoming datagrams
2330 * from other sources.
2332 * Generally connection oriented sockets can only connect once, but
2333 * connection-less sockets can connect multiple times to change the
2336 * If the connect call needs to do network I/O it will block, unless
2337 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2338 * and the user can be notified of the connection finishing by waiting
2339 * for the G_IO_OUT condition. The result of the connection must then be
2340 * checked with g_socket_check_connect_result().
2342 * Returns: %TRUE if connected, %FALSE on error.
2347 g_socket_connect (GSocket *socket,
2348 GSocketAddress *address,
2349 GCancellable *cancellable,
2352 struct sockaddr_storage buffer;
2354 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2356 if (!check_socket (socket, error))
2359 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2362 if (socket->priv->remote_address)
2363 g_object_unref (socket->priv->remote_address);
2364 socket->priv->remote_address = g_object_ref (address);
2368 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2369 g_socket_address_get_native_size (address)) < 0)
2371 int errsv = get_socket_errno ();
2377 if (errsv == EINPROGRESS)
2379 if (errsv == WSAEWOULDBLOCK)
2382 win32_unset_event_mask (socket, FD_CONNECT);
2384 if (socket->priv->blocking)
2386 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2388 if (g_socket_check_connect_result (socket, error))
2394 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2395 _("Connection in progress"));
2396 socket->priv->connect_pending = TRUE;
2400 g_set_error_literal (error, G_IO_ERROR,
2401 socket_io_error_from_errno (errsv),
2402 socket_strerror (errsv));
2409 win32_unset_event_mask (socket, FD_CONNECT);
2411 socket->priv->connected = TRUE;
2417 * g_socket_check_connect_result:
2418 * @socket: a #GSocket
2419 * @error: #GError for error reporting, or %NULL to ignore.
2421 * Checks and resets the pending connect error for the socket.
2422 * This is used to check for errors when g_socket_connect() is
2423 * used in non-blocking mode.
2425 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2430 g_socket_check_connect_result (GSocket *socket,
2435 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2437 if (!check_socket (socket, error))
2440 if (!check_timeout (socket, error))
2443 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
2445 g_prefix_error (error, _("Unable to get pending error: "));
2451 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2452 socket_strerror (value));
2453 if (socket->priv->remote_address)
2455 g_object_unref (socket->priv->remote_address);
2456 socket->priv->remote_address = NULL;
2461 socket->priv->connected = TRUE;
2466 * g_socket_get_available_bytes:
2467 * @socket: a #GSocket
2469 * Get the amount of data pending in the OS input buffer.
2471 * If @socket is a UDP or SCTP socket, this will return the size of
2472 * just the next packet, even if additional packets are buffered after
2475 * Note that on Windows, this function is rather inefficient in the
2476 * UDP case, and so if you know any plausible upper bound on the size
2477 * of the incoming packet, it is better to just do a
2478 * g_socket_receive() with a buffer of that size, rather than calling
2479 * g_socket_get_available_bytes() first and then doing a receive of
2480 * exactly the right size.
2482 * Returns: the number of bytes that can be read from the socket
2483 * without blocking or truncating, or -1 on error.
2488 g_socket_get_available_bytes (GSocket *socket)
2491 const gint bufsize = 64 * 1024;
2492 static guchar *buf = NULL;
2498 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2500 #if defined (SO_NREAD)
2501 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
2503 #elif !defined (G_OS_WIN32)
2504 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2507 if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
2509 if (G_UNLIKELY (g_once_init_enter (&buf)))
2510 g_once_init_leave (&buf, g_malloc (bufsize));
2512 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
2513 if (avail == -1 && get_socket_errno () == WSAEWOULDBLOCK)
2518 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
2528 * @socket: a #GSocket
2529 * @buffer: (array length=size) (element-type guint8): a buffer to
2530 * read data into (which should be at least @size bytes long).
2531 * @size: the number of bytes you want to read from the socket
2532 * @cancellable: (allow-none): a %GCancellable or %NULL
2533 * @error: #GError for error reporting, or %NULL to ignore.
2535 * Receive data (up to @size bytes) from a socket. This is mainly used by
2536 * connection-oriented sockets; it is identical to g_socket_receive_from()
2537 * with @address set to %NULL.
2539 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2540 * g_socket_receive() will always read either 0 or 1 complete messages from
2541 * the socket. If the received message is too large to fit in @buffer, then
2542 * the data beyond @size bytes will be discarded, without any explicit
2543 * indication that this has occurred.
2545 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2546 * number of bytes, up to @size. If more than @size bytes have been
2547 * received, the additional data will be returned in future calls to
2548 * g_socket_receive().
2550 * If the socket is in blocking mode the call will block until there
2551 * is some data to receive, the connection is closed, or there is an
2552 * error. If there is no data available and the socket is in
2553 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2554 * returned. To be notified when data is available, wait for the
2555 * %G_IO_IN condition.
2557 * On error -1 is returned and @error is set accordingly.
2559 * Returns: Number of bytes read, or 0 if the connection was closed by
2560 * the peer, or -1 on error
2565 g_socket_receive (GSocket *socket,
2568 GCancellable *cancellable,
2571 return g_socket_receive_with_blocking (socket, buffer, size,
2572 socket->priv->blocking,
2573 cancellable, error);
2577 * g_socket_receive_with_blocking:
2578 * @socket: a #GSocket
2579 * @buffer: (array length=size) (element-type guint8): a buffer to
2580 * read data into (which should be at least @size bytes long).
2581 * @size: the number of bytes you want to read from the socket
2582 * @blocking: whether to do blocking or non-blocking I/O
2583 * @cancellable: (allow-none): a %GCancellable or %NULL
2584 * @error: #GError for error reporting, or %NULL to ignore.
2586 * This behaves exactly the same as g_socket_receive(), except that
2587 * the choice of blocking or non-blocking behavior is determined by
2588 * the @blocking argument rather than by @socket's properties.
2590 * Returns: Number of bytes read, or 0 if the connection was closed by
2591 * the peer, or -1 on error
2596 g_socket_receive_with_blocking (GSocket *socket,
2600 GCancellable *cancellable,
2605 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2607 if (!check_socket (socket, error))
2610 if (!check_timeout (socket, error))
2613 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2618 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2620 int errsv = get_socket_errno ();
2625 #ifdef WSAEWOULDBLOCK
2626 if (errsv == WSAEWOULDBLOCK)
2628 if (errsv == EWOULDBLOCK ||
2632 win32_unset_event_mask (socket, FD_READ);
2636 if (!g_socket_condition_wait (socket,
2637 G_IO_IN, cancellable, error))
2644 win32_unset_event_mask (socket, FD_READ);
2646 g_set_error (error, G_IO_ERROR,
2647 socket_io_error_from_errno (errsv),
2648 _("Error receiving data: %s"), socket_strerror (errsv));
2652 win32_unset_event_mask (socket, FD_READ);
2661 * g_socket_receive_from:
2662 * @socket: a #GSocket
2663 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2665 * @buffer: (array length=size) (element-type guint8): a buffer to
2666 * read data into (which should be at least @size bytes long).
2667 * @size: the number of bytes you want to read from the socket
2668 * @cancellable: (allow-none): a %GCancellable or %NULL
2669 * @error: #GError for error reporting, or %NULL to ignore.
2671 * Receive data (up to @size bytes) from a socket.
2673 * If @address is non-%NULL then @address will be set equal to the
2674 * source address of the received packet.
2675 * @address is owned by the caller.
2677 * See g_socket_receive() for additional information.
2679 * Returns: Number of bytes read, or 0 if the connection was closed by
2680 * the peer, or -1 on error
2685 g_socket_receive_from (GSocket *socket,
2686 GSocketAddress **address,
2689 GCancellable *cancellable,
2697 return g_socket_receive_message (socket,
2705 /* See the comment about SIGPIPE above. */
2707 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2709 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2714 * @socket: a #GSocket
2715 * @buffer: (array length=size) (element-type guint8): the buffer
2716 * containing the data to send.
2717 * @size: the number of bytes to send
2718 * @cancellable: (allow-none): a %GCancellable or %NULL
2719 * @error: #GError for error reporting, or %NULL to ignore.
2721 * Tries to send @size bytes from @buffer on the socket. This is
2722 * mainly used by connection-oriented sockets; it is identical to
2723 * g_socket_send_to() with @address set to %NULL.
2725 * If the socket is in blocking mode the call will block until there is
2726 * space for the data in the socket queue. If there is no space available
2727 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2728 * will be returned. To be notified when space is available, wait for the
2729 * %G_IO_OUT condition. Note though that you may still receive
2730 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2731 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2732 * very common due to the way the underlying APIs work.)
2734 * On error -1 is returned and @error is set accordingly.
2736 * Returns: Number of bytes written (which may be less than @size), or -1
2742 g_socket_send (GSocket *socket,
2743 const gchar *buffer,
2745 GCancellable *cancellable,
2748 return g_socket_send_with_blocking (socket, buffer, size,
2749 socket->priv->blocking,
2750 cancellable, error);
2754 * g_socket_send_with_blocking:
2755 * @socket: a #GSocket
2756 * @buffer: (array length=size) (element-type guint8): the buffer
2757 * containing the data to send.
2758 * @size: the number of bytes to send
2759 * @blocking: whether to do blocking or non-blocking I/O
2760 * @cancellable: (allow-none): a %GCancellable or %NULL
2761 * @error: #GError for error reporting, or %NULL to ignore.
2763 * This behaves exactly the same as g_socket_send(), except that
2764 * the choice of blocking or non-blocking behavior is determined by
2765 * the @blocking argument rather than by @socket's properties.
2767 * Returns: Number of bytes written (which may be less than @size), or -1
2773 g_socket_send_with_blocking (GSocket *socket,
2774 const gchar *buffer,
2777 GCancellable *cancellable,
2782 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2784 if (!check_socket (socket, error))
2787 if (!check_timeout (socket, error))
2790 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2795 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2797 int errsv = get_socket_errno ();
2802 #ifdef WSAEWOULDBLOCK
2803 if (errsv == WSAEWOULDBLOCK)
2805 if (errsv == EWOULDBLOCK ||
2809 win32_unset_event_mask (socket, FD_WRITE);
2813 if (!g_socket_condition_wait (socket,
2814 G_IO_OUT, cancellable, error))
2821 g_set_error (error, G_IO_ERROR,
2822 socket_io_error_from_errno (errsv),
2823 _("Error sending data: %s"), socket_strerror (errsv));
2834 * @socket: a #GSocket
2835 * @address: (allow-none): a #GSocketAddress, or %NULL
2836 * @buffer: (array length=size) (element-type guint8): the buffer
2837 * containing the data to send.
2838 * @size: the number of bytes to send
2839 * @cancellable: (allow-none): a %GCancellable or %NULL
2840 * @error: #GError for error reporting, or %NULL to ignore.
2842 * Tries to send @size bytes from @buffer to @address. If @address is
2843 * %NULL then the message is sent to the default receiver (set by
2844 * g_socket_connect()).
2846 * See g_socket_send() for additional information.
2848 * Returns: Number of bytes written (which may be less than @size), or -1
2854 g_socket_send_to (GSocket *socket,
2855 GSocketAddress *address,
2856 const gchar *buffer,
2858 GCancellable *cancellable,
2866 return g_socket_send_message (socket,
2876 * g_socket_shutdown:
2877 * @socket: a #GSocket
2878 * @shutdown_read: whether to shut down the read side
2879 * @shutdown_write: whether to shut down the write side
2880 * @error: #GError for error reporting, or %NULL to ignore.
2882 * Shut down part of a full-duplex connection.
2884 * If @shutdown_read is %TRUE then the receiving side of the connection
2885 * is shut down, and further reading is disallowed.
2887 * If @shutdown_write is %TRUE then the sending side of the connection
2888 * is shut down, and further writing is disallowed.
2890 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2892 * One example where this is used is graceful disconnect for TCP connections
2893 * where you close the sending side, then wait for the other side to close
2894 * the connection, thus ensuring that the other side saw all sent data.
2896 * Returns: %TRUE on success, %FALSE on error
2901 g_socket_shutdown (GSocket *socket,
2902 gboolean shutdown_read,
2903 gboolean shutdown_write,
2908 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2910 if (!check_socket (socket, error))
2914 if (!shutdown_read && !shutdown_write)
2918 if (shutdown_read && shutdown_write)
2920 else if (shutdown_read)
2925 if (shutdown_read && shutdown_write)
2927 else if (shutdown_read)
2933 if (shutdown (socket->priv->fd, how) != 0)
2935 int errsv = get_socket_errno ();
2936 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2937 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2941 if (shutdown_read && shutdown_write)
2942 socket->priv->connected = FALSE;
2949 * @socket: a #GSocket
2950 * @error: #GError for error reporting, or %NULL to ignore.
2952 * Closes the socket, shutting down any active connection.
2954 * Closing a socket does not wait for all outstanding I/O operations
2955 * to finish, so the caller should not rely on them to be guaranteed
2956 * to complete even if the close returns with no error.
2958 * Once the socket is closed, all other operations will return
2959 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2962 * Sockets will be automatically closed when the last reference
2963 * is dropped, but you might want to call this function to make sure
2964 * resources are released as early as possible.
2966 * Beware that due to the way that TCP works, it is possible for
2967 * recently-sent data to be lost if either you close a socket while the
2968 * %G_IO_IN condition is set, or else if the remote connection tries to
2969 * send something to you after you close the socket but before it has
2970 * finished reading all of the data you sent. There is no easy generic
2971 * way to avoid this problem; the easiest fix is to design the network
2972 * protocol such that the client will never send data "out of turn".
2973 * Another solution is for the server to half-close the connection by
2974 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2975 * and then wait for the client to notice this and close its side of the
2976 * connection, after which the server can safely call g_socket_close().
2977 * (This is what #GTcpConnection does if you call
2978 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2979 * only works if the client will close its connection after the server
2982 * Returns: %TRUE on success, %FALSE on error
2987 g_socket_close (GSocket *socket,
2992 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2994 if (socket->priv->closed)
2995 return TRUE; /* Multiple close not an error */
2997 if (!check_socket (socket, error))
3003 res = closesocket (socket->priv->fd);
3005 res = close (socket->priv->fd);
3009 int errsv = get_socket_errno ();
3014 g_set_error (error, G_IO_ERROR,
3015 socket_io_error_from_errno (errsv),
3016 _("Error closing socket: %s"),
3017 socket_strerror (errsv));
3023 socket->priv->connected = FALSE;
3024 socket->priv->closed = TRUE;
3025 if (socket->priv->remote_address)
3027 g_object_unref (socket->priv->remote_address);
3028 socket->priv->remote_address = NULL;
3035 * g_socket_is_closed:
3036 * @socket: a #GSocket
3038 * Checks whether a socket is closed.
3040 * Returns: %TRUE if socket is closed, %FALSE otherwise
3045 g_socket_is_closed (GSocket *socket)
3047 return socket->priv->closed;
3051 /* Broken source, used on errors */
3053 broken_dispatch (GSource *source,
3054 GSourceFunc callback,
3060 static GSourceFuncs broken_funcs =
3069 network_events_for_condition (GIOCondition condition)
3073 if (condition & G_IO_IN)
3074 event_mask |= (FD_READ | FD_ACCEPT);
3075 if (condition & G_IO_OUT)
3076 event_mask |= (FD_WRITE | FD_CONNECT);
3077 event_mask |= FD_CLOSE;
3083 ensure_event (GSocket *socket)
3085 if (socket->priv->event == WSA_INVALID_EVENT)
3086 socket->priv->event = WSACreateEvent();
3090 update_select_events (GSocket *socket)
3097 ensure_event (socket);
3100 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3103 event_mask |= network_events_for_condition (*ptr);
3106 if (event_mask != socket->priv->selected_events)
3108 /* If no events selected, disable event so we can unset
3111 if (event_mask == 0)
3114 event = socket->priv->event;
3116 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3117 socket->priv->selected_events = event_mask;
3122 add_condition_watch (GSocket *socket,
3123 GIOCondition *condition)
3125 g_mutex_lock (&socket->priv->win32_source_lock);
3126 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3128 socket->priv->requested_conditions =
3129 g_list_prepend (socket->priv->requested_conditions, condition);
3131 update_select_events (socket);
3132 g_mutex_unlock (&socket->priv->win32_source_lock);
3136 remove_condition_watch (GSocket *socket,
3137 GIOCondition *condition)
3139 g_mutex_lock (&socket->priv->win32_source_lock);
3140 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3142 socket->priv->requested_conditions =
3143 g_list_remove (socket->priv->requested_conditions, condition);
3145 update_select_events (socket);
3146 g_mutex_unlock (&socket->priv->win32_source_lock);
3150 update_condition (GSocket *socket)
3152 WSANETWORKEVENTS events;
3153 GIOCondition condition;
3155 if (WSAEnumNetworkEvents (socket->priv->fd,
3156 socket->priv->event,
3159 socket->priv->current_events |= events.lNetworkEvents;
3160 if (events.lNetworkEvents & FD_WRITE &&
3161 events.iErrorCode[FD_WRITE_BIT] != 0)
3162 socket->priv->current_errors |= FD_WRITE;
3163 if (events.lNetworkEvents & FD_CONNECT &&
3164 events.iErrorCode[FD_CONNECT_BIT] != 0)
3165 socket->priv->current_errors |= FD_CONNECT;
3169 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3170 condition |= G_IO_IN;
3172 if (socket->priv->current_events & FD_CLOSE)
3174 int r, errsv, buffer;
3176 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3178 errsv = get_socket_errno ();
3181 (r < 0 && errsv == WSAENOTCONN))
3182 condition |= G_IO_IN;
3184 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3185 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3186 condition |= G_IO_HUP;
3188 condition |= G_IO_ERR;
3191 if (socket->priv->closed)
3192 condition |= G_IO_HUP;
3194 /* Never report both G_IO_OUT and HUP, these are
3195 mutually exclusive (can't write to a closed socket) */
3196 if ((condition & G_IO_HUP) == 0 &&
3197 socket->priv->current_events & FD_WRITE)
3199 if (socket->priv->current_errors & FD_WRITE)
3200 condition |= G_IO_ERR;
3202 condition |= G_IO_OUT;
3206 if (socket->priv->current_events & FD_CONNECT)
3208 if (socket->priv->current_errors & FD_CONNECT)
3209 condition |= (G_IO_HUP | G_IO_ERR);
3211 condition |= G_IO_OUT;
3227 GIOCondition condition;
3232 socket_source_prepare_win32 (GSource *source,
3235 GSocketSource *socket_source = (GSocketSource *)source;
3239 return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3243 socket_source_check_win32 (GSource *source)
3247 return socket_source_prepare_win32 (source, &timeout);
3252 socket_source_dispatch (GSource *source,
3253 GSourceFunc callback,
3256 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3257 GSocketSource *socket_source = (GSocketSource *)source;
3258 GSocket *socket = socket_source->socket;
3264 events = update_condition (socket_source->socket);
3266 events = g_source_query_unix_fd (source, socket_source->fd_tag);
3269 timeout = g_source_get_ready_time (source);
3270 if (timeout >= 0 && timeout < g_source_get_time (source))
3272 socket->priv->timed_out = TRUE;
3273 events |= (G_IO_IN | G_IO_OUT);
3276 ret = (*func) (socket, events & socket_source->condition, user_data);
3278 if (socket->priv->timeout)
3279 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3281 g_source_set_ready_time (source, -1);
3287 socket_source_finalize (GSource *source)
3289 GSocketSource *socket_source = (GSocketSource *)source;
3292 socket = socket_source->socket;
3295 remove_condition_watch (socket, &socket_source->condition);
3298 g_object_unref (socket);
3302 socket_source_closure_callback (GSocket *socket,
3303 GIOCondition condition,
3306 GClosure *closure = data;
3308 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3309 GValue result_value = G_VALUE_INIT;
3312 g_value_init (&result_value, G_TYPE_BOOLEAN);
3314 g_value_init (¶ms[0], G_TYPE_SOCKET);
3315 g_value_set_object (¶ms[0], socket);
3316 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
3317 g_value_set_flags (¶ms[1], condition);
3319 g_closure_invoke (closure, &result_value, 2, params, NULL);
3321 result = g_value_get_boolean (&result_value);
3322 g_value_unset (&result_value);
3323 g_value_unset (¶ms[0]);
3324 g_value_unset (¶ms[1]);
3329 static GSourceFuncs socket_source_funcs =
3332 socket_source_prepare_win32,
3333 socket_source_check_win32,
3335 NULL, NULL, /* check, prepare */
3337 socket_source_dispatch,
3338 socket_source_finalize,
3339 (GSourceFunc)socket_source_closure_callback,
3343 socket_source_new (GSocket *socket,
3344 GIOCondition condition,
3345 GCancellable *cancellable)
3348 GSocketSource *socket_source;
3351 ensure_event (socket);
3353 if (socket->priv->event == WSA_INVALID_EVENT)
3355 g_warning ("Failed to create WSAEvent");
3356 return g_source_new (&broken_funcs, sizeof (GSource));
3360 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
3362 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3363 g_source_set_name (source, "GSocket");
3364 socket_source = (GSocketSource *)source;
3366 socket_source->socket = g_object_ref (socket);
3367 socket_source->condition = condition;
3371 GSource *cancellable_source;
3373 cancellable_source = g_cancellable_source_new (cancellable);
3374 g_source_add_child_source (source, cancellable_source);
3375 g_source_set_dummy_callback (cancellable_source);
3376 g_source_unref (cancellable_source);
3380 add_condition_watch (socket, &socket_source->condition);
3381 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3382 socket_source->pollfd.events = condition;
3383 socket_source->pollfd.revents = 0;
3384 g_source_add_poll (source, &socket_source->pollfd);
3386 socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
3389 if (socket->priv->timeout)
3390 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3392 g_source_set_ready_time (source, -1);
3398 * g_socket_create_source: (skip)
3399 * @socket: a #GSocket
3400 * @condition: a #GIOCondition mask to monitor
3401 * @cancellable: (allow-none): a %GCancellable or %NULL
3403 * Creates a #GSource that can be attached to a %GMainContext to monitor
3404 * for the availability of the specified @condition on the socket. The #GSource
3405 * keeps a reference to the @socket.
3407 * The callback on the source is of the #GSocketSourceFunc type.
3409 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3410 * these conditions will always be reported output if they are true.
3412 * @cancellable if not %NULL can be used to cancel the source, which will
3413 * cause the source to trigger, reporting the current condition (which
3414 * is likely 0 unless cancellation happened at the same time as a
3415 * condition change). You can check for this in the callback using
3416 * g_cancellable_is_cancelled().
3418 * If @socket has a timeout set, and it is reached before @condition
3419 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3420 * %G_IO_OUT depending on @condition. However, @socket will have been
3421 * marked as having had a timeout, and so the next #GSocket I/O method
3422 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3424 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3429 g_socket_create_source (GSocket *socket,
3430 GIOCondition condition,
3431 GCancellable *cancellable)
3433 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3435 return socket_source_new (socket, condition, cancellable);
3439 * g_socket_condition_check:
3440 * @socket: a #GSocket
3441 * @condition: a #GIOCondition mask to check
3443 * Checks on the readiness of @socket to perform operations.
3444 * The operations specified in @condition are checked for and masked
3445 * against the currently-satisfied conditions on @socket. The result
3448 * Note that on Windows, it is possible for an operation to return
3449 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3450 * g_socket_condition_check() has claimed that the socket is ready for
3451 * writing. Rather than calling g_socket_condition_check() and then
3452 * writing to the socket if it succeeds, it is generally better to
3453 * simply try writing to the socket right away, and try again later if
3454 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3456 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3457 * these conditions will always be set in the output if they are true.
3459 * This call never blocks.
3461 * Returns: the @GIOCondition mask of the current state
3466 g_socket_condition_check (GSocket *socket,
3467 GIOCondition condition)
3469 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3471 if (!check_socket (socket, NULL))
3476 GIOCondition current_condition;
3478 condition |= G_IO_ERR | G_IO_HUP;
3480 add_condition_watch (socket, &condition);
3481 current_condition = update_condition (socket);
3482 remove_condition_watch (socket, &condition);
3483 return condition & current_condition;
3489 poll_fd.fd = socket->priv->fd;
3490 poll_fd.events = condition;
3491 poll_fd.revents = 0;
3494 result = g_poll (&poll_fd, 1, 0);
3495 while (result == -1 && get_socket_errno () == EINTR);
3497 return poll_fd.revents;
3503 * g_socket_condition_wait:
3504 * @socket: a #GSocket
3505 * @condition: a #GIOCondition mask to wait for
3506 * @cancellable: (allow-none): a #GCancellable, or %NULL
3507 * @error: a #GError pointer, or %NULL
3509 * Waits for @condition to become true on @socket. When the condition
3510 * is met, %TRUE is returned.
3512 * If @cancellable is cancelled before the condition is met, or if the
3513 * socket has a timeout set and it is reached before the condition is
3514 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3515 * the appropriate value (%G_IO_ERROR_CANCELLED or
3516 * %G_IO_ERROR_TIMED_OUT).
3518 * See also g_socket_condition_timed_wait().
3520 * Returns: %TRUE if the condition was met, %FALSE otherwise
3525 g_socket_condition_wait (GSocket *socket,
3526 GIOCondition condition,
3527 GCancellable *cancellable,
3530 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3532 return g_socket_condition_timed_wait (socket, condition, -1,
3533 cancellable, error);
3537 * g_socket_condition_timed_wait:
3538 * @socket: a #GSocket
3539 * @condition: a #GIOCondition mask to wait for
3540 * @timeout: the maximum time (in microseconds) to wait, or -1
3541 * @cancellable: (allow-none): a #GCancellable, or %NULL
3542 * @error: a #GError pointer, or %NULL
3544 * Waits for up to @timeout microseconds for @condition to become true
3545 * on @socket. If the condition is met, %TRUE is returned.
3547 * If @cancellable is cancelled before the condition is met, or if
3548 * @timeout (or the socket's #GSocket:timeout) is reached before the
3549 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3550 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3551 * %G_IO_ERROR_TIMED_OUT).
3553 * If you don't want a timeout, use g_socket_condition_wait().
3554 * (Alternatively, you can pass -1 for @timeout.)
3556 * Note that although @timeout is in microseconds for consistency with
3557 * other GLib APIs, this function actually only has millisecond
3558 * resolution, and the behavior is undefined if @timeout is not an
3559 * exact number of milliseconds.
3561 * Returns: %TRUE if the condition was met, %FALSE otherwise
3566 g_socket_condition_timed_wait (GSocket *socket,
3567 GIOCondition condition,
3569 GCancellable *cancellable,
3574 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3576 if (!check_socket (socket, error))
3579 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3582 if (socket->priv->timeout &&
3583 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3584 timeout = socket->priv->timeout * 1000;
3585 else if (timeout != -1)
3586 timeout = timeout / 1000;
3588 start_time = g_get_monotonic_time ();
3592 GIOCondition current_condition;
3598 /* Always check these */
3599 condition |= G_IO_ERR | G_IO_HUP;
3601 add_condition_watch (socket, &condition);
3604 events[num_events++] = socket->priv->event;
3606 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3607 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3610 timeout = WSA_INFINITE;
3612 current_condition = update_condition (socket);
3613 while ((condition & current_condition) == 0)
3615 res = WSAWaitForMultipleEvents (num_events, events,
3616 FALSE, timeout, FALSE);
3617 if (res == WSA_WAIT_FAILED)
3619 int errsv = get_socket_errno ();
3621 g_set_error (error, G_IO_ERROR,
3622 socket_io_error_from_errno (errsv),
3623 _("Waiting for socket condition: %s"),
3624 socket_strerror (errsv));
3627 else if (res == WSA_WAIT_TIMEOUT)
3629 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3630 _("Socket I/O timed out"));
3634 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3637 current_condition = update_condition (socket);
3639 if (timeout != WSA_INFINITE)
3641 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3646 remove_condition_watch (socket, &condition);
3648 g_cancellable_release_fd (cancellable);
3650 return (condition & current_condition) != 0;
3658 poll_fd[0].fd = socket->priv->fd;
3659 poll_fd[0].events = condition;
3662 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3667 result = g_poll (poll_fd, num, timeout);
3668 if (result != -1 || errno != EINTR)
3673 timeout -= (g_get_monotonic_time () - start_time) / 1000;
3680 g_cancellable_release_fd (cancellable);
3684 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3685 _("Socket I/O timed out"));
3689 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3695 * g_socket_send_message:
3696 * @socket: a #GSocket
3697 * @address: (allow-none): a #GSocketAddress, or %NULL
3698 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3699 * @num_vectors: the number of elements in @vectors, or -1
3700 * @messages: (array length=num_messages) (allow-none): a pointer to an
3701 * array of #GSocketControlMessages, or %NULL.
3702 * @num_messages: number of elements in @messages, or -1.
3703 * @flags: an int containing #GSocketMsgFlags flags
3704 * @cancellable: (allow-none): a %GCancellable or %NULL
3705 * @error: #GError for error reporting, or %NULL to ignore.
3707 * Send data to @address on @socket. This is the most complicated and
3708 * fully-featured version of this call. For easier use, see
3709 * g_socket_send() and g_socket_send_to().
3711 * If @address is %NULL then the message is sent to the default receiver
3712 * (set by g_socket_connect()).
3714 * @vectors must point to an array of #GOutputVector structs and
3715 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3716 * then @vectors is assumed to be terminated by a #GOutputVector with a
3717 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3718 * that the sent data will be gathered from. Using multiple
3719 * #GOutputVectors is more memory-efficient than manually copying
3720 * data from multiple sources into a single buffer, and more
3721 * network-efficient than making multiple calls to g_socket_send().
3723 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3724 * #GSocketControlMessage instances. These correspond to the control
3725 * messages to be sent on the socket.
3726 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3729 * @flags modify how the message is sent. The commonly available arguments
3730 * for this are available in the #GSocketMsgFlags enum, but the
3731 * values there are the same as the system values, and the flags
3732 * are passed in as-is, so you can pass in system-specific flags too.
3734 * If the socket is in blocking mode the call will block until there is
3735 * space for the data in the socket queue. If there is no space available
3736 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3737 * will be returned. To be notified when space is available, wait for the
3738 * %G_IO_OUT condition. Note though that you may still receive
3739 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3740 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3741 * very common due to the way the underlying APIs work.)
3743 * On error -1 is returned and @error is set accordingly.
3745 * Returns: Number of bytes written (which may be less than @size), or -1
3751 g_socket_send_message (GSocket *socket,
3752 GSocketAddress *address,
3753 GOutputVector *vectors,
3755 GSocketControlMessage **messages,
3758 GCancellable *cancellable,
3761 GOutputVector one_vector;
3764 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3765 g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), -1);
3766 g_return_val_if_fail (num_vectors == 0 || vectors != NULL, -1);
3767 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
3768 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
3769 g_return_val_if_fail (error == NULL || *error == NULL, -1);
3771 if (!check_socket (socket, error))
3774 if (!check_timeout (socket, error))
3777 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3780 if (num_vectors == -1)
3782 for (num_vectors = 0;
3783 vectors[num_vectors].buffer != NULL;
3788 if (num_messages == -1)
3790 for (num_messages = 0;
3791 messages != NULL && messages[num_messages] != NULL;
3796 if (num_vectors == 0)
3800 one_vector.buffer = &zero;
3801 one_vector.size = 1;
3803 vectors = &one_vector;
3816 msg.msg_namelen = g_socket_address_get_native_size (address);
3817 msg.msg_name = g_alloca (msg.msg_namelen);
3818 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3823 msg.msg_name = NULL;
3824 msg.msg_namelen = 0;
3829 /* this entire expression will be evaluated at compile time */
3830 if (sizeof *msg.msg_iov == sizeof *vectors &&
3831 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3832 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3833 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3834 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3835 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3836 G_STRUCT_OFFSET (GOutputVector, size))
3837 /* ABI is compatible */
3839 msg.msg_iov = (struct iovec *) vectors;
3840 msg.msg_iovlen = num_vectors;
3843 /* ABI is incompatible */
3847 msg.msg_iov = g_newa (struct iovec, num_vectors);
3848 for (i = 0; i < num_vectors; i++)
3850 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3851 msg.msg_iov[i].iov_len = vectors[i].size;
3853 msg.msg_iovlen = num_vectors;
3859 struct cmsghdr *cmsg;
3862 msg.msg_controllen = 0;
3863 for (i = 0; i < num_messages; i++)
3864 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3866 if (msg.msg_controllen == 0)
3867 msg.msg_control = NULL;
3870 msg.msg_control = g_alloca (msg.msg_controllen);
3871 memset (msg.msg_control, '\0', msg.msg_controllen);
3874 cmsg = CMSG_FIRSTHDR (&msg);
3875 for (i = 0; i < num_messages; i++)
3877 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3878 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3879 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3880 g_socket_control_message_serialize (messages[i],
3882 cmsg = CMSG_NXTHDR (&msg, cmsg);
3884 g_assert (cmsg == NULL);
3889 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3892 int errsv = get_socket_errno ();
3897 if (socket->priv->blocking &&
3898 (errsv == EWOULDBLOCK ||
3901 if (!g_socket_condition_wait (socket,
3902 G_IO_OUT, cancellable, error))
3908 g_set_error (error, G_IO_ERROR,
3909 socket_io_error_from_errno (errsv),
3910 _("Error sending message: %s"), socket_strerror (errsv));
3921 struct sockaddr_storage addr;
3928 /* Win32 doesn't support control messages.
3929 Actually this is possible for raw and datagram sockets
3930 via WSASendMessage on Vista or later, but that doesn't
3932 if (num_messages != 0)
3934 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3935 _("GSocketControlMessage not supported on Windows"));
3940 bufs = g_newa (WSABUF, num_vectors);
3941 for (i = 0; i < num_vectors; i++)
3943 bufs[i].buf = (char *)vectors[i].buffer;
3944 bufs[i].len = (gulong)vectors[i].size;
3948 addrlen = 0; /* Avoid warning */
3951 addrlen = g_socket_address_get_native_size (address);
3952 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3959 result = WSASendTo (socket->priv->fd,
3962 (const struct sockaddr *)&addr, addrlen,
3965 result = WSASend (socket->priv->fd,
3972 int errsv = get_socket_errno ();
3974 if (errsv == WSAEINTR)
3977 if (errsv == WSAEWOULDBLOCK)
3979 win32_unset_event_mask (socket, FD_WRITE);
3981 if (socket->priv->blocking)
3983 if (!g_socket_condition_wait (socket,
3984 G_IO_OUT, cancellable, error))
3991 g_set_error (error, G_IO_ERROR,
3992 socket_io_error_from_errno (errsv),
3993 _("Error sending message: %s"), socket_strerror (errsv));
4006 * g_socket_send_messages:
4007 * @socket: a #GSocket
4008 * @messages: (array length=num_messages): an array of #GOutputMessage structs
4009 * @num_messages: the number of elements in @messages
4010 * @flags: an int containing #GSocketMsgFlags flags
4011 * @cancellable: (allow-none): a %GCancellable or %NULL
4012 * @error: #GError for error reporting, or %NULL to ignore.
4014 * Send multiple data messages from @socket in one go. This is the most
4015 * complicated and fully-featured version of this call. For easier use, see
4016 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
4018 * @messages must point to an array of #GOutputMessage structs and
4019 * @num_messages must be the length of this array. Each #GOutputMessage
4020 * contains an address to send the data to, and a pointer to an array of
4021 * #GOutputVector structs to describe the buffers that the data to be sent
4022 * for each message will be gathered from. Using multiple #GOutputVectors is
4023 * more memory-efficient than manually copying data from multiple sources
4024 * into a single buffer, and more network-efficient than making multiple
4025 * calls to g_socket_send(). Sending multiple messages in one go avoids the
4026 * overhead of making a lot of syscalls in scenarios where a lot of data
4027 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
4028 * or where the same data needs to be sent to multiple recipients.
4030 * @flags modify how the message is sent. The commonly available arguments
4031 * for this are available in the #GSocketMsgFlags enum, but the
4032 * values there are the same as the system values, and the flags
4033 * are passed in as-is, so you can pass in system-specific flags too.
4035 * If the socket is in blocking mode the call will block until there is
4036 * space for all the data in the socket queue. If there is no space available
4037 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4038 * will be returned if no data was written at all, otherwise the number of
4039 * messages sent will be returned. To be notified when space is available,
4040 * wait for the %G_IO_OUT condition. Note though that you may still receive
4041 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4042 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4043 * very common due to the way the underlying APIs work.)
4045 * On error -1 is returned and @error is set accordingly.
4047 * Returns: number of messages sent, or -1 on error. Note that the number of
4048 * messages sent may be smaller than @num_messages if the socket is
4049 * non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
4050 * in which case the caller may re-try to send the remaining messages.
4055 g_socket_send_messages (GSocket *socket,
4056 GOutputMessage *messages,
4059 GCancellable *cancellable,
4062 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4063 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
4064 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
4065 g_return_val_if_fail (error == NULL || *error == NULL, -1);
4067 if (!check_socket (socket, error))
4070 if (!check_timeout (socket, error))
4073 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4076 if (num_messages == 0)
4079 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
4081 struct mmsghdr *msgvec;
4082 gint i, num_sent, result, max_sent;
4085 #define MAX_NUM_MESSAGES UIO_MAXIOV
4087 #define MAX_NUM_MESSAGES 1024
4090 if (num_messages > MAX_NUM_MESSAGES)
4091 num_messages = MAX_NUM_MESSAGES;
4093 msgvec = g_newa (struct mmsghdr, num_messages);
4095 for (i = 0; i < num_messages; ++i)
4097 GOutputMessage *msg = &messages[i];
4098 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
4100 msgvec[i].msg_len = 0;
4102 msg_hdr->msg_flags = 0;
4105 if (i > 0 && msg->address == messages[i-1].address)
4107 msg_hdr->msg_name = msgvec[i-1].msg_hdr.msg_name;
4108 msg_hdr->msg_namelen = msgvec[i-1].msg_hdr.msg_namelen;
4110 else if (msg->address)
4112 msg_hdr->msg_namelen = g_socket_address_get_native_size (msg->address);
4113 msg_hdr->msg_name = g_alloca (msg_hdr->msg_namelen);
4114 if (!g_socket_address_to_native (msg->address, msg_hdr->msg_name, msg_hdr->msg_namelen, error))
4119 msg_hdr->msg_name = NULL;
4120 msg_hdr->msg_namelen = 0;
4125 /* this entire expression will be evaluated at compile time */
4126 if (sizeof (struct iovec) == sizeof (GOutputVector) &&
4127 sizeof msg_hdr->msg_iov->iov_base == sizeof msg->vectors->buffer &&
4128 G_STRUCT_OFFSET (struct iovec, iov_base) ==
4129 G_STRUCT_OFFSET (GOutputVector, buffer) &&
4130 sizeof msg_hdr->msg_iov->iov_len == sizeof msg->vectors->size &&
4131 G_STRUCT_OFFSET (struct iovec, iov_len) ==
4132 G_STRUCT_OFFSET (GOutputVector, size))
4133 /* ABI is compatible */
4135 msg_hdr->msg_iov = (struct iovec *) msg->vectors;
4136 msg_hdr->msg_iovlen = msg->num_vectors;
4139 /* ABI is incompatible */
4143 msg_hdr->msg_iov = g_newa (struct iovec, msg->num_vectors);
4144 for (j = 0; j < msg->num_vectors; j++)
4146 msg_hdr->msg_iov[j].iov_base = (void *) msg->vectors[j].buffer;
4147 msg_hdr->msg_iov[j].iov_len = msg->vectors[j].size;
4149 msg_hdr->msg_iovlen = msg->num_vectors;
4155 struct cmsghdr *cmsg;
4158 msg_hdr->msg_controllen = 0;
4159 for (j = 0; j < msg->num_control_messages; j++)
4160 msg_hdr->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (msg->control_messages[j]));
4162 if (msg_hdr->msg_controllen == 0)
4163 msg_hdr->msg_control = NULL;
4166 msg_hdr->msg_control = g_alloca (msg_hdr->msg_controllen);
4167 memset (msg_hdr->msg_control, '\0', msg_hdr->msg_controllen);
4170 cmsg = CMSG_FIRSTHDR (msg_hdr);
4171 for (j = 0; j < msg->num_control_messages; j++)
4173 GSocketControlMessage *cm = msg->control_messages[j];
4175 cmsg->cmsg_level = g_socket_control_message_get_level (cm);
4176 cmsg->cmsg_type = g_socket_control_message_get_msg_type (cm);
4177 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (cm));
4178 g_socket_control_message_serialize (cm, CMSG_DATA (cmsg));
4179 cmsg = CMSG_NXTHDR (msg_hdr, cmsg);
4181 g_assert (cmsg == NULL);
4185 num_sent = result = 0;
4186 max_sent = num_messages;
4187 while (num_sent < num_messages)
4191 if (socket->priv->blocking &&
4192 !g_socket_condition_wait (socket,
4193 G_IO_OUT, cancellable, error))
4196 ret = sendmmsg (socket->priv->fd, msgvec + num_sent, num_messages - num_sent,
4197 flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4201 int errsv = get_socket_errno ();
4206 if (socket->priv->blocking &&
4207 (errsv == EWOULDBLOCK ||
4212 (errsv == EWOULDBLOCK ||
4215 max_sent = num_sent;
4219 g_set_error (error, G_IO_ERROR,
4220 socket_io_error_from_errno (errsv),
4221 _("Error sending message: %s"), socket_strerror (errsv));
4223 /* we have to iterate over all messages below now, because we don't
4224 * know where between num_sent and num_messages the error occured */
4225 max_sent = num_messages;
4235 for (i = 0; i < max_sent; ++i)
4236 messages[i].bytes_sent = msgvec[i].msg_len;
4245 for (i = 0; i < num_messages; ++i)
4247 GOutputMessage *msg = &messages[i];
4248 GError *msg_error = NULL;
4250 result = g_socket_send_message (socket, msg->address,
4251 msg->vectors, msg->num_vectors,
4252 msg->control_messages,
4253 msg->num_control_messages,
4254 flags, cancellable, &msg_error);
4258 /* if we couldn't send all messages, just return how many we did
4259 * manage to send, provided we managed to send at least one */
4260 if (msg_error->code == G_IO_ERROR_WOULD_BLOCK && i > 0)
4262 g_error_free (msg_error);
4267 g_propagate_error (error, msg_error);
4272 msg->bytes_sent = result;
4280 static GSocketAddress *
4281 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
4283 GSocketAddress *saddr;
4285 guint64 oldest_time = G_MAXUINT64;
4286 gint oldest_index = 0;
4288 if (native_len <= 0)
4292 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
4294 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
4295 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
4296 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
4301 if (tmp_native_len != native_len)
4304 if (memcmp (tmp_native, native, native_len) == 0)
4306 saddr = g_object_ref (tmp);
4307 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
4311 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
4313 oldest_time = socket->priv->recv_addr_cache[i].last_used;
4318 saddr = g_socket_address_new_from_native (native, native_len);
4320 if (socket->priv->recv_addr_cache[oldest_index].addr)
4322 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
4323 g_free (socket->priv->recv_addr_cache[oldest_index].native);
4326 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
4327 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
4328 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
4329 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
4335 * g_socket_receive_message:
4336 * @socket: a #GSocket
4337 * @address: (out) (allow-none): a pointer to a #GSocketAddress
4339 * @vectors: (array length=num_vectors): an array of #GInputVector structs
4340 * @num_vectors: the number of elements in @vectors, or -1
4341 * @messages: (array length=num_messages) (allow-none): a pointer which
4342 * may be filled with an array of #GSocketControlMessages, or %NULL
4343 * @num_messages: a pointer which will be filled with the number of
4344 * elements in @messages, or %NULL
4345 * @flags: a pointer to an int containing #GSocketMsgFlags flags
4346 * @cancellable: (allow-none): a %GCancellable or %NULL
4347 * @error: a #GError pointer, or %NULL
4349 * Receive data from a socket. This is the most complicated and
4350 * fully-featured version of this call. For easier use, see
4351 * g_socket_receive() and g_socket_receive_from().
4353 * If @address is non-%NULL then @address will be set equal to the
4354 * source address of the received packet.
4355 * @address is owned by the caller.
4357 * @vector must point to an array of #GInputVector structs and
4358 * @num_vectors must be the length of this array. These structs
4359 * describe the buffers that received data will be scattered into.
4360 * If @num_vectors is -1, then @vectors is assumed to be terminated
4361 * by a #GInputVector with a %NULL buffer pointer.
4363 * As a special case, if @num_vectors is 0 (in which case, @vectors
4364 * may of course be %NULL), then a single byte is received and
4365 * discarded. This is to facilitate the common practice of sending a
4366 * single '\0' byte for the purposes of transferring ancillary data.
4368 * @messages, if non-%NULL, will be set to point to a newly-allocated
4369 * array of #GSocketControlMessage instances or %NULL if no such
4370 * messages was received. These correspond to the control messages
4371 * received from the kernel, one #GSocketControlMessage per message
4372 * from the kernel. This array is %NULL-terminated and must be freed
4373 * by the caller using g_free() after calling g_object_unref() on each
4374 * element. If @messages is %NULL, any control messages received will
4377 * @num_messages, if non-%NULL, will be set to the number of control
4378 * messages received.
4380 * If both @messages and @num_messages are non-%NULL, then
4381 * @num_messages gives the number of #GSocketControlMessage instances
4382 * in @messages (ie: not including the %NULL terminator).
4384 * @flags is an in/out parameter. The commonly available arguments
4385 * for this are available in the #GSocketMsgFlags enum, but the
4386 * values there are the same as the system values, and the flags
4387 * are passed in as-is, so you can pass in system-specific flags too
4388 * (and g_socket_receive_message() may pass system-specific flags out).
4390 * As with g_socket_receive(), data may be discarded if @socket is
4391 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
4392 * provide enough buffer space to read a complete message. You can pass
4393 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
4394 * removing it from the receive queue, but there is no portable way to find
4395 * out the length of the message other than by reading it into a
4396 * sufficiently-large buffer.
4398 * If the socket is in blocking mode the call will block until there
4399 * is some data to receive, the connection is closed, or there is an
4400 * error. If there is no data available and the socket is in
4401 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
4402 * returned. To be notified when data is available, wait for the
4403 * %G_IO_IN condition.
4405 * On error -1 is returned and @error is set accordingly.
4407 * Returns: Number of bytes read, or 0 if the connection was closed by
4408 * the peer, or -1 on error
4413 g_socket_receive_message (GSocket *socket,
4414 GSocketAddress **address,
4415 GInputVector *vectors,
4417 GSocketControlMessage ***messages,
4420 GCancellable *cancellable,
4423 GInputVector one_vector;
4426 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4428 if (!check_socket (socket, error))
4431 if (!check_timeout (socket, error))
4434 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4437 if (num_vectors == -1)
4439 for (num_vectors = 0;
4440 vectors[num_vectors].buffer != NULL;
4445 if (num_vectors == 0)
4447 one_vector.buffer = &one_byte;
4448 one_vector.size = 1;
4450 vectors = &one_vector;
4457 struct sockaddr_storage one_sockaddr;
4462 msg.msg_name = &one_sockaddr;
4463 msg.msg_namelen = sizeof (struct sockaddr_storage);
4467 msg.msg_name = NULL;
4468 msg.msg_namelen = 0;
4472 /* this entire expression will be evaluated at compile time */
4473 if (sizeof *msg.msg_iov == sizeof *vectors &&
4474 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4475 G_STRUCT_OFFSET (struct iovec, iov_base) ==
4476 G_STRUCT_OFFSET (GInputVector, buffer) &&
4477 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4478 G_STRUCT_OFFSET (struct iovec, iov_len) ==
4479 G_STRUCT_OFFSET (GInputVector, size))
4480 /* ABI is compatible */
4482 msg.msg_iov = (struct iovec *) vectors;
4483 msg.msg_iovlen = num_vectors;
4486 /* ABI is incompatible */
4490 msg.msg_iov = g_newa (struct iovec, num_vectors);
4491 for (i = 0; i < num_vectors; i++)
4493 msg.msg_iov[i].iov_base = vectors[i].buffer;
4494 msg.msg_iov[i].iov_len = vectors[i].size;
4496 msg.msg_iovlen = num_vectors;
4500 msg.msg_control = g_alloca (2048);
4501 msg.msg_controllen = 2048;
4505 msg.msg_flags = *flags;
4509 /* We always set the close-on-exec flag so we don't leak file
4510 * descriptors into child processes. Note that gunixfdmessage.c
4511 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4513 #ifdef MSG_CMSG_CLOEXEC
4514 msg.msg_flags |= MSG_CMSG_CLOEXEC;
4520 if (socket->priv->blocking &&
4521 !g_socket_condition_wait (socket,
4522 G_IO_IN, cancellable, error))
4525 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4526 #ifdef MSG_CMSG_CLOEXEC
4527 if (result < 0 && get_socket_errno () == EINVAL)
4529 /* We must be running on an old kernel. Call without the flag. */
4530 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4531 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4537 int errsv = get_socket_errno ();
4542 if (socket->priv->blocking &&
4543 (errsv == EWOULDBLOCK ||
4547 g_set_error (error, G_IO_ERROR,
4548 socket_io_error_from_errno (errsv),
4549 _("Error receiving message: %s"), socket_strerror (errsv));
4556 /* decode address */
4557 if (address != NULL)
4559 *address = cache_recv_address (socket, msg.msg_name, msg.msg_namelen);
4562 /* decode control messages */
4564 GPtrArray *my_messages = NULL;
4565 struct cmsghdr *cmsg;
4567 if (msg.msg_controllen >= sizeof (struct cmsghdr))
4569 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4571 GSocketControlMessage *message;
4573 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4575 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4577 if (message == NULL)
4578 /* We've already spewed about the problem in the
4579 deserialization code, so just continue */
4582 if (messages == NULL)
4584 /* we have to do it this way if the user ignores the
4585 * messages so that we will close any received fds.
4587 g_object_unref (message);
4591 if (my_messages == NULL)
4592 my_messages = g_ptr_array_new ();
4593 g_ptr_array_add (my_messages, message);
4599 *num_messages = my_messages != NULL ? my_messages->len : 0;
4603 if (my_messages == NULL)
4609 g_ptr_array_add (my_messages, NULL);
4610 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4615 g_assert (my_messages == NULL);
4619 /* capture the flags */
4621 *flags = msg.msg_flags;
4627 struct sockaddr_storage addr;
4629 DWORD bytes_received;
4636 bufs = g_newa (WSABUF, num_vectors);
4637 for (i = 0; i < num_vectors; i++)
4639 bufs[i].buf = (char *)vectors[i].buffer;
4640 bufs[i].len = (gulong)vectors[i].size;
4652 addrlen = sizeof addr;
4654 result = WSARecvFrom (socket->priv->fd,
4656 &bytes_received, &win_flags,
4657 (struct sockaddr *)&addr, &addrlen,
4660 result = WSARecv (socket->priv->fd,
4662 &bytes_received, &win_flags,
4666 int errsv = get_socket_errno ();
4668 if (errsv == WSAEINTR)
4671 if (errsv == WSAEWOULDBLOCK)
4673 win32_unset_event_mask (socket, FD_READ);
4675 if (socket->priv->blocking)
4677 if (!g_socket_condition_wait (socket,
4678 G_IO_IN, cancellable, error))
4685 g_set_error (error, G_IO_ERROR,
4686 socket_io_error_from_errno (errsv),
4687 _("Error receiving message: %s"), socket_strerror (errsv));
4691 win32_unset_event_mask (socket, FD_READ);
4695 /* decode address */
4696 if (address != NULL)
4698 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
4701 /* capture the flags */
4705 if (messages != NULL)
4707 if (num_messages != NULL)
4710 return bytes_received;
4716 * g_socket_get_credentials:
4717 * @socket: a #GSocket.
4718 * @error: #GError for error reporting, or %NULL to ignore.
4720 * Returns the credentials of the foreign process connected to this
4721 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4724 * If this operation isn't supported on the OS, the method fails with
4725 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4726 * by reading the %SO_PEERCRED option on the underlying socket.
4728 * Other ways to obtain credentials from a foreign peer includes the
4729 * #GUnixCredentialsMessage type and
4730 * g_unix_connection_send_credentials() /
4731 * g_unix_connection_receive_credentials() functions.
4733 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4734 * that must be freed with g_object_unref().
4739 g_socket_get_credentials (GSocket *socket,
4744 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4745 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4749 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
4753 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
4754 socklen_t optlen = sizeof (native_creds_buf);
4756 if (getsockopt (socket->priv->fd,
4762 ret = g_credentials_new ();
4763 g_credentials_set_native (ret,
4764 G_CREDENTIALS_NATIVE_TYPE,
4768 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
4770 struct unpcbid cred;
4771 socklen_t optlen = sizeof (cred);
4773 if (getsockopt (socket->priv->fd,
4779 ret = g_credentials_new ();
4780 g_credentials_set_native (ret,
4781 G_CREDENTIALS_NATIVE_TYPE,
4785 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
4787 ucred_t *ucred = NULL;
4789 if (getpeerucred (socket->priv->fd, &ucred) == 0)
4791 ret = g_credentials_new ();
4792 g_credentials_set_native (ret,
4793 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
4799 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
4804 int errsv = get_socket_errno ();
4808 socket_io_error_from_errno (errsv),
4809 _("Unable to read socket credentials: %s"),
4810 socket_strerror (errsv));
4815 g_set_error_literal (error,
4817 G_IO_ERROR_NOT_SUPPORTED,
4818 _("g_socket_get_credentials not implemented for this OS"));
4825 * g_socket_get_option:
4826 * @socket: a #GSocket
4827 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
4828 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
4829 * @value: (out): return location for the option value
4830 * @error: #GError for error reporting, or %NULL to ignore.
4832 * Gets the value of an integer-valued option on @socket, as with
4833 * getsockopt(). (If you need to fetch a non-integer-valued option,
4834 * you will need to call getsockopt() directly.)
4836 * The [<gio/gnetworking.h>][gio-gnetworking.h]
4837 * header pulls in system headers that will define most of the
4838 * standard/portable socket options. For unusual socket protocols or
4839 * platform-dependent options, you may need to include additional
4842 * Note that even for socket options that are a single byte in size,
4843 * @value is still a pointer to a #gint variable, not a #guchar;
4844 * g_socket_get_option() will handle the conversion internally.
4846 * Returns: success or failure. On failure, @error will be set, and
4847 * the system error value (`errno` or WSAGetLastError()) will still
4848 * be set to the result of the getsockopt() call.
4853 g_socket_get_option (GSocket *socket,
4861 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4864 size = sizeof (gint);
4865 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
4867 int errsv = get_socket_errno ();
4869 g_set_error_literal (error,
4871 socket_io_error_from_errno (errsv),
4872 socket_strerror (errsv));
4874 /* Reset errno in case the caller wants to look at it */
4880 #if G_BYTE_ORDER == G_BIG_ENDIAN
4881 /* If the returned value is smaller than an int then we need to
4882 * slide it over into the low-order bytes of *value.
4884 if (size != sizeof (gint))
4885 *value = *value >> (8 * (sizeof (gint) - size));
4892 * g_socket_set_option:
4893 * @socket: a #GSocket
4894 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
4895 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
4896 * @value: the value to set the option to
4897 * @error: #GError for error reporting, or %NULL to ignore.
4899 * Sets the value of an integer-valued option on @socket, as with
4900 * setsockopt(). (If you need to set a non-integer-valued option,
4901 * you will need to call setsockopt() directly.)
4903 * The [<gio/gnetworking.h>][gio-gnetworking.h]
4904 * header pulls in system headers that will define most of the
4905 * standard/portable socket options. For unusual socket protocols or
4906 * platform-dependent options, you may need to include additional
4909 * Returns: success or failure. On failure, @error will be set, and
4910 * the system error value (`errno` or WSAGetLastError()) will still
4911 * be set to the result of the setsockopt() call.
4916 g_socket_set_option (GSocket *socket,
4924 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4926 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
4929 #if !defined (__linux__) && !defined (G_OS_WIN32)
4930 /* Linux and Windows let you set a single-byte value from an int,
4931 * but most other platforms don't.
4933 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
4935 #if G_BYTE_ORDER == G_BIG_ENDIAN
4936 value = value << (8 * (sizeof (gint) - 1));
4938 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
4943 errsv = get_socket_errno ();
4945 g_set_error_literal (error,
4947 socket_io_error_from_errno (errsv),
4948 socket_strerror (errsv));