1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2008 Christian Kellner, Samuel Cormier-Iijima
4 * Copyright © 2009 Codethink Limited
5 * Copyright © 2009 Red Hat, Inc
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General
18 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 * Authors: Christian Kellner <gicmo@gnome.org>
21 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
22 * Ryan Lortie <desrt@desrt.ca>
23 * Alexander Larsson <alexl@redhat.com>
31 #include "glib-unix.h"
42 # include <sys/ioctl.h>
45 #ifdef HAVE_SYS_FILIO_H
46 # include <sys/filio.h>
53 #include "gcancellable.h"
54 #include "gioenumtypes.h"
55 #include "ginetaddress.h"
56 #include "ginitable.h"
60 #include "gnetworkingprivate.h"
61 #include "gsocketaddress.h"
62 #include "gsocketcontrolmessage.h"
63 #include "gcredentials.h"
64 #include "gcredentialsprivate.h"
69 * @short_description: Low-level socket object
71 * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
73 * A #GSocket is a low-level networking primitive. It is a more or less
74 * direct mapping of the BSD socket API in a portable GObject based API.
75 * It supports both the UNIX socket implementations and winsock2 on Windows.
77 * #GSocket is the platform independent base upon which the higher level
78 * network primitives are based. Applications are not typically meant to
79 * use it directly, but rather through classes like #GSocketClient,
80 * #GSocketService and #GSocketConnection. However there may be cases where
81 * direct use of #GSocket is useful.
83 * #GSocket implements the #GInitable interface, so if it is manually constructed
84 * by e.g. g_object_new() you must call g_initable_init() and check the
85 * results before using the object. This is done automatically in
86 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
89 * Sockets operate in two general modes, blocking or non-blocking. When
90 * in blocking mode all operations block until the requested operation
91 * is finished or there is an error. In non-blocking mode all calls that
92 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
93 * To know when a call would successfully run you can call g_socket_condition_check(),
94 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
95 * attach it to a #GMainContext to get callbacks when I/O is possible.
96 * Note that all sockets are always set to non blocking mode in the system, and
97 * blocking mode is emulated in GSocket.
99 * When working in non-blocking mode applications should always be able to
100 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
101 * function said that I/O was possible. This can easily happen in case
102 * of a race condition in the application, but it can also happen for other
103 * reasons. For instance, on Windows a socket is always seen as writable
104 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
106 * #GSockets can be either connection oriented or datagram based.
107 * For connection oriented types you must first establish a connection by
108 * either connecting to an address or accepting a connection from another
109 * address. For connectionless socket types the target/source address is
110 * specified or received in each I/O operation.
112 * All socket file descriptors are set to be close-on-exec.
114 * Note that creating a #GSocket causes the signal %SIGPIPE to be
115 * ignored for the remainder of the program. If you are writing a
116 * command-line utility that uses #GSocket, you may need to take into
117 * account the fact that your program will not automatically be killed
118 * if it tries to write to %stdout after it has been closed.
120 * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
121 * a #GSocket concurrently from multiple threads, you must implement your own
127 static void g_socket_initable_iface_init (GInitableIface *iface);
128 static gboolean g_socket_initable_init (GInitable *initable,
129 GCancellable *cancellable,
147 PROP_MULTICAST_LOOPBACK,
151 /* Size of the receiver cache for g_socket_receive_from() */
152 #define RECV_ADDR_CACHE_SIZE 8
154 struct _GSocketPrivate
156 GSocketFamily family;
158 GSocketProtocol protocol;
162 GError *construct_error;
163 GSocketAddress *remote_address;
171 guint connect_pending : 1;
177 GList *requested_conditions; /* list of requested GIOCondition * */
178 GMutex win32_source_lock;
182 GSocketAddress *addr;
183 struct sockaddr *native;
186 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
189 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
190 G_ADD_PRIVATE (GSocket)
191 g_networking_init ();
192 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
193 g_socket_initable_iface_init));
196 get_socket_errno (void)
201 return WSAGetLastError ();
206 socket_io_error_from_errno (int err)
209 return g_io_error_from_win32_error (err);
211 return g_io_error_from_errno (err);
216 socket_strerror (int err)
219 return g_strerror (err);
224 msg = g_win32_error_message (err);
226 msg_ret = g_intern_string (msg);
234 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
236 _win32_unset_event_mask (GSocket *socket, int mask)
238 socket->priv->current_events &= ~mask;
239 socket->priv->current_errors &= ~mask;
242 #define win32_unset_event_mask(_socket, _mask)
245 /* Windows has broken prototypes... */
247 #define getsockopt(sockfd, level, optname, optval, optlen) \
248 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
249 #define setsockopt(sockfd, level, optname, optval, optlen) \
250 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
251 #define getsockname(sockfd, addr, addrlen) \
252 getsockname (sockfd, addr, (int *)addrlen)
253 #define getpeername(sockfd, addr, addrlen) \
254 getpeername (sockfd, addr, (int *)addrlen)
255 #define recv(sockfd, buf, len, flags) \
256 recv (sockfd, (gpointer)buf, len, flags)
260 check_socket (GSocket *socket,
263 if (!socket->priv->inited)
265 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
266 _("Invalid socket, not initialized"));
270 if (socket->priv->construct_error)
272 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
273 _("Invalid socket, initialization failed due to: %s"),
274 socket->priv->construct_error->message);
278 if (socket->priv->closed)
280 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
281 _("Socket is already closed"));
289 check_timeout (GSocket *socket,
292 if (socket->priv->timed_out)
294 socket->priv->timed_out = FALSE;
295 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
296 _("Socket I/O timed out"));
304 g_socket_details_from_fd (GSocket *socket)
306 struct sockaddr_storage address;
312 fd = socket->priv->fd;
313 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
315 errsv = get_socket_errno ();
327 /* programmer error */
328 g_error ("creating GSocket from fd %d: %s\n",
329 fd, socket_strerror (errsv));
340 socket->priv->type = G_SOCKET_TYPE_STREAM;
344 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
348 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
352 socket->priv->type = G_SOCKET_TYPE_INVALID;
356 addrlen = sizeof address;
357 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
359 errsv = get_socket_errno ();
365 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
366 sizeof address.ss_family <= addrlen);
367 family = address.ss_family;
371 /* On Solaris, this happens if the socket is not yet connected.
372 * But we can use SO_DOMAIN as a workaround there.
375 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
377 errsv = get_socket_errno ();
381 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
389 case G_SOCKET_FAMILY_IPV4:
390 case G_SOCKET_FAMILY_IPV6:
391 socket->priv->family = address.ss_family;
392 switch (socket->priv->type)
394 case G_SOCKET_TYPE_STREAM:
395 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
398 case G_SOCKET_TYPE_DATAGRAM:
399 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
402 case G_SOCKET_TYPE_SEQPACKET:
403 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
411 case G_SOCKET_FAMILY_UNIX:
412 socket->priv->family = G_SOCKET_FAMILY_UNIX;
413 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
417 socket->priv->family = G_SOCKET_FAMILY_INVALID;
421 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
423 addrlen = sizeof address;
424 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
425 socket->priv->connected = TRUE;
428 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
430 socket->priv->keepalive = !!value;
434 /* Can't read, maybe not supported, assume FALSE */
435 socket->priv->keepalive = FALSE;
441 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
442 socket_io_error_from_errno (errsv),
443 _("creating GSocket from fd: %s"),
444 socket_strerror (errsv));
447 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
449 g_socket (gint domain,
457 fd = socket (domain, type | SOCK_CLOEXEC, protocol);
461 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
462 if (fd < 0 && (errno == EINVAL || errno == EPROTOTYPE))
464 fd = socket (domain, type, protocol);
468 int errsv = get_socket_errno ();
470 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
471 _("Unable to create socket: %s"), socket_strerror (errsv));
480 /* We always want to set close-on-exec to protect users. If you
481 need to so some weird inheritance to exec you can re-enable this
482 using lower level hacks with g_socket_get_fd(). */
483 flags = fcntl (fd, F_GETFD, 0);
485 (flags & FD_CLOEXEC) == 0)
488 fcntl (fd, F_SETFD, flags);
497 g_socket_create_socket (GSocketFamily family,
506 case G_SOCKET_TYPE_STREAM:
507 native_type = SOCK_STREAM;
510 case G_SOCKET_TYPE_DATAGRAM:
511 native_type = SOCK_DGRAM;
514 case G_SOCKET_TYPE_SEQPACKET:
515 native_type = SOCK_SEQPACKET;
519 g_assert_not_reached ();
524 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
525 _("Unable to create socket: %s"), _("Unknown family was specified"));
531 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
532 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
536 return g_socket (family, native_type, protocol, error);
540 g_socket_constructed (GObject *object)
542 GSocket *socket = G_SOCKET (object);
544 if (socket->priv->fd >= 0)
545 /* create socket->priv info from the fd */
546 g_socket_details_from_fd (socket);
549 /* create the fd from socket->priv info */
550 socket->priv->fd = g_socket_create_socket (socket->priv->family,
552 socket->priv->protocol,
553 &socket->priv->construct_error);
555 if (socket->priv->fd != -1)
558 GError *error = NULL;
563 /* Always use native nonblocking sockets, as Windows sets sockets to
564 * nonblocking automatically in certain operations. This way we make
565 * things work the same on all platforms.
568 if (!g_unix_set_fd_nonblocking (socket->priv->fd, TRUE, &error))
570 g_warning ("Error setting socket nonblocking: %s", error->message);
571 g_clear_error (&error);
576 if (ioctlsocket (socket->priv->fd, FIONBIO, &arg) == SOCKET_ERROR)
578 int errsv = get_socket_errno ();
579 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
584 /* See note about SIGPIPE below. */
585 g_socket_set_option (socket, SOL_SOCKET, SO_NOSIGPIPE, TRUE, NULL);
591 g_socket_get_property (GObject *object,
596 GSocket *socket = G_SOCKET (object);
597 GSocketAddress *address;
602 g_value_set_enum (value, socket->priv->family);
606 g_value_set_enum (value, socket->priv->type);
610 g_value_set_enum (value, socket->priv->protocol);
614 g_value_set_int (value, socket->priv->fd);
618 g_value_set_boolean (value, socket->priv->blocking);
621 case PROP_LISTEN_BACKLOG:
622 g_value_set_int (value, socket->priv->listen_backlog);
626 g_value_set_boolean (value, socket->priv->keepalive);
629 case PROP_LOCAL_ADDRESS:
630 address = g_socket_get_local_address (socket, NULL);
631 g_value_take_object (value, address);
634 case PROP_REMOTE_ADDRESS:
635 address = g_socket_get_remote_address (socket, NULL);
636 g_value_take_object (value, address);
640 g_value_set_uint (value, socket->priv->timeout);
644 g_value_set_uint (value, g_socket_get_ttl (socket));
648 g_value_set_boolean (value, g_socket_get_broadcast (socket));
651 case PROP_MULTICAST_LOOPBACK:
652 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
655 case PROP_MULTICAST_TTL:
656 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
660 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
665 g_socket_set_property (GObject *object,
670 GSocket *socket = G_SOCKET (object);
675 socket->priv->family = g_value_get_enum (value);
679 socket->priv->type = g_value_get_enum (value);
683 socket->priv->protocol = g_value_get_enum (value);
687 socket->priv->fd = g_value_get_int (value);
691 g_socket_set_blocking (socket, g_value_get_boolean (value));
694 case PROP_LISTEN_BACKLOG:
695 g_socket_set_listen_backlog (socket, g_value_get_int (value));
699 g_socket_set_keepalive (socket, g_value_get_boolean (value));
703 g_socket_set_timeout (socket, g_value_get_uint (value));
707 g_socket_set_ttl (socket, g_value_get_uint (value));
711 g_socket_set_broadcast (socket, g_value_get_boolean (value));
714 case PROP_MULTICAST_LOOPBACK:
715 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
718 case PROP_MULTICAST_TTL:
719 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
723 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
728 g_socket_finalize (GObject *object)
730 GSocket *socket = G_SOCKET (object);
733 g_clear_error (&socket->priv->construct_error);
735 if (socket->priv->fd != -1 &&
736 !socket->priv->closed)
737 g_socket_close (socket, NULL);
739 if (socket->priv->remote_address)
740 g_object_unref (socket->priv->remote_address);
743 if (socket->priv->event != WSA_INVALID_EVENT)
745 WSACloseEvent (socket->priv->event);
746 socket->priv->event = WSA_INVALID_EVENT;
749 g_assert (socket->priv->requested_conditions == NULL);
750 g_mutex_clear (&socket->priv->win32_source_lock);
753 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
755 if (socket->priv->recv_addr_cache[i].addr)
757 g_object_unref (socket->priv->recv_addr_cache[i].addr);
758 g_free (socket->priv->recv_addr_cache[i].native);
762 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
763 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
767 g_socket_class_init (GSocketClass *klass)
769 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
772 /* There is no portable, thread-safe way to avoid having the process
773 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
774 * forced to simply ignore the signal process-wide.
776 * Even if we ignore it though, gdb will still stop if the app
777 * receives a SIGPIPE, which can be confusing and annoying. So when
778 * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
779 * prevent the signal from occurring at all.
781 signal (SIGPIPE, SIG_IGN);
784 gobject_class->finalize = g_socket_finalize;
785 gobject_class->constructed = g_socket_constructed;
786 gobject_class->set_property = g_socket_set_property;
787 gobject_class->get_property = g_socket_get_property;
789 g_object_class_install_property (gobject_class, PROP_FAMILY,
790 g_param_spec_enum ("family",
792 P_("The sockets address family"),
793 G_TYPE_SOCKET_FAMILY,
794 G_SOCKET_FAMILY_INVALID,
795 G_PARAM_CONSTRUCT_ONLY |
797 G_PARAM_STATIC_STRINGS));
799 g_object_class_install_property (gobject_class, PROP_TYPE,
800 g_param_spec_enum ("type",
802 P_("The sockets type"),
804 G_SOCKET_TYPE_STREAM,
805 G_PARAM_CONSTRUCT_ONLY |
807 G_PARAM_STATIC_STRINGS));
809 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
810 g_param_spec_enum ("protocol",
811 P_("Socket protocol"),
812 P_("The id of the protocol to use, or -1 for unknown"),
813 G_TYPE_SOCKET_PROTOCOL,
814 G_SOCKET_PROTOCOL_UNKNOWN,
815 G_PARAM_CONSTRUCT_ONLY |
817 G_PARAM_STATIC_STRINGS));
819 g_object_class_install_property (gobject_class, PROP_FD,
820 g_param_spec_int ("fd",
821 P_("File descriptor"),
822 P_("The sockets file descriptor"),
826 G_PARAM_CONSTRUCT_ONLY |
828 G_PARAM_STATIC_STRINGS));
830 g_object_class_install_property (gobject_class, PROP_BLOCKING,
831 g_param_spec_boolean ("blocking",
833 P_("Whether or not I/O on this socket is blocking"),
836 G_PARAM_STATIC_STRINGS));
838 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
839 g_param_spec_int ("listen-backlog",
840 P_("Listen backlog"),
841 P_("Outstanding connections in the listen queue"),
846 G_PARAM_STATIC_STRINGS));
848 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
849 g_param_spec_boolean ("keepalive",
850 P_("Keep connection alive"),
851 P_("Keep connection alive by sending periodic pings"),
854 G_PARAM_STATIC_STRINGS));
856 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
857 g_param_spec_object ("local-address",
859 P_("The local address the socket is bound to"),
860 G_TYPE_SOCKET_ADDRESS,
862 G_PARAM_STATIC_STRINGS));
864 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
865 g_param_spec_object ("remote-address",
866 P_("Remote address"),
867 P_("The remote address the socket is connected to"),
868 G_TYPE_SOCKET_ADDRESS,
870 G_PARAM_STATIC_STRINGS));
875 * The timeout in seconds on socket I/O
879 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
880 g_param_spec_uint ("timeout",
882 P_("The timeout in seconds on socket I/O"),
887 G_PARAM_STATIC_STRINGS));
892 * Whether the socket should allow sending to broadcast addresses.
896 g_object_class_install_property (gobject_class, PROP_BROADCAST,
897 g_param_spec_boolean ("broadcast",
899 P_("Whether to allow sending to broadcast addresses"),
902 G_PARAM_STATIC_STRINGS));
907 * Time-to-live for outgoing unicast packets
911 g_object_class_install_property (gobject_class, PROP_TTL,
912 g_param_spec_uint ("ttl",
914 P_("Time-to-live of outgoing unicast packets"),
917 G_PARAM_STATIC_STRINGS));
920 * GSocket:multicast-loopback:
922 * Whether outgoing multicast packets loop back to the local host.
926 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
927 g_param_spec_boolean ("multicast-loopback",
928 P_("Multicast loopback"),
929 P_("Whether outgoing multicast packets loop back to the local host"),
932 G_PARAM_STATIC_STRINGS));
935 * GSocket:multicast-ttl:
937 * Time-to-live out outgoing multicast packets
941 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
942 g_param_spec_uint ("multicast-ttl",
944 P_("Time-to-live of outgoing multicast packets"),
947 G_PARAM_STATIC_STRINGS));
951 g_socket_initable_iface_init (GInitableIface *iface)
953 iface->init = g_socket_initable_init;
957 g_socket_init (GSocket *socket)
959 socket->priv = g_socket_get_instance_private (socket);
961 socket->priv->fd = -1;
962 socket->priv->blocking = TRUE;
963 socket->priv->listen_backlog = 10;
964 socket->priv->construct_error = NULL;
966 socket->priv->event = WSA_INVALID_EVENT;
967 g_mutex_init (&socket->priv->win32_source_lock);
972 g_socket_initable_init (GInitable *initable,
973 GCancellable *cancellable,
978 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
980 socket = G_SOCKET (initable);
982 if (cancellable != NULL)
984 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
985 _("Cancellable initialization not supported"));
989 socket->priv->inited = TRUE;
991 if (socket->priv->construct_error)
994 *error = g_error_copy (socket->priv->construct_error);
1004 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1005 * @type: the socket type to use.
1006 * @protocol: the id of the protocol to use, or 0 for default.
1007 * @error: #GError for error reporting, or %NULL to ignore.
1009 * Creates a new #GSocket with the defined family, type and protocol.
1010 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1011 * for the family and type is used.
1013 * The @protocol is a family and type specific int that specifies what
1014 * kind of protocol to use. #GSocketProtocol lists several common ones.
1015 * Many families only support one protocol, and use 0 for this, others
1016 * support several and using 0 means to use the default protocol for
1017 * the family and type.
1019 * The protocol id is passed directly to the operating
1020 * system, so you can use protocols not listed in #GSocketProtocol if you
1021 * know the protocol number used for it.
1023 * Returns: a #GSocket or %NULL on error.
1024 * Free the returned object with g_object_unref().
1029 g_socket_new (GSocketFamily family,
1031 GSocketProtocol protocol,
1034 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1038 "protocol", protocol,
1043 * g_socket_new_from_fd:
1044 * @fd: a native socket file descriptor.
1045 * @error: #GError for error reporting, or %NULL to ignore.
1047 * Creates a new #GSocket from a native file descriptor
1048 * or winsock SOCKET handle.
1050 * This reads all the settings from the file descriptor so that
1051 * all properties should work. Note that the file descriptor
1052 * will be set to non-blocking mode, independent on the blocking
1053 * mode of the #GSocket.
1055 * Returns: a #GSocket or %NULL on error.
1056 * Free the returned object with g_object_unref().
1061 g_socket_new_from_fd (gint fd,
1064 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1071 * g_socket_set_blocking:
1072 * @socket: a #GSocket.
1073 * @blocking: Whether to use blocking I/O or not.
1075 * Sets the blocking mode of the socket. In blocking mode
1076 * all operations block until they succeed or there is an error. In
1077 * non-blocking mode all functions return results immediately or
1078 * with a %G_IO_ERROR_WOULD_BLOCK error.
1080 * All sockets are created in blocking mode. However, note that the
1081 * platform level socket is always non-blocking, and blocking mode
1082 * is a GSocket level feature.
1087 g_socket_set_blocking (GSocket *socket,
1090 g_return_if_fail (G_IS_SOCKET (socket));
1092 blocking = !!blocking;
1094 if (socket->priv->blocking == blocking)
1097 socket->priv->blocking = blocking;
1098 g_object_notify (G_OBJECT (socket), "blocking");
1102 * g_socket_get_blocking:
1103 * @socket: a #GSocket.
1105 * Gets the blocking mode of the socket. For details on blocking I/O,
1106 * see g_socket_set_blocking().
1108 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1113 g_socket_get_blocking (GSocket *socket)
1115 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1117 return socket->priv->blocking;
1121 * g_socket_set_keepalive:
1122 * @socket: a #GSocket.
1123 * @keepalive: Value for the keepalive flag
1125 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1126 * this flag is set on a socket, the system will attempt to verify that the
1127 * remote socket endpoint is still present if a sufficiently long period of
1128 * time passes with no data being exchanged. If the system is unable to
1129 * verify the presence of the remote endpoint, it will automatically close
1132 * This option is only functional on certain kinds of sockets. (Notably,
1133 * %G_SOCKET_PROTOCOL_TCP sockets.)
1135 * The exact time between pings is system- and protocol-dependent, but will
1136 * normally be at least two hours. Most commonly, you would set this flag
1137 * on a server socket if you want to allow clients to remain idle for long
1138 * periods of time, but also want to ensure that connections are eventually
1139 * garbage-collected if clients crash or become unreachable.
1144 g_socket_set_keepalive (GSocket *socket,
1147 GError *error = NULL;
1149 g_return_if_fail (G_IS_SOCKET (socket));
1151 keepalive = !!keepalive;
1152 if (socket->priv->keepalive == keepalive)
1155 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1158 g_warning ("error setting keepalive: %s", error->message);
1159 g_error_free (error);
1163 socket->priv->keepalive = keepalive;
1164 g_object_notify (G_OBJECT (socket), "keepalive");
1168 * g_socket_get_keepalive:
1169 * @socket: a #GSocket.
1171 * Gets the keepalive mode of the socket. For details on this,
1172 * see g_socket_set_keepalive().
1174 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1179 g_socket_get_keepalive (GSocket *socket)
1181 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1183 return socket->priv->keepalive;
1187 * g_socket_get_listen_backlog:
1188 * @socket: a #GSocket.
1190 * Gets the listen backlog setting of the socket. For details on this,
1191 * see g_socket_set_listen_backlog().
1193 * Returns: the maximum number of pending connections.
1198 g_socket_get_listen_backlog (GSocket *socket)
1200 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1202 return socket->priv->listen_backlog;
1206 * g_socket_set_listen_backlog:
1207 * @socket: a #GSocket.
1208 * @backlog: the maximum number of pending connections.
1210 * Sets the maximum number of outstanding connections allowed
1211 * when listening on this socket. If more clients than this are
1212 * connecting to the socket and the application is not handling them
1213 * on time then the new connections will be refused.
1215 * Note that this must be called before g_socket_listen() and has no
1216 * effect if called after that.
1221 g_socket_set_listen_backlog (GSocket *socket,
1224 g_return_if_fail (G_IS_SOCKET (socket));
1225 g_return_if_fail (!socket->priv->listening);
1227 if (backlog != socket->priv->listen_backlog)
1229 socket->priv->listen_backlog = backlog;
1230 g_object_notify (G_OBJECT (socket), "listen-backlog");
1235 * g_socket_get_timeout:
1236 * @socket: a #GSocket.
1238 * Gets the timeout setting of the socket. For details on this, see
1239 * g_socket_set_timeout().
1241 * Returns: the timeout in seconds
1246 g_socket_get_timeout (GSocket *socket)
1248 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1250 return socket->priv->timeout;
1254 * g_socket_set_timeout:
1255 * @socket: a #GSocket.
1256 * @timeout: the timeout for @socket, in seconds, or 0 for none
1258 * Sets the time in seconds after which I/O operations on @socket will
1259 * time out if they have not yet completed.
1261 * On a blocking socket, this means that any blocking #GSocket
1262 * operation will time out after @timeout seconds of inactivity,
1263 * returning %G_IO_ERROR_TIMED_OUT.
1265 * On a non-blocking socket, calls to g_socket_condition_wait() will
1266 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1267 * created with g_socket_create_source() will trigger after
1268 * @timeout seconds of inactivity, with the requested condition
1269 * set, at which point calling g_socket_receive(), g_socket_send(),
1270 * g_socket_check_connect_result(), etc, will fail with
1271 * %G_IO_ERROR_TIMED_OUT.
1273 * If @timeout is 0 (the default), operations will never time out
1276 * Note that if an I/O operation is interrupted by a signal, this may
1277 * cause the timeout to be reset.
1282 g_socket_set_timeout (GSocket *socket,
1285 g_return_if_fail (G_IS_SOCKET (socket));
1287 if (timeout != socket->priv->timeout)
1289 socket->priv->timeout = timeout;
1290 g_object_notify (G_OBJECT (socket), "timeout");
1296 * @socket: a #GSocket.
1298 * Gets the unicast time-to-live setting on @socket; see
1299 * g_socket_set_ttl() for more details.
1301 * Returns: the time-to-live setting on @socket
1306 g_socket_get_ttl (GSocket *socket)
1308 GError *error = NULL;
1311 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1313 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1315 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1318 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1320 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1324 g_return_val_if_reached (0);
1328 g_warning ("error getting unicast ttl: %s", error->message);
1329 g_error_free (error);
1338 * @socket: a #GSocket.
1339 * @ttl: the time-to-live value for all unicast packets on @socket
1341 * Sets the time-to-live for outgoing unicast packets on @socket.
1342 * By default the platform-specific default value is used.
1347 g_socket_set_ttl (GSocket *socket,
1350 GError *error = NULL;
1352 g_return_if_fail (G_IS_SOCKET (socket));
1354 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1356 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1359 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1361 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1363 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1367 g_return_if_reached ();
1371 g_warning ("error setting unicast ttl: %s", error->message);
1372 g_error_free (error);
1376 g_object_notify (G_OBJECT (socket), "ttl");
1380 * g_socket_get_broadcast:
1381 * @socket: a #GSocket.
1383 * Gets the broadcast setting on @socket; if %TRUE,
1384 * it is possible to send packets to broadcast
1387 * Returns: the broadcast setting on @socket
1392 g_socket_get_broadcast (GSocket *socket)
1394 GError *error = NULL;
1397 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1399 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1402 g_warning ("error getting broadcast: %s", error->message);
1403 g_error_free (error);
1411 * g_socket_set_broadcast:
1412 * @socket: a #GSocket.
1413 * @broadcast: whether @socket should allow sending to broadcast
1416 * Sets whether @socket should allow sending to broadcast addresses.
1417 * This is %FALSE by default.
1422 g_socket_set_broadcast (GSocket *socket,
1425 GError *error = NULL;
1427 g_return_if_fail (G_IS_SOCKET (socket));
1429 broadcast = !!broadcast;
1431 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1434 g_warning ("error setting broadcast: %s", error->message);
1435 g_error_free (error);
1439 g_object_notify (G_OBJECT (socket), "broadcast");
1443 * g_socket_get_multicast_loopback:
1444 * @socket: a #GSocket.
1446 * Gets the multicast loopback setting on @socket; if %TRUE (the
1447 * default), outgoing multicast packets will be looped back to
1448 * multicast listeners on the same host.
1450 * Returns: the multicast loopback setting on @socket
1455 g_socket_get_multicast_loopback (GSocket *socket)
1457 GError *error = NULL;
1460 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1462 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1464 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1467 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1469 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1473 g_return_val_if_reached (FALSE);
1477 g_warning ("error getting multicast loopback: %s", error->message);
1478 g_error_free (error);
1486 * g_socket_set_multicast_loopback:
1487 * @socket: a #GSocket.
1488 * @loopback: whether @socket should receive messages sent to its
1489 * multicast groups from the local host
1491 * Sets whether outgoing multicast packets will be received by sockets
1492 * listening on that multicast address on the same host. This is %TRUE
1498 g_socket_set_multicast_loopback (GSocket *socket,
1501 GError *error = NULL;
1503 g_return_if_fail (G_IS_SOCKET (socket));
1505 loopback = !!loopback;
1507 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1509 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1512 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1514 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1516 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1520 g_return_if_reached ();
1524 g_warning ("error setting multicast loopback: %s", error->message);
1525 g_error_free (error);
1529 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1533 * g_socket_get_multicast_ttl:
1534 * @socket: a #GSocket.
1536 * Gets the multicast time-to-live setting on @socket; see
1537 * g_socket_set_multicast_ttl() for more details.
1539 * Returns: the multicast time-to-live setting on @socket
1544 g_socket_get_multicast_ttl (GSocket *socket)
1546 GError *error = NULL;
1549 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1551 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1553 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1556 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1558 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1562 g_return_val_if_reached (FALSE);
1566 g_warning ("error getting multicast ttl: %s", error->message);
1567 g_error_free (error);
1575 * g_socket_set_multicast_ttl:
1576 * @socket: a #GSocket.
1577 * @ttl: the time-to-live value for all multicast datagrams on @socket
1579 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1580 * By default, this is 1, meaning that multicast packets will not leave
1581 * the local network.
1586 g_socket_set_multicast_ttl (GSocket *socket,
1589 GError *error = NULL;
1591 g_return_if_fail (G_IS_SOCKET (socket));
1593 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1595 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1598 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1600 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1602 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1606 g_return_if_reached ();
1610 g_warning ("error setting multicast ttl: %s", error->message);
1611 g_error_free (error);
1615 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1619 * g_socket_get_family:
1620 * @socket: a #GSocket.
1622 * Gets the socket family of the socket.
1624 * Returns: a #GSocketFamily
1629 g_socket_get_family (GSocket *socket)
1631 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1633 return socket->priv->family;
1637 * g_socket_get_socket_type:
1638 * @socket: a #GSocket.
1640 * Gets the socket type of the socket.
1642 * Returns: a #GSocketType
1647 g_socket_get_socket_type (GSocket *socket)
1649 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1651 return socket->priv->type;
1655 * g_socket_get_protocol:
1656 * @socket: a #GSocket.
1658 * Gets the socket protocol id the socket was created with.
1659 * In case the protocol is unknown, -1 is returned.
1661 * Returns: a protocol id, or -1 if unknown
1666 g_socket_get_protocol (GSocket *socket)
1668 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1670 return socket->priv->protocol;
1675 * @socket: a #GSocket.
1677 * Returns the underlying OS socket object. On unix this
1678 * is a socket file descriptor, and on Windows this is
1679 * a Winsock2 SOCKET handle. This may be useful for
1680 * doing platform specific or otherwise unusual operations
1683 * Returns: the file descriptor of the socket.
1688 g_socket_get_fd (GSocket *socket)
1690 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1692 return socket->priv->fd;
1696 * g_socket_get_local_address:
1697 * @socket: a #GSocket.
1698 * @error: #GError for error reporting, or %NULL to ignore.
1700 * Try to get the local address of a bound socket. This is only
1701 * useful if the socket has been bound to a local address,
1702 * either explicitly or implicitly when connecting.
1704 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1705 * Free the returned object with g_object_unref().
1710 g_socket_get_local_address (GSocket *socket,
1713 struct sockaddr_storage buffer;
1714 guint len = sizeof (buffer);
1716 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1718 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1720 int errsv = get_socket_errno ();
1721 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1722 _("could not get local address: %s"), socket_strerror (errsv));
1726 return g_socket_address_new_from_native (&buffer, len);
1730 * g_socket_get_remote_address:
1731 * @socket: a #GSocket.
1732 * @error: #GError for error reporting, or %NULL to ignore.
1734 * Try to get the remove address of a connected socket. This is only
1735 * useful for connection oriented sockets that have been connected.
1737 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1738 * Free the returned object with g_object_unref().
1743 g_socket_get_remote_address (GSocket *socket,
1746 struct sockaddr_storage buffer;
1747 guint len = sizeof (buffer);
1749 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1751 if (socket->priv->connect_pending)
1753 if (!g_socket_check_connect_result (socket, error))
1756 socket->priv->connect_pending = FALSE;
1759 if (!socket->priv->remote_address)
1761 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1763 int errsv = get_socket_errno ();
1764 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1765 _("could not get remote address: %s"), socket_strerror (errsv));
1769 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1772 return g_object_ref (socket->priv->remote_address);
1776 * g_socket_is_connected:
1777 * @socket: a #GSocket.
1779 * Check whether the socket is connected. This is only useful for
1780 * connection-oriented sockets.
1782 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1787 g_socket_is_connected (GSocket *socket)
1789 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1791 return socket->priv->connected;
1796 * @socket: a #GSocket.
1797 * @error: #GError for error reporting, or %NULL to ignore.
1799 * Marks the socket as a server socket, i.e. a socket that is used
1800 * to accept incoming requests using g_socket_accept().
1802 * Before calling this the socket must be bound to a local address using
1805 * To set the maximum amount of outstanding clients, use
1806 * g_socket_set_listen_backlog().
1808 * Returns: %TRUE on success, %FALSE on error.
1813 g_socket_listen (GSocket *socket,
1816 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1818 if (!check_socket (socket, error))
1821 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1823 int errsv = get_socket_errno ();
1825 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1826 _("could not listen: %s"), socket_strerror (errsv));
1830 socket->priv->listening = TRUE;
1837 * @socket: a #GSocket.
1838 * @address: a #GSocketAddress specifying the local address.
1839 * @allow_reuse: whether to allow reusing this address
1840 * @error: #GError for error reporting, or %NULL to ignore.
1842 * When a socket is created it is attached to an address family, but it
1843 * doesn't have an address in this family. g_socket_bind() assigns the
1844 * address (sometimes called name) of the socket.
1846 * It is generally required to bind to a local address before you can
1847 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1848 * In certain situations, you may also want to bind a socket that will be
1849 * used to initiate connections, though this is not normally required.
1851 * If @socket is a TCP socket, then @allow_reuse controls the setting
1852 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
1853 * server sockets (sockets that you will eventually call
1854 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
1855 * set this flag on a server socket may cause g_socket_bind() to return
1856 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
1857 * immediately restarted.)
1859 * If @socket is a UDP socket, then @allow_reuse determines whether or
1860 * not other UDP sockets can be bound to the same address at the same
1861 * time. In particular, you can have several UDP sockets bound to the
1862 * same address, and they will all receive all of the multicast and
1863 * broadcast packets sent to that address. (The behavior of unicast
1864 * UDP packets to an address with multiple listeners is not defined.)
1866 * Returns: %TRUE on success, %FALSE on error.
1871 g_socket_bind (GSocket *socket,
1872 GSocketAddress *address,
1873 gboolean reuse_address,
1876 struct sockaddr_storage addr;
1877 gboolean so_reuseaddr;
1879 gboolean so_reuseport;
1882 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1884 if (!check_socket (socket, error))
1887 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1890 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
1891 * sockets, but has nasty side effects we don't want for TCP
1894 * On other platforms, we set SO_REUSEPORT, if it exists, for
1895 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
1896 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
1897 * the desired semantics on UDP (as it does on Linux, although
1898 * Linux has SO_REUSEPORT too as of 3.9).
1902 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1904 so_reuseaddr = !!reuse_address;
1908 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1911 /* Ignore errors here, the only likely error is "not supported", and
1912 * this is a "best effort" thing mainly.
1914 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
1916 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
1919 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1920 g_socket_address_get_native_size (address)) < 0)
1922 int errsv = get_socket_errno ();
1924 G_IO_ERROR, socket_io_error_from_errno (errsv),
1925 _("Error binding to address: %s"), socket_strerror (errsv));
1932 #if !defined(HAVE_IF_NAMETOINDEX) && defined(G_OS_WIN32)
1934 if_nametoindex (const gchar *iface)
1936 PIP_ADAPTER_ADDRESSES addresses = NULL, p;
1937 gulong addresses_len = 0;
1941 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, NULL, &addresses_len);
1942 if (res != NO_ERROR && res != ERROR_BUFFER_OVERFLOW)
1944 if (res == ERROR_NO_DATA)
1951 addresses = g_malloc (addresses_len);
1952 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, addresses, &addresses_len);
1954 if (res != NO_ERROR)
1957 if (res == ERROR_NO_DATA)
1967 if (strcmp (p->AdapterName, iface) == 0)
1983 #define HAVE_IF_NAMETOINDEX 1
1987 g_socket_multicast_group_operation (GSocket *socket,
1988 GInetAddress *group,
1989 gboolean source_specific,
1991 gboolean join_group,
1994 const guint8 *native_addr;
1995 gint optname, result;
1997 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1998 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
1999 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2001 if (!check_socket (socket, error))
2004 native_addr = g_inet_address_to_bytes (group);
2005 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2007 #ifdef HAVE_IP_MREQN
2008 struct ip_mreqn mc_req;
2010 struct ip_mreq mc_req;
2013 memset (&mc_req, 0, sizeof (mc_req));
2014 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2016 #ifdef HAVE_IP_MREQN
2018 mc_req.imr_ifindex = if_nametoindex (iface);
2020 mc_req.imr_ifindex = 0; /* Pick any. */
2021 #elif defined(G_OS_WIN32)
2023 mc_req.imr_interface.s_addr = g_htonl (if_nametoindex (iface));
2025 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2027 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2030 if (source_specific)
2032 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2033 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2035 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2037 _("Error joining multicast group: %s") :
2038 _("Error leaving multicast group: %s"),
2039 _("No support for source-specific multicast"));
2044 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2045 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2046 &mc_req, sizeof (mc_req));
2048 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2050 struct ipv6_mreq mc_req_ipv6;
2052 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2053 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2054 #ifdef HAVE_IF_NAMETOINDEX
2056 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2059 mc_req_ipv6.ipv6mr_interface = 0;
2061 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2062 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2063 &mc_req_ipv6, sizeof (mc_req_ipv6));
2066 g_return_val_if_reached (FALSE);
2070 int errsv = get_socket_errno ();
2072 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2074 _("Error joining multicast group: %s") :
2075 _("Error leaving multicast group: %s"),
2076 socket_strerror (errsv));
2084 * g_socket_join_multicast_group:
2085 * @socket: a #GSocket.
2086 * @group: a #GInetAddress specifying the group address to join.
2087 * @iface: (allow-none): Name of the interface to use, or %NULL
2088 * @source_specific: %TRUE if source-specific multicast should be used
2089 * @error: #GError for error reporting, or %NULL to ignore.
2091 * Registers @socket to receive multicast messages sent to @group.
2092 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2093 * been bound to an appropriate interface and port with
2096 * If @iface is %NULL, the system will automatically pick an interface
2097 * to bind to based on @group.
2099 * If @source_specific is %TRUE, source-specific multicast as defined
2100 * in RFC 4604 is used. Note that on older platforms this may fail
2101 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2103 * Returns: %TRUE on success, %FALSE on error.
2108 g_socket_join_multicast_group (GSocket *socket,
2109 GInetAddress *group,
2110 gboolean source_specific,
2114 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2118 * g_socket_leave_multicast_group:
2119 * @socket: a #GSocket.
2120 * @group: a #GInetAddress specifying the group address to leave.
2121 * @iface: (allow-none): Interface used
2122 * @source_specific: %TRUE if source-specific multicast was used
2123 * @error: #GError for error reporting, or %NULL to ignore.
2125 * Removes @socket from the multicast group defined by @group, @iface,
2126 * and @source_specific (which must all have the same values they had
2127 * when you joined the group).
2129 * @socket remains bound to its address and port, and can still receive
2130 * unicast messages after calling this.
2132 * Returns: %TRUE on success, %FALSE on error.
2137 g_socket_leave_multicast_group (GSocket *socket,
2138 GInetAddress *group,
2139 gboolean source_specific,
2143 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2147 * g_socket_speaks_ipv4:
2148 * @socket: a #GSocket
2150 * Checks if a socket is capable of speaking IPv4.
2152 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2153 * and under some combinations of circumstances IPv6 sockets are also
2154 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2157 * No other types of sockets are currently considered as being capable
2160 * Returns: %TRUE if this socket can be used with IPv4.
2165 g_socket_speaks_ipv4 (GSocket *socket)
2167 switch (socket->priv->family)
2169 case G_SOCKET_FAMILY_IPV4:
2172 case G_SOCKET_FAMILY_IPV6:
2173 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2177 if (!g_socket_get_option (socket,
2178 IPPROTO_IPV6, IPV6_V6ONLY,
2195 * @socket: a #GSocket.
2196 * @cancellable: (allow-none): a %GCancellable or %NULL
2197 * @error: #GError for error reporting, or %NULL to ignore.
2199 * Accept incoming connections on a connection-based socket. This removes
2200 * the first outstanding connection request from the listening socket and
2201 * creates a #GSocket object for it.
2203 * The @socket must be bound to a local address with g_socket_bind() and
2204 * must be listening for incoming connections (g_socket_listen()).
2206 * If there are no outstanding connections then the operation will block
2207 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2208 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2210 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2211 * Free the returned object with g_object_unref().
2216 g_socket_accept (GSocket *socket,
2217 GCancellable *cancellable,
2220 GSocket *new_socket;
2223 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2225 if (!check_socket (socket, error))
2228 if (!check_timeout (socket, error))
2233 if (socket->priv->blocking &&
2234 !g_socket_condition_wait (socket,
2235 G_IO_IN, cancellable, error))
2238 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2240 int errsv = get_socket_errno ();
2242 win32_unset_event_mask (socket, FD_ACCEPT);
2247 if (socket->priv->blocking)
2249 #ifdef WSAEWOULDBLOCK
2250 if (errsv == WSAEWOULDBLOCK)
2253 if (errsv == EWOULDBLOCK ||
2259 g_set_error (error, G_IO_ERROR,
2260 socket_io_error_from_errno (errsv),
2261 _("Error accepting connection: %s"), socket_strerror (errsv));
2267 win32_unset_event_mask (socket, FD_ACCEPT);
2271 /* The socket inherits the accepting sockets event mask and even object,
2272 we need to remove that */
2273 WSAEventSelect (ret, NULL, 0);
2279 /* We always want to set close-on-exec to protect users. If you
2280 need to so some weird inheritance to exec you can re-enable this
2281 using lower level hacks with g_socket_get_fd(). */
2282 flags = fcntl (ret, F_GETFD, 0);
2284 (flags & FD_CLOEXEC) == 0)
2286 flags |= FD_CLOEXEC;
2287 fcntl (ret, F_SETFD, flags);
2292 new_socket = g_socket_new_from_fd (ret, error);
2293 if (new_socket == NULL)
2302 new_socket->priv->protocol = socket->priv->protocol;
2309 * @socket: a #GSocket.
2310 * @address: a #GSocketAddress specifying the remote address.
2311 * @cancellable: (allow-none): a %GCancellable or %NULL
2312 * @error: #GError for error reporting, or %NULL to ignore.
2314 * Connect the socket to the specified remote address.
2316 * For connection oriented socket this generally means we attempt to make
2317 * a connection to the @address. For a connection-less socket it sets
2318 * the default address for g_socket_send() and discards all incoming datagrams
2319 * from other sources.
2321 * Generally connection oriented sockets can only connect once, but
2322 * connection-less sockets can connect multiple times to change the
2325 * If the connect call needs to do network I/O it will block, unless
2326 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2327 * and the user can be notified of the connection finishing by waiting
2328 * for the G_IO_OUT condition. The result of the connection must then be
2329 * checked with g_socket_check_connect_result().
2331 * Returns: %TRUE if connected, %FALSE on error.
2336 g_socket_connect (GSocket *socket,
2337 GSocketAddress *address,
2338 GCancellable *cancellable,
2341 struct sockaddr_storage buffer;
2343 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2345 if (!check_socket (socket, error))
2348 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2351 if (socket->priv->remote_address)
2352 g_object_unref (socket->priv->remote_address);
2353 socket->priv->remote_address = g_object_ref (address);
2357 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2358 g_socket_address_get_native_size (address)) < 0)
2360 int errsv = get_socket_errno ();
2366 if (errsv == EINPROGRESS)
2368 if (errsv == WSAEWOULDBLOCK)
2371 if (socket->priv->blocking)
2373 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2375 if (g_socket_check_connect_result (socket, error))
2381 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2382 _("Connection in progress"));
2383 socket->priv->connect_pending = TRUE;
2387 g_set_error_literal (error, G_IO_ERROR,
2388 socket_io_error_from_errno (errsv),
2389 socket_strerror (errsv));
2396 win32_unset_event_mask (socket, FD_CONNECT);
2398 socket->priv->connected = TRUE;
2404 * g_socket_check_connect_result:
2405 * @socket: a #GSocket
2406 * @error: #GError for error reporting, or %NULL to ignore.
2408 * Checks and resets the pending connect error for the socket.
2409 * This is used to check for errors when g_socket_connect() is
2410 * used in non-blocking mode.
2412 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2417 g_socket_check_connect_result (GSocket *socket,
2422 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2424 if (!check_socket (socket, error))
2427 if (!check_timeout (socket, error))
2430 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
2432 g_prefix_error (error, _("Unable to get pending error: "));
2438 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2439 socket_strerror (value));
2440 if (socket->priv->remote_address)
2442 g_object_unref (socket->priv->remote_address);
2443 socket->priv->remote_address = NULL;
2448 socket->priv->connected = TRUE;
2453 * g_socket_get_available_bytes:
2454 * @socket: a #GSocket
2456 * Get the amount of data pending in the OS input buffer.
2458 * If @socket is a UDP or SCTP socket, this will return the size of
2459 * just the next packet, even if additional packets are buffered after
2462 * Note that on Windows, this function is rather inefficient in the
2463 * UDP case, and so if you know any plausible upper bound on the size
2464 * of the incoming packet, it is better to just do a
2465 * g_socket_receive() with a buffer of that size, rather than calling
2466 * g_socket_get_available_bytes() first and then doing a receive of
2467 * exactly the right size.
2469 * Returns: the number of bytes that can be read from the socket
2470 * without blocking or truncating, or -1 on error.
2475 g_socket_get_available_bytes (GSocket *socket)
2478 const gint bufsize = 64 * 1024;
2479 static guchar *buf = NULL;
2485 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2487 #if defined (SO_NREAD)
2488 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
2490 #elif !defined (G_OS_WIN32)
2491 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2494 if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
2496 if (G_UNLIKELY (g_once_init_enter (&buf)))
2497 g_once_init_leave (&buf, g_malloc (bufsize));
2499 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
2500 if (avail == -1 && get_socket_errno () == WSAEWOULDBLOCK)
2505 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
2515 * @socket: a #GSocket
2516 * @buffer: (array length=size) (element-type guint8): a buffer to
2517 * read data into (which should be at least @size bytes long).
2518 * @size: the number of bytes you want to read from the socket
2519 * @cancellable: (allow-none): a %GCancellable or %NULL
2520 * @error: #GError for error reporting, or %NULL to ignore.
2522 * Receive data (up to @size bytes) from a socket. This is mainly used by
2523 * connection-oriented sockets; it is identical to g_socket_receive_from()
2524 * with @address set to %NULL.
2526 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2527 * g_socket_receive() will always read either 0 or 1 complete messages from
2528 * the socket. If the received message is too large to fit in @buffer, then
2529 * the data beyond @size bytes will be discarded, without any explicit
2530 * indication that this has occurred.
2532 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2533 * number of bytes, up to @size. If more than @size bytes have been
2534 * received, the additional data will be returned in future calls to
2535 * g_socket_receive().
2537 * If the socket is in blocking mode the call will block until there
2538 * is some data to receive, the connection is closed, or there is an
2539 * error. If there is no data available and the socket is in
2540 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2541 * returned. To be notified when data is available, wait for the
2542 * %G_IO_IN condition.
2544 * On error -1 is returned and @error is set accordingly.
2546 * Returns: Number of bytes read, or 0 if the connection was closed by
2547 * the peer, or -1 on error
2552 g_socket_receive (GSocket *socket,
2555 GCancellable *cancellable,
2558 return g_socket_receive_with_blocking (socket, buffer, size,
2559 socket->priv->blocking,
2560 cancellable, error);
2564 * g_socket_receive_with_blocking:
2565 * @socket: a #GSocket
2566 * @buffer: (array length=size) (element-type guint8): a buffer to
2567 * read data into (which should be at least @size bytes long).
2568 * @size: the number of bytes you want to read from the socket
2569 * @blocking: whether to do blocking or non-blocking I/O
2570 * @cancellable: (allow-none): a %GCancellable or %NULL
2571 * @error: #GError for error reporting, or %NULL to ignore.
2573 * This behaves exactly the same as g_socket_receive(), except that
2574 * the choice of blocking or non-blocking behavior is determined by
2575 * the @blocking argument rather than by @socket's properties.
2577 * Returns: Number of bytes read, or 0 if the connection was closed by
2578 * the peer, or -1 on error
2583 g_socket_receive_with_blocking (GSocket *socket,
2587 GCancellable *cancellable,
2592 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2594 if (!check_socket (socket, error))
2597 if (!check_timeout (socket, error))
2600 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2606 !g_socket_condition_wait (socket,
2607 G_IO_IN, cancellable, error))
2610 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2612 int errsv = get_socket_errno ();
2619 #ifdef WSAEWOULDBLOCK
2620 if (errsv == WSAEWOULDBLOCK)
2623 if (errsv == EWOULDBLOCK ||
2629 win32_unset_event_mask (socket, FD_READ);
2631 g_set_error (error, G_IO_ERROR,
2632 socket_io_error_from_errno (errsv),
2633 _("Error receiving data: %s"), socket_strerror (errsv));
2637 win32_unset_event_mask (socket, FD_READ);
2646 * g_socket_receive_from:
2647 * @socket: a #GSocket
2648 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2650 * @buffer: (array length=size) (element-type guint8): a buffer to
2651 * read data into (which should be at least @size bytes long).
2652 * @size: the number of bytes you want to read from the socket
2653 * @cancellable: (allow-none): a %GCancellable or %NULL
2654 * @error: #GError for error reporting, or %NULL to ignore.
2656 * Receive data (up to @size bytes) from a socket.
2658 * If @address is non-%NULL then @address will be set equal to the
2659 * source address of the received packet.
2660 * @address is owned by the caller.
2662 * See g_socket_receive() for additional information.
2664 * Returns: Number of bytes read, or 0 if the connection was closed by
2665 * the peer, or -1 on error
2670 g_socket_receive_from (GSocket *socket,
2671 GSocketAddress **address,
2674 GCancellable *cancellable,
2682 return g_socket_receive_message (socket,
2690 /* See the comment about SIGPIPE above. */
2692 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2694 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2699 * @socket: a #GSocket
2700 * @buffer: (array length=size) (element-type guint8): the buffer
2701 * containing the data to send.
2702 * @size: the number of bytes to send
2703 * @cancellable: (allow-none): a %GCancellable or %NULL
2704 * @error: #GError for error reporting, or %NULL to ignore.
2706 * Tries to send @size bytes from @buffer on the socket. This is
2707 * mainly used by connection-oriented sockets; it is identical to
2708 * g_socket_send_to() with @address set to %NULL.
2710 * If the socket is in blocking mode the call will block until there is
2711 * space for the data in the socket queue. If there is no space available
2712 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2713 * will be returned. To be notified when space is available, wait for the
2714 * %G_IO_OUT condition. Note though that you may still receive
2715 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2716 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2717 * very common due to the way the underlying APIs work.)
2719 * On error -1 is returned and @error is set accordingly.
2721 * Returns: Number of bytes written (which may be less than @size), or -1
2727 g_socket_send (GSocket *socket,
2728 const gchar *buffer,
2730 GCancellable *cancellable,
2733 return g_socket_send_with_blocking (socket, buffer, size,
2734 socket->priv->blocking,
2735 cancellable, error);
2739 * g_socket_send_with_blocking:
2740 * @socket: a #GSocket
2741 * @buffer: (array length=size) (element-type guint8): the buffer
2742 * containing the data to send.
2743 * @size: the number of bytes to send
2744 * @blocking: whether to do blocking or non-blocking I/O
2745 * @cancellable: (allow-none): a %GCancellable or %NULL
2746 * @error: #GError for error reporting, or %NULL to ignore.
2748 * This behaves exactly the same as g_socket_send(), except that
2749 * the choice of blocking or non-blocking behavior is determined by
2750 * the @blocking argument rather than by @socket's properties.
2752 * Returns: Number of bytes written (which may be less than @size), or -1
2758 g_socket_send_with_blocking (GSocket *socket,
2759 const gchar *buffer,
2762 GCancellable *cancellable,
2767 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2769 if (!check_socket (socket, error))
2772 if (!check_timeout (socket, error))
2775 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2781 !g_socket_condition_wait (socket,
2782 G_IO_OUT, cancellable, error))
2785 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2787 int errsv = get_socket_errno ();
2792 #ifdef WSAEWOULDBLOCK
2793 if (errsv == WSAEWOULDBLOCK)
2794 win32_unset_event_mask (socket, FD_WRITE);
2799 #ifdef WSAEWOULDBLOCK
2800 if (errsv == WSAEWOULDBLOCK)
2803 if (errsv == EWOULDBLOCK ||
2809 g_set_error (error, G_IO_ERROR,
2810 socket_io_error_from_errno (errsv),
2811 _("Error sending data: %s"), socket_strerror (errsv));
2822 * @socket: a #GSocket
2823 * @address: (allow-none): a #GSocketAddress, or %NULL
2824 * @buffer: (array length=size) (element-type guint8): the buffer
2825 * containing the data to send.
2826 * @size: the number of bytes to send
2827 * @cancellable: (allow-none): a %GCancellable or %NULL
2828 * @error: #GError for error reporting, or %NULL to ignore.
2830 * Tries to send @size bytes from @buffer to @address. If @address is
2831 * %NULL then the message is sent to the default receiver (set by
2832 * g_socket_connect()).
2834 * See g_socket_send() for additional information.
2836 * Returns: Number of bytes written (which may be less than @size), or -1
2842 g_socket_send_to (GSocket *socket,
2843 GSocketAddress *address,
2844 const gchar *buffer,
2846 GCancellable *cancellable,
2854 return g_socket_send_message (socket,
2864 * g_socket_shutdown:
2865 * @socket: a #GSocket
2866 * @shutdown_read: whether to shut down the read side
2867 * @shutdown_write: whether to shut down the write side
2868 * @error: #GError for error reporting, or %NULL to ignore.
2870 * Shut down part of a full-duplex connection.
2872 * If @shutdown_read is %TRUE then the receiving side of the connection
2873 * is shut down, and further reading is disallowed.
2875 * If @shutdown_write is %TRUE then the sending side of the connection
2876 * is shut down, and further writing is disallowed.
2878 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2880 * One example where this is used is graceful disconnect for TCP connections
2881 * where you close the sending side, then wait for the other side to close
2882 * the connection, thus ensuring that the other side saw all sent data.
2884 * Returns: %TRUE on success, %FALSE on error
2889 g_socket_shutdown (GSocket *socket,
2890 gboolean shutdown_read,
2891 gboolean shutdown_write,
2896 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2898 if (!check_socket (socket, error))
2902 if (!shutdown_read && !shutdown_write)
2906 if (shutdown_read && shutdown_write)
2908 else if (shutdown_read)
2913 if (shutdown_read && shutdown_write)
2915 else if (shutdown_read)
2921 if (shutdown (socket->priv->fd, how) != 0)
2923 int errsv = get_socket_errno ();
2924 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2925 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2929 if (shutdown_read && shutdown_write)
2930 socket->priv->connected = FALSE;
2937 * @socket: a #GSocket
2938 * @error: #GError for error reporting, or %NULL to ignore.
2940 * Closes the socket, shutting down any active connection.
2942 * Closing a socket does not wait for all outstanding I/O operations
2943 * to finish, so the caller should not rely on them to be guaranteed
2944 * to complete even if the close returns with no error.
2946 * Once the socket is closed, all other operations will return
2947 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2950 * Sockets will be automatically closed when the last reference
2951 * is dropped, but you might want to call this function to make sure
2952 * resources are released as early as possible.
2954 * Beware that due to the way that TCP works, it is possible for
2955 * recently-sent data to be lost if either you close a socket while the
2956 * %G_IO_IN condition is set, or else if the remote connection tries to
2957 * send something to you after you close the socket but before it has
2958 * finished reading all of the data you sent. There is no easy generic
2959 * way to avoid this problem; the easiest fix is to design the network
2960 * protocol such that the client will never send data "out of turn".
2961 * Another solution is for the server to half-close the connection by
2962 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2963 * and then wait for the client to notice this and close its side of the
2964 * connection, after which the server can safely call g_socket_close().
2965 * (This is what #GTcpConnection does if you call
2966 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2967 * only works if the client will close its connection after the server
2970 * Returns: %TRUE on success, %FALSE on error
2975 g_socket_close (GSocket *socket,
2980 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2982 if (socket->priv->closed)
2983 return TRUE; /* Multiple close not an error */
2985 if (!check_socket (socket, error))
2991 res = closesocket (socket->priv->fd);
2993 res = close (socket->priv->fd);
2997 int errsv = get_socket_errno ();
3002 g_set_error (error, G_IO_ERROR,
3003 socket_io_error_from_errno (errsv),
3004 _("Error closing socket: %s"),
3005 socket_strerror (errsv));
3011 socket->priv->connected = FALSE;
3012 socket->priv->closed = TRUE;
3013 if (socket->priv->remote_address)
3015 g_object_unref (socket->priv->remote_address);
3016 socket->priv->remote_address = NULL;
3023 * g_socket_is_closed:
3024 * @socket: a #GSocket
3026 * Checks whether a socket is closed.
3028 * Returns: %TRUE if socket is closed, %FALSE otherwise
3033 g_socket_is_closed (GSocket *socket)
3035 return socket->priv->closed;
3039 /* Broken source, used on errors */
3041 broken_dispatch (GSource *source,
3042 GSourceFunc callback,
3048 static GSourceFuncs broken_funcs =
3057 network_events_for_condition (GIOCondition condition)
3061 if (condition & G_IO_IN)
3062 event_mask |= (FD_READ | FD_ACCEPT);
3063 if (condition & G_IO_OUT)
3064 event_mask |= (FD_WRITE | FD_CONNECT);
3065 event_mask |= FD_CLOSE;
3071 ensure_event (GSocket *socket)
3073 if (socket->priv->event == WSA_INVALID_EVENT)
3074 socket->priv->event = WSACreateEvent();
3078 update_select_events (GSocket *socket)
3085 ensure_event (socket);
3088 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3091 event_mask |= network_events_for_condition (*ptr);
3094 if (event_mask != socket->priv->selected_events)
3096 /* If no events selected, disable event so we can unset
3099 if (event_mask == 0)
3102 event = socket->priv->event;
3104 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3105 socket->priv->selected_events = event_mask;
3110 add_condition_watch (GSocket *socket,
3111 GIOCondition *condition)
3113 g_mutex_lock (&socket->priv->win32_source_lock);
3114 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3116 socket->priv->requested_conditions =
3117 g_list_prepend (socket->priv->requested_conditions, condition);
3119 update_select_events (socket);
3120 g_mutex_unlock (&socket->priv->win32_source_lock);
3124 remove_condition_watch (GSocket *socket,
3125 GIOCondition *condition)
3127 g_mutex_lock (&socket->priv->win32_source_lock);
3128 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3130 socket->priv->requested_conditions =
3131 g_list_remove (socket->priv->requested_conditions, condition);
3133 update_select_events (socket);
3134 g_mutex_unlock (&socket->priv->win32_source_lock);
3138 update_condition (GSocket *socket)
3140 WSANETWORKEVENTS events;
3141 GIOCondition condition;
3143 if (WSAEnumNetworkEvents (socket->priv->fd,
3144 socket->priv->event,
3147 socket->priv->current_events |= events.lNetworkEvents;
3148 if (events.lNetworkEvents & FD_WRITE &&
3149 events.iErrorCode[FD_WRITE_BIT] != 0)
3150 socket->priv->current_errors |= FD_WRITE;
3151 if (events.lNetworkEvents & FD_CONNECT &&
3152 events.iErrorCode[FD_CONNECT_BIT] != 0)
3153 socket->priv->current_errors |= FD_CONNECT;
3157 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3158 condition |= G_IO_IN;
3160 if (socket->priv->current_events & FD_CLOSE)
3162 int r, errsv, buffer;
3164 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3166 errsv = get_socket_errno ();
3169 (r < 0 && errsv == WSAENOTCONN))
3170 condition |= G_IO_IN;
3172 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3173 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3174 condition |= G_IO_HUP;
3176 condition |= G_IO_ERR;
3179 if (socket->priv->closed)
3180 condition |= G_IO_HUP;
3182 /* Never report both G_IO_OUT and HUP, these are
3183 mutually exclusive (can't write to a closed socket) */
3184 if ((condition & G_IO_HUP) == 0 &&
3185 socket->priv->current_events & FD_WRITE)
3187 if (socket->priv->current_errors & FD_WRITE)
3188 condition |= G_IO_ERR;
3190 condition |= G_IO_OUT;
3194 if (socket->priv->current_events & FD_CONNECT)
3196 if (socket->priv->current_errors & FD_CONNECT)
3197 condition |= (G_IO_HUP | G_IO_ERR);
3199 condition |= G_IO_OUT;
3215 GIOCondition condition;
3220 socket_source_prepare_win32 (GSource *source,
3223 GSocketSource *socket_source = (GSocketSource *)source;
3227 return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3231 socket_source_check_win32 (GSource *source)
3235 return socket_source_prepare_win32 (source, &timeout);
3240 socket_source_dispatch (GSource *source,
3241 GSourceFunc callback,
3244 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3245 GSocketSource *socket_source = (GSocketSource *)source;
3246 GSocket *socket = socket_source->socket;
3252 events = update_condition (socket_source->socket);
3254 events = g_source_query_unix_fd (source, socket_source->fd_tag);
3257 timeout = g_source_get_ready_time (source);
3258 if (timeout >= 0 && timeout < g_source_get_time (source))
3260 socket->priv->timed_out = TRUE;
3261 events |= (G_IO_IN | G_IO_OUT);
3264 ret = (*func) (socket, events & socket_source->condition, user_data);
3266 if (socket->priv->timeout)
3267 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3269 g_source_set_ready_time (source, -1);
3275 socket_source_finalize (GSource *source)
3277 GSocketSource *socket_source = (GSocketSource *)source;
3280 socket = socket_source->socket;
3283 remove_condition_watch (socket, &socket_source->condition);
3286 g_object_unref (socket);
3290 socket_source_closure_callback (GSocket *socket,
3291 GIOCondition condition,
3294 GClosure *closure = data;
3296 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3297 GValue result_value = G_VALUE_INIT;
3300 g_value_init (&result_value, G_TYPE_BOOLEAN);
3302 g_value_init (¶ms[0], G_TYPE_SOCKET);
3303 g_value_set_object (¶ms[0], socket);
3304 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
3305 g_value_set_flags (¶ms[1], condition);
3307 g_closure_invoke (closure, &result_value, 2, params, NULL);
3309 result = g_value_get_boolean (&result_value);
3310 g_value_unset (&result_value);
3311 g_value_unset (¶ms[0]);
3312 g_value_unset (¶ms[1]);
3317 static GSourceFuncs socket_source_funcs =
3320 socket_source_prepare_win32,
3321 socket_source_check_win32,
3323 NULL, NULL, /* check, prepare */
3325 socket_source_dispatch,
3326 socket_source_finalize,
3327 (GSourceFunc)socket_source_closure_callback,
3331 socket_source_new (GSocket *socket,
3332 GIOCondition condition,
3333 GCancellable *cancellable)
3336 GSocketSource *socket_source;
3339 ensure_event (socket);
3341 if (socket->priv->event == WSA_INVALID_EVENT)
3343 g_warning ("Failed to create WSAEvent");
3344 return g_source_new (&broken_funcs, sizeof (GSource));
3348 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
3350 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3351 g_source_set_name (source, "GSocket");
3352 socket_source = (GSocketSource *)source;
3354 socket_source->socket = g_object_ref (socket);
3355 socket_source->condition = condition;
3359 GSource *cancellable_source;
3361 cancellable_source = g_cancellable_source_new (cancellable);
3362 g_source_add_child_source (source, cancellable_source);
3363 g_source_set_dummy_callback (cancellable_source);
3364 g_source_unref (cancellable_source);
3368 add_condition_watch (socket, &socket_source->condition);
3369 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3370 socket_source->pollfd.events = condition;
3371 socket_source->pollfd.revents = 0;
3372 g_source_add_poll (source, &socket_source->pollfd);
3374 socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
3377 if (socket->priv->timeout)
3378 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3380 g_source_set_ready_time (source, -1);
3386 * g_socket_create_source: (skip)
3387 * @socket: a #GSocket
3388 * @condition: a #GIOCondition mask to monitor
3389 * @cancellable: (allow-none): a %GCancellable or %NULL
3391 * Creates a #GSource that can be attached to a %GMainContext to monitor
3392 * for the availability of the specified @condition on the socket. The #GSource
3393 * keeps a reference to the @socket.
3395 * The callback on the source is of the #GSocketSourceFunc type.
3397 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3398 * these conditions will always be reported output if they are true.
3400 * @cancellable if not %NULL can be used to cancel the source, which will
3401 * cause the source to trigger, reporting the current condition (which
3402 * is likely 0 unless cancellation happened at the same time as a
3403 * condition change). You can check for this in the callback using
3404 * g_cancellable_is_cancelled().
3406 * If @socket has a timeout set, and it is reached before @condition
3407 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3408 * %G_IO_OUT depending on @condition. However, @socket will have been
3409 * marked as having had a timeout, and so the next #GSocket I/O method
3410 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3412 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3417 g_socket_create_source (GSocket *socket,
3418 GIOCondition condition,
3419 GCancellable *cancellable)
3421 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3423 return socket_source_new (socket, condition, cancellable);
3427 * g_socket_condition_check:
3428 * @socket: a #GSocket
3429 * @condition: a #GIOCondition mask to check
3431 * Checks on the readiness of @socket to perform operations.
3432 * The operations specified in @condition are checked for and masked
3433 * against the currently-satisfied conditions on @socket. The result
3436 * Note that on Windows, it is possible for an operation to return
3437 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3438 * g_socket_condition_check() has claimed that the socket is ready for
3439 * writing. Rather than calling g_socket_condition_check() and then
3440 * writing to the socket if it succeeds, it is generally better to
3441 * simply try writing to the socket right away, and try again later if
3442 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3444 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3445 * these conditions will always be set in the output if they are true.
3447 * This call never blocks.
3449 * Returns: the @GIOCondition mask of the current state
3454 g_socket_condition_check (GSocket *socket,
3455 GIOCondition condition)
3457 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3459 if (!check_socket (socket, NULL))
3464 GIOCondition current_condition;
3466 condition |= G_IO_ERR | G_IO_HUP;
3468 add_condition_watch (socket, &condition);
3469 current_condition = update_condition (socket);
3470 remove_condition_watch (socket, &condition);
3471 return condition & current_condition;
3477 poll_fd.fd = socket->priv->fd;
3478 poll_fd.events = condition;
3479 poll_fd.revents = 0;
3482 result = g_poll (&poll_fd, 1, 0);
3483 while (result == -1 && get_socket_errno () == EINTR);
3485 return poll_fd.revents;
3491 * g_socket_condition_wait:
3492 * @socket: a #GSocket
3493 * @condition: a #GIOCondition mask to wait for
3494 * @cancellable: (allow-none): a #GCancellable, or %NULL
3495 * @error: a #GError pointer, or %NULL
3497 * Waits for @condition to become true on @socket. When the condition
3498 * is met, %TRUE is returned.
3500 * If @cancellable is cancelled before the condition is met, or if the
3501 * socket has a timeout set and it is reached before the condition is
3502 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3503 * the appropriate value (%G_IO_ERROR_CANCELLED or
3504 * %G_IO_ERROR_TIMED_OUT).
3506 * See also g_socket_condition_timed_wait().
3508 * Returns: %TRUE if the condition was met, %FALSE otherwise
3513 g_socket_condition_wait (GSocket *socket,
3514 GIOCondition condition,
3515 GCancellable *cancellable,
3518 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3520 return g_socket_condition_timed_wait (socket, condition, -1,
3521 cancellable, error);
3525 * g_socket_condition_timed_wait:
3526 * @socket: a #GSocket
3527 * @condition: a #GIOCondition mask to wait for
3528 * @timeout: the maximum time (in microseconds) to wait, or -1
3529 * @cancellable: (allow-none): a #GCancellable, or %NULL
3530 * @error: a #GError pointer, or %NULL
3532 * Waits for up to @timeout microseconds for @condition to become true
3533 * on @socket. If the condition is met, %TRUE is returned.
3535 * If @cancellable is cancelled before the condition is met, or if
3536 * @timeout (or the socket's #GSocket:timeout) is reached before the
3537 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3538 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3539 * %G_IO_ERROR_TIMED_OUT).
3541 * If you don't want a timeout, use g_socket_condition_wait().
3542 * (Alternatively, you can pass -1 for @timeout.)
3544 * Note that although @timeout is in microseconds for consistency with
3545 * other GLib APIs, this function actually only has millisecond
3546 * resolution, and the behavior is undefined if @timeout is not an
3547 * exact number of milliseconds.
3549 * Returns: %TRUE if the condition was met, %FALSE otherwise
3554 g_socket_condition_timed_wait (GSocket *socket,
3555 GIOCondition condition,
3557 GCancellable *cancellable,
3562 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3564 if (!check_socket (socket, error))
3567 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3570 if (socket->priv->timeout &&
3571 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3572 timeout = socket->priv->timeout * 1000;
3573 else if (timeout != -1)
3574 timeout = timeout / 1000;
3576 start_time = g_get_monotonic_time ();
3580 GIOCondition current_condition;
3586 /* Always check these */
3587 condition |= G_IO_ERR | G_IO_HUP;
3589 add_condition_watch (socket, &condition);
3592 events[num_events++] = socket->priv->event;
3594 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3595 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3598 timeout = WSA_INFINITE;
3600 current_condition = update_condition (socket);
3601 while ((condition & current_condition) == 0)
3603 res = WSAWaitForMultipleEvents (num_events, events,
3604 FALSE, timeout, FALSE);
3605 if (res == WSA_WAIT_FAILED)
3607 int errsv = get_socket_errno ();
3609 g_set_error (error, G_IO_ERROR,
3610 socket_io_error_from_errno (errsv),
3611 _("Waiting for socket condition: %s"),
3612 socket_strerror (errsv));
3615 else if (res == WSA_WAIT_TIMEOUT)
3617 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3618 _("Socket I/O timed out"));
3622 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3625 current_condition = update_condition (socket);
3627 if (timeout != WSA_INFINITE)
3629 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3634 remove_condition_watch (socket, &condition);
3636 g_cancellable_release_fd (cancellable);
3638 return (condition & current_condition) != 0;
3646 poll_fd[0].fd = socket->priv->fd;
3647 poll_fd[0].events = condition;
3650 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3655 result = g_poll (poll_fd, num, timeout);
3656 if (result != -1 || errno != EINTR)
3661 timeout -= (g_get_monotonic_time () - start_time) / 1000;
3668 g_cancellable_release_fd (cancellable);
3672 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3673 _("Socket I/O timed out"));
3677 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3683 * g_socket_send_message:
3684 * @socket: a #GSocket
3685 * @address: (allow-none): a #GSocketAddress, or %NULL
3686 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3687 * @num_vectors: the number of elements in @vectors, or -1
3688 * @messages: (array length=num_messages) (allow-none): a pointer to an
3689 * array of #GSocketControlMessages, or %NULL.
3690 * @num_messages: number of elements in @messages, or -1.
3691 * @flags: an int containing #GSocketMsgFlags flags
3692 * @cancellable: (allow-none): a %GCancellable or %NULL
3693 * @error: #GError for error reporting, or %NULL to ignore.
3695 * Send data to @address on @socket. This is the most complicated and
3696 * fully-featured version of this call. For easier use, see
3697 * g_socket_send() and g_socket_send_to().
3699 * If @address is %NULL then the message is sent to the default receiver
3700 * (set by g_socket_connect()).
3702 * @vectors must point to an array of #GOutputVector structs and
3703 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3704 * then @vectors is assumed to be terminated by a #GOutputVector with a
3705 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3706 * that the sent data will be gathered from. Using multiple
3707 * #GOutputVectors is more memory-efficient than manually copying
3708 * data from multiple sources into a single buffer, and more
3709 * network-efficient than making multiple calls to g_socket_send().
3711 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3712 * #GSocketControlMessage instances. These correspond to the control
3713 * messages to be sent on the socket.
3714 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3717 * @flags modify how the message is sent. The commonly available arguments
3718 * for this are available in the #GSocketMsgFlags enum, but the
3719 * values there are the same as the system values, and the flags
3720 * are passed in as-is, so you can pass in system-specific flags too.
3722 * If the socket is in blocking mode the call will block until there is
3723 * space for the data in the socket queue. If there is no space available
3724 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3725 * will be returned. To be notified when space is available, wait for the
3726 * %G_IO_OUT condition. Note though that you may still receive
3727 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3728 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3729 * very common due to the way the underlying APIs work.)
3731 * On error -1 is returned and @error is set accordingly.
3733 * Returns: Number of bytes written (which may be less than @size), or -1
3739 g_socket_send_message (GSocket *socket,
3740 GSocketAddress *address,
3741 GOutputVector *vectors,
3743 GSocketControlMessage **messages,
3746 GCancellable *cancellable,
3749 GOutputVector one_vector;
3752 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3753 g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), -1);
3754 g_return_val_if_fail (num_vectors == 0 || vectors != NULL, -1);
3755 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
3756 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
3757 g_return_val_if_fail (error == NULL || *error == NULL, -1);
3759 if (!check_socket (socket, error))
3762 if (!check_timeout (socket, error))
3765 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3768 if (num_vectors == -1)
3770 for (num_vectors = 0;
3771 vectors[num_vectors].buffer != NULL;
3776 if (num_messages == -1)
3778 for (num_messages = 0;
3779 messages != NULL && messages[num_messages] != NULL;
3784 if (num_vectors == 0)
3788 one_vector.buffer = &zero;
3789 one_vector.size = 1;
3791 vectors = &one_vector;
3804 msg.msg_namelen = g_socket_address_get_native_size (address);
3805 msg.msg_name = g_alloca (msg.msg_namelen);
3806 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3811 msg.msg_name = NULL;
3812 msg.msg_namelen = 0;
3817 /* this entire expression will be evaluated at compile time */
3818 if (sizeof *msg.msg_iov == sizeof *vectors &&
3819 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3820 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3821 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3822 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3823 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3824 G_STRUCT_OFFSET (GOutputVector, size))
3825 /* ABI is compatible */
3827 msg.msg_iov = (struct iovec *) vectors;
3828 msg.msg_iovlen = num_vectors;
3831 /* ABI is incompatible */
3835 msg.msg_iov = g_newa (struct iovec, num_vectors);
3836 for (i = 0; i < num_vectors; i++)
3838 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3839 msg.msg_iov[i].iov_len = vectors[i].size;
3841 msg.msg_iovlen = num_vectors;
3847 struct cmsghdr *cmsg;
3850 msg.msg_controllen = 0;
3851 for (i = 0; i < num_messages; i++)
3852 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3854 if (msg.msg_controllen == 0)
3855 msg.msg_control = NULL;
3858 msg.msg_control = g_alloca (msg.msg_controllen);
3859 memset (msg.msg_control, '\0', msg.msg_controllen);
3862 cmsg = CMSG_FIRSTHDR (&msg);
3863 for (i = 0; i < num_messages; i++)
3865 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3866 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3867 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3868 g_socket_control_message_serialize (messages[i],
3870 cmsg = CMSG_NXTHDR (&msg, cmsg);
3872 g_assert (cmsg == NULL);
3877 if (socket->priv->blocking &&
3878 !g_socket_condition_wait (socket,
3879 G_IO_OUT, cancellable, error))
3882 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3885 int errsv = get_socket_errno ();
3890 if (socket->priv->blocking &&
3891 (errsv == EWOULDBLOCK ||
3895 g_set_error (error, G_IO_ERROR,
3896 socket_io_error_from_errno (errsv),
3897 _("Error sending message: %s"), socket_strerror (errsv));
3908 struct sockaddr_storage addr;
3915 /* Win32 doesn't support control messages.
3916 Actually this is possible for raw and datagram sockets
3917 via WSASendMessage on Vista or later, but that doesn't
3919 if (num_messages != 0)
3921 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3922 _("GSocketControlMessage not supported on Windows"));
3927 bufs = g_newa (WSABUF, num_vectors);
3928 for (i = 0; i < num_vectors; i++)
3930 bufs[i].buf = (char *)vectors[i].buffer;
3931 bufs[i].len = (gulong)vectors[i].size;
3935 addrlen = 0; /* Avoid warning */
3938 addrlen = g_socket_address_get_native_size (address);
3939 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3945 if (socket->priv->blocking &&
3946 !g_socket_condition_wait (socket,
3947 G_IO_OUT, cancellable, error))
3951 result = WSASendTo (socket->priv->fd,
3954 (const struct sockaddr *)&addr, addrlen,
3957 result = WSASend (socket->priv->fd,
3964 int errsv = get_socket_errno ();
3966 if (errsv == WSAEINTR)
3969 if (errsv == WSAEWOULDBLOCK)
3970 win32_unset_event_mask (socket, FD_WRITE);
3972 if (socket->priv->blocking &&
3973 errsv == WSAEWOULDBLOCK)
3976 g_set_error (error, G_IO_ERROR,
3977 socket_io_error_from_errno (errsv),
3978 _("Error sending message: %s"), socket_strerror (errsv));
3990 static GSocketAddress *
3991 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
3993 GSocketAddress *saddr;
3995 guint64 oldest_time = G_MAXUINT64;
3996 gint oldest_index = 0;
3998 if (native_len <= 0)
4002 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
4004 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
4005 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
4006 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
4011 if (tmp_native_len != native_len)
4014 if (memcmp (tmp_native, native, native_len) == 0)
4016 saddr = g_object_ref (tmp);
4017 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
4021 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
4023 oldest_time = socket->priv->recv_addr_cache[i].last_used;
4028 saddr = g_socket_address_new_from_native (native, native_len);
4030 if (socket->priv->recv_addr_cache[oldest_index].addr)
4032 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
4033 g_free (socket->priv->recv_addr_cache[oldest_index].native);
4036 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
4037 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
4038 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
4039 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
4045 * g_socket_receive_message:
4046 * @socket: a #GSocket
4047 * @address: (out) (allow-none): a pointer to a #GSocketAddress
4049 * @vectors: (array length=num_vectors): an array of #GInputVector structs
4050 * @num_vectors: the number of elements in @vectors, or -1
4051 * @messages: (array length=num_messages) (allow-none): a pointer which
4052 * may be filled with an array of #GSocketControlMessages, or %NULL
4053 * @num_messages: a pointer which will be filled with the number of
4054 * elements in @messages, or %NULL
4055 * @flags: a pointer to an int containing #GSocketMsgFlags flags
4056 * @cancellable: (allow-none): a %GCancellable or %NULL
4057 * @error: a #GError pointer, or %NULL
4059 * Receive data from a socket. This is the most complicated and
4060 * fully-featured version of this call. For easier use, see
4061 * g_socket_receive() and g_socket_receive_from().
4063 * If @address is non-%NULL then @address will be set equal to the
4064 * source address of the received packet.
4065 * @address is owned by the caller.
4067 * @vector must point to an array of #GInputVector structs and
4068 * @num_vectors must be the length of this array. These structs
4069 * describe the buffers that received data will be scattered into.
4070 * If @num_vectors is -1, then @vectors is assumed to be terminated
4071 * by a #GInputVector with a %NULL buffer pointer.
4073 * As a special case, if @num_vectors is 0 (in which case, @vectors
4074 * may of course be %NULL), then a single byte is received and
4075 * discarded. This is to facilitate the common practice of sending a
4076 * single '\0' byte for the purposes of transferring ancillary data.
4078 * @messages, if non-%NULL, will be set to point to a newly-allocated
4079 * array of #GSocketControlMessage instances or %NULL if no such
4080 * messages was received. These correspond to the control messages
4081 * received from the kernel, one #GSocketControlMessage per message
4082 * from the kernel. This array is %NULL-terminated and must be freed
4083 * by the caller using g_free() after calling g_object_unref() on each
4084 * element. If @messages is %NULL, any control messages received will
4087 * @num_messages, if non-%NULL, will be set to the number of control
4088 * messages received.
4090 * If both @messages and @num_messages are non-%NULL, then
4091 * @num_messages gives the number of #GSocketControlMessage instances
4092 * in @messages (ie: not including the %NULL terminator).
4094 * @flags is an in/out parameter. The commonly available arguments
4095 * for this are available in the #GSocketMsgFlags enum, but the
4096 * values there are the same as the system values, and the flags
4097 * are passed in as-is, so you can pass in system-specific flags too
4098 * (and g_socket_receive_message() may pass system-specific flags out).
4100 * As with g_socket_receive(), data may be discarded if @socket is
4101 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
4102 * provide enough buffer space to read a complete message. You can pass
4103 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
4104 * removing it from the receive queue, but there is no portable way to find
4105 * out the length of the message other than by reading it into a
4106 * sufficiently-large buffer.
4108 * If the socket is in blocking mode the call will block until there
4109 * is some data to receive, the connection is closed, or there is an
4110 * error. If there is no data available and the socket is in
4111 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
4112 * returned. To be notified when data is available, wait for the
4113 * %G_IO_IN condition.
4115 * On error -1 is returned and @error is set accordingly.
4117 * Returns: Number of bytes read, or 0 if the connection was closed by
4118 * the peer, or -1 on error
4123 g_socket_receive_message (GSocket *socket,
4124 GSocketAddress **address,
4125 GInputVector *vectors,
4127 GSocketControlMessage ***messages,
4130 GCancellable *cancellable,
4133 GInputVector one_vector;
4136 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4138 if (!check_socket (socket, error))
4141 if (!check_timeout (socket, error))
4144 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4147 if (num_vectors == -1)
4149 for (num_vectors = 0;
4150 vectors[num_vectors].buffer != NULL;
4155 if (num_vectors == 0)
4157 one_vector.buffer = &one_byte;
4158 one_vector.size = 1;
4160 vectors = &one_vector;
4167 struct sockaddr_storage one_sockaddr;
4172 msg.msg_name = &one_sockaddr;
4173 msg.msg_namelen = sizeof (struct sockaddr_storage);
4177 msg.msg_name = NULL;
4178 msg.msg_namelen = 0;
4182 /* this entire expression will be evaluated at compile time */
4183 if (sizeof *msg.msg_iov == sizeof *vectors &&
4184 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4185 G_STRUCT_OFFSET (struct iovec, iov_base) ==
4186 G_STRUCT_OFFSET (GInputVector, buffer) &&
4187 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4188 G_STRUCT_OFFSET (struct iovec, iov_len) ==
4189 G_STRUCT_OFFSET (GInputVector, size))
4190 /* ABI is compatible */
4192 msg.msg_iov = (struct iovec *) vectors;
4193 msg.msg_iovlen = num_vectors;
4196 /* ABI is incompatible */
4200 msg.msg_iov = g_newa (struct iovec, num_vectors);
4201 for (i = 0; i < num_vectors; i++)
4203 msg.msg_iov[i].iov_base = vectors[i].buffer;
4204 msg.msg_iov[i].iov_len = vectors[i].size;
4206 msg.msg_iovlen = num_vectors;
4210 msg.msg_control = g_alloca (2048);
4211 msg.msg_controllen = 2048;
4215 msg.msg_flags = *flags;
4219 /* We always set the close-on-exec flag so we don't leak file
4220 * descriptors into child processes. Note that gunixfdmessage.c
4221 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4223 #ifdef MSG_CMSG_CLOEXEC
4224 msg.msg_flags |= MSG_CMSG_CLOEXEC;
4230 if (socket->priv->blocking &&
4231 !g_socket_condition_wait (socket,
4232 G_IO_IN, cancellable, error))
4235 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4236 #ifdef MSG_CMSG_CLOEXEC
4237 if (result < 0 && get_socket_errno () == EINVAL)
4239 /* We must be running on an old kernel. Call without the flag. */
4240 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4241 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4247 int errsv = get_socket_errno ();
4252 if (socket->priv->blocking &&
4253 (errsv == EWOULDBLOCK ||
4257 g_set_error (error, G_IO_ERROR,
4258 socket_io_error_from_errno (errsv),
4259 _("Error receiving message: %s"), socket_strerror (errsv));
4266 /* decode address */
4267 if (address != NULL)
4269 *address = cache_recv_address (socket, msg.msg_name, msg.msg_namelen);
4272 /* decode control messages */
4274 GPtrArray *my_messages = NULL;
4275 struct cmsghdr *cmsg;
4277 if (msg.msg_controllen >= sizeof (struct cmsghdr))
4279 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4281 GSocketControlMessage *message;
4283 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4285 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4287 if (message == NULL)
4288 /* We've already spewed about the problem in the
4289 deserialization code, so just continue */
4292 if (messages == NULL)
4294 /* we have to do it this way if the user ignores the
4295 * messages so that we will close any received fds.
4297 g_object_unref (message);
4301 if (my_messages == NULL)
4302 my_messages = g_ptr_array_new ();
4303 g_ptr_array_add (my_messages, message);
4309 *num_messages = my_messages != NULL ? my_messages->len : 0;
4313 if (my_messages == NULL)
4319 g_ptr_array_add (my_messages, NULL);
4320 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4325 g_assert (my_messages == NULL);
4329 /* capture the flags */
4331 *flags = msg.msg_flags;
4337 struct sockaddr_storage addr;
4339 DWORD bytes_received;
4346 bufs = g_newa (WSABUF, num_vectors);
4347 for (i = 0; i < num_vectors; i++)
4349 bufs[i].buf = (char *)vectors[i].buffer;
4350 bufs[i].len = (gulong)vectors[i].size;
4362 if (socket->priv->blocking &&
4363 !g_socket_condition_wait (socket,
4364 G_IO_IN, cancellable, error))
4367 addrlen = sizeof addr;
4369 result = WSARecvFrom (socket->priv->fd,
4371 &bytes_received, &win_flags,
4372 (struct sockaddr *)&addr, &addrlen,
4375 result = WSARecv (socket->priv->fd,
4377 &bytes_received, &win_flags,
4381 int errsv = get_socket_errno ();
4383 if (errsv == WSAEINTR)
4386 win32_unset_event_mask (socket, FD_READ);
4388 if (socket->priv->blocking &&
4389 errsv == WSAEWOULDBLOCK)
4392 g_set_error (error, G_IO_ERROR,
4393 socket_io_error_from_errno (errsv),
4394 _("Error receiving message: %s"), socket_strerror (errsv));
4398 win32_unset_event_mask (socket, FD_READ);
4402 /* decode address */
4403 if (address != NULL)
4405 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
4408 /* capture the flags */
4412 if (messages != NULL)
4414 if (num_messages != NULL)
4417 return bytes_received;
4423 * g_socket_get_credentials:
4424 * @socket: a #GSocket.
4425 * @error: #GError for error reporting, or %NULL to ignore.
4427 * Returns the credentials of the foreign process connected to this
4428 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4431 * If this operation isn't supported on the OS, the method fails with
4432 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4433 * by reading the %SO_PEERCRED option on the underlying socket.
4435 * Other ways to obtain credentials from a foreign peer includes the
4436 * #GUnixCredentialsMessage type and
4437 * g_unix_connection_send_credentials() /
4438 * g_unix_connection_receive_credentials() functions.
4440 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4441 * that must be freed with g_object_unref().
4446 g_socket_get_credentials (GSocket *socket,
4451 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4452 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4456 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
4460 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
4461 socklen_t optlen = sizeof (native_creds_buf);
4463 if (getsockopt (socket->priv->fd,
4469 ret = g_credentials_new ();
4470 g_credentials_set_native (ret,
4471 G_CREDENTIALS_NATIVE_TYPE,
4475 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
4477 struct unpcbid cred;
4478 socklen_t optlen = sizeof (cred);
4480 if (getsockopt (socket->priv->fd,
4486 ret = g_credentials_new ();
4487 g_credentials_set_native (ret,
4488 G_CREDENTIALS_NATIVE_TYPE,
4492 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
4494 ucred_t *ucred = NULL;
4496 if (getpeerucred (socket->priv->fd, &ucred) == 0)
4498 ret = g_credentials_new ();
4499 g_credentials_set_native (ret,
4500 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
4506 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
4511 int errsv = get_socket_errno ();
4515 socket_io_error_from_errno (errsv),
4516 _("Unable to read socket credentials: %s"),
4517 socket_strerror (errsv));
4522 g_set_error_literal (error,
4524 G_IO_ERROR_NOT_SUPPORTED,
4525 _("g_socket_get_credentials not implemented for this OS"));
4532 * g_socket_get_option:
4533 * @socket: a #GSocket
4534 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
4535 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
4536 * @value: (out): return location for the option value
4537 * @error: #GError for error reporting, or %NULL to ignore.
4539 * Gets the value of an integer-valued option on @socket, as with
4540 * getsockopt(). (If you need to fetch a non-integer-valued option,
4541 * you will need to call getsockopt() directly.)
4543 * The [<gio/gnetworking.h>][gio-gnetworking.h]
4544 * header pulls in system headers that will define most of the
4545 * standard/portable socket options. For unusual socket protocols or
4546 * platform-dependent options, you may need to include additional
4549 * Note that even for socket options that are a single byte in size,
4550 * @value is still a pointer to a #gint variable, not a #guchar;
4551 * g_socket_get_option() will handle the conversion internally.
4553 * Returns: success or failure. On failure, @error will be set, and
4554 * the system error value (`errno` or WSAGetLastError()) will still
4555 * be set to the result of the getsockopt() call.
4560 g_socket_get_option (GSocket *socket,
4568 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4571 size = sizeof (gint);
4572 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
4574 int errsv = get_socket_errno ();
4576 g_set_error_literal (error,
4578 socket_io_error_from_errno (errsv),
4579 socket_strerror (errsv));
4581 /* Reset errno in case the caller wants to look at it */
4587 #if G_BYTE_ORDER == G_BIG_ENDIAN
4588 /* If the returned value is smaller than an int then we need to
4589 * slide it over into the low-order bytes of *value.
4591 if (size != sizeof (gint))
4592 *value = *value >> (8 * (sizeof (gint) - size));
4599 * g_socket_set_option:
4600 * @socket: a #GSocket
4601 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
4602 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
4603 * @value: the value to set the option to
4604 * @error: #GError for error reporting, or %NULL to ignore.
4606 * Sets the value of an integer-valued option on @socket, as with
4607 * setsockopt(). (If you need to set a non-integer-valued option,
4608 * you will need to call setsockopt() directly.)
4610 * The [<gio/gnetworking.h>][gio-gnetworking.h]
4611 * header pulls in system headers that will define most of the
4612 * standard/portable socket options. For unusual socket protocols or
4613 * platform-dependent options, you may need to include additional
4616 * Returns: success or failure. On failure, @error will be set, and
4617 * the system error value (`errno` or WSAGetLastError()) will still
4618 * be set to the result of the setsockopt() call.
4623 g_socket_set_option (GSocket *socket,
4631 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4633 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
4636 #if !defined (__linux__) && !defined (G_OS_WIN32)
4637 /* Linux and Windows let you set a single-byte value from an int,
4638 * but most other platforms don't.
4640 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
4642 #if G_BYTE_ORDER == G_BIG_ENDIAN
4643 value = value << (8 * (sizeof (gint) - 1));
4645 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
4650 errsv = get_socket_errno ();
4652 g_set_error_literal (error,
4654 socket_io_error_from_errno (errsv),
4655 socket_strerror (errsv));