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 set_fd_nonblocking (int fd)
263 GError *error = NULL;
269 if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
271 g_warning ("Error setting socket nonblocking: %s", error->message);
272 g_clear_error (&error);
277 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
279 int errsv = get_socket_errno ();
280 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
286 check_socket (GSocket *socket,
289 if (!socket->priv->inited)
291 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
292 _("Invalid socket, not initialized"));
296 if (socket->priv->construct_error)
298 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
299 _("Invalid socket, initialization failed due to: %s"),
300 socket->priv->construct_error->message);
304 if (socket->priv->closed)
306 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
307 _("Socket is already closed"));
315 check_timeout (GSocket *socket,
318 if (socket->priv->timed_out)
320 socket->priv->timed_out = FALSE;
321 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
322 _("Socket I/O timed out"));
330 g_socket_details_from_fd (GSocket *socket)
332 struct sockaddr_storage address;
338 fd = socket->priv->fd;
339 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
341 errsv = get_socket_errno ();
353 /* programmer error */
354 g_error ("creating GSocket from fd %d: %s\n",
355 fd, socket_strerror (errsv));
366 socket->priv->type = G_SOCKET_TYPE_STREAM;
370 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
374 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
378 socket->priv->type = G_SOCKET_TYPE_INVALID;
382 addrlen = sizeof address;
383 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
385 errsv = get_socket_errno ();
391 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
392 sizeof address.ss_family <= addrlen);
393 family = address.ss_family;
397 /* On Solaris, this happens if the socket is not yet connected.
398 * But we can use SO_DOMAIN as a workaround there.
401 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
403 errsv = get_socket_errno ();
407 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
415 case G_SOCKET_FAMILY_IPV4:
416 case G_SOCKET_FAMILY_IPV6:
417 socket->priv->family = address.ss_family;
418 switch (socket->priv->type)
420 case G_SOCKET_TYPE_STREAM:
421 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
424 case G_SOCKET_TYPE_DATAGRAM:
425 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
428 case G_SOCKET_TYPE_SEQPACKET:
429 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
437 case G_SOCKET_FAMILY_UNIX:
438 socket->priv->family = G_SOCKET_FAMILY_UNIX;
439 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
443 socket->priv->family = G_SOCKET_FAMILY_INVALID;
447 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
449 addrlen = sizeof address;
450 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
451 socket->priv->connected = TRUE;
454 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
456 socket->priv->keepalive = !!value;
460 /* Can't read, maybe not supported, assume FALSE */
461 socket->priv->keepalive = FALSE;
467 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
468 socket_io_error_from_errno (errsv),
469 _("creating GSocket from fd: %s"),
470 socket_strerror (errsv));
473 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
475 g_socket (gint domain,
483 fd = socket (domain, type | SOCK_CLOEXEC, protocol);
487 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
488 if (fd < 0 && (errno == EINVAL || errno == EPROTOTYPE))
490 fd = socket (domain, type, protocol);
494 int errsv = get_socket_errno ();
496 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
497 _("Unable to create socket: %s"), socket_strerror (errsv));
506 /* We always want to set close-on-exec to protect users. If you
507 need to so some weird inheritance to exec you can re-enable this
508 using lower level hacks with g_socket_get_fd(). */
509 flags = fcntl (fd, F_GETFD, 0);
511 (flags & FD_CLOEXEC) == 0)
514 fcntl (fd, F_SETFD, flags);
523 g_socket_create_socket (GSocketFamily family,
532 case G_SOCKET_TYPE_STREAM:
533 native_type = SOCK_STREAM;
536 case G_SOCKET_TYPE_DATAGRAM:
537 native_type = SOCK_DGRAM;
540 case G_SOCKET_TYPE_SEQPACKET:
541 native_type = SOCK_SEQPACKET;
545 g_assert_not_reached ();
550 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
551 _("Unable to create socket: %s"), _("Unknown family was specified"));
557 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
558 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
562 return g_socket (family, native_type, protocol, error);
566 g_socket_constructed (GObject *object)
568 GSocket *socket = G_SOCKET (object);
570 if (socket->priv->fd >= 0)
571 /* create socket->priv info from the fd */
572 g_socket_details_from_fd (socket);
575 /* create the fd from socket->priv info */
576 socket->priv->fd = g_socket_create_socket (socket->priv->family,
578 socket->priv->protocol,
579 &socket->priv->construct_error);
581 /* Always use native nonblocking sockets, as
582 windows sets sockets to nonblocking automatically
583 in certain operations. This way we make things work
584 the same on all platforms */
585 if (socket->priv->fd != -1)
586 set_fd_nonblocking (socket->priv->fd);
590 g_socket_get_property (GObject *object,
595 GSocket *socket = G_SOCKET (object);
596 GSocketAddress *address;
601 g_value_set_enum (value, socket->priv->family);
605 g_value_set_enum (value, socket->priv->type);
609 g_value_set_enum (value, socket->priv->protocol);
613 g_value_set_int (value, socket->priv->fd);
617 g_value_set_boolean (value, socket->priv->blocking);
620 case PROP_LISTEN_BACKLOG:
621 g_value_set_int (value, socket->priv->listen_backlog);
625 g_value_set_boolean (value, socket->priv->keepalive);
628 case PROP_LOCAL_ADDRESS:
629 address = g_socket_get_local_address (socket, NULL);
630 g_value_take_object (value, address);
633 case PROP_REMOTE_ADDRESS:
634 address = g_socket_get_remote_address (socket, NULL);
635 g_value_take_object (value, address);
639 g_value_set_uint (value, socket->priv->timeout);
643 g_value_set_uint (value, g_socket_get_ttl (socket));
647 g_value_set_boolean (value, g_socket_get_broadcast (socket));
650 case PROP_MULTICAST_LOOPBACK:
651 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
654 case PROP_MULTICAST_TTL:
655 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
659 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
664 g_socket_set_property (GObject *object,
669 GSocket *socket = G_SOCKET (object);
674 socket->priv->family = g_value_get_enum (value);
678 socket->priv->type = g_value_get_enum (value);
682 socket->priv->protocol = g_value_get_enum (value);
686 socket->priv->fd = g_value_get_int (value);
690 g_socket_set_blocking (socket, g_value_get_boolean (value));
693 case PROP_LISTEN_BACKLOG:
694 g_socket_set_listen_backlog (socket, g_value_get_int (value));
698 g_socket_set_keepalive (socket, g_value_get_boolean (value));
702 g_socket_set_timeout (socket, g_value_get_uint (value));
706 g_socket_set_ttl (socket, g_value_get_uint (value));
710 g_socket_set_broadcast (socket, g_value_get_boolean (value));
713 case PROP_MULTICAST_LOOPBACK:
714 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
717 case PROP_MULTICAST_TTL:
718 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
722 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
727 g_socket_finalize (GObject *object)
729 GSocket *socket = G_SOCKET (object);
732 g_clear_error (&socket->priv->construct_error);
734 if (socket->priv->fd != -1 &&
735 !socket->priv->closed)
736 g_socket_close (socket, NULL);
738 if (socket->priv->remote_address)
739 g_object_unref (socket->priv->remote_address);
742 if (socket->priv->event != WSA_INVALID_EVENT)
744 WSACloseEvent (socket->priv->event);
745 socket->priv->event = WSA_INVALID_EVENT;
748 g_assert (socket->priv->requested_conditions == NULL);
749 g_mutex_clear (&socket->priv->win32_source_lock);
752 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
754 if (socket->priv->recv_addr_cache[i].addr)
756 g_object_unref (socket->priv->recv_addr_cache[i].addr);
757 g_free (socket->priv->recv_addr_cache[i].native);
761 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
762 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
766 g_socket_class_init (GSocketClass *klass)
768 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
771 /* There is no portable, thread-safe way to avoid having the process
772 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
773 * forced to simply ignore the signal process-wide.
775 signal (SIGPIPE, SIG_IGN);
778 gobject_class->finalize = g_socket_finalize;
779 gobject_class->constructed = g_socket_constructed;
780 gobject_class->set_property = g_socket_set_property;
781 gobject_class->get_property = g_socket_get_property;
783 g_object_class_install_property (gobject_class, PROP_FAMILY,
784 g_param_spec_enum ("family",
786 P_("The sockets address family"),
787 G_TYPE_SOCKET_FAMILY,
788 G_SOCKET_FAMILY_INVALID,
789 G_PARAM_CONSTRUCT_ONLY |
791 G_PARAM_STATIC_STRINGS));
793 g_object_class_install_property (gobject_class, PROP_TYPE,
794 g_param_spec_enum ("type",
796 P_("The sockets type"),
798 G_SOCKET_TYPE_STREAM,
799 G_PARAM_CONSTRUCT_ONLY |
801 G_PARAM_STATIC_STRINGS));
803 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
804 g_param_spec_enum ("protocol",
805 P_("Socket protocol"),
806 P_("The id of the protocol to use, or -1 for unknown"),
807 G_TYPE_SOCKET_PROTOCOL,
808 G_SOCKET_PROTOCOL_UNKNOWN,
809 G_PARAM_CONSTRUCT_ONLY |
811 G_PARAM_STATIC_STRINGS));
813 g_object_class_install_property (gobject_class, PROP_FD,
814 g_param_spec_int ("fd",
815 P_("File descriptor"),
816 P_("The sockets file descriptor"),
820 G_PARAM_CONSTRUCT_ONLY |
822 G_PARAM_STATIC_STRINGS));
824 g_object_class_install_property (gobject_class, PROP_BLOCKING,
825 g_param_spec_boolean ("blocking",
827 P_("Whether or not I/O on this socket is blocking"),
830 G_PARAM_STATIC_STRINGS));
832 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
833 g_param_spec_int ("listen-backlog",
834 P_("Listen backlog"),
835 P_("Outstanding connections in the listen queue"),
840 G_PARAM_STATIC_STRINGS));
842 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
843 g_param_spec_boolean ("keepalive",
844 P_("Keep connection alive"),
845 P_("Keep connection alive by sending periodic pings"),
848 G_PARAM_STATIC_STRINGS));
850 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
851 g_param_spec_object ("local-address",
853 P_("The local address the socket is bound to"),
854 G_TYPE_SOCKET_ADDRESS,
856 G_PARAM_STATIC_STRINGS));
858 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
859 g_param_spec_object ("remote-address",
860 P_("Remote address"),
861 P_("The remote address the socket is connected to"),
862 G_TYPE_SOCKET_ADDRESS,
864 G_PARAM_STATIC_STRINGS));
869 * The timeout in seconds on socket I/O
873 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
874 g_param_spec_uint ("timeout",
876 P_("The timeout in seconds on socket I/O"),
881 G_PARAM_STATIC_STRINGS));
886 * Whether the socket should allow sending to broadcast addresses.
890 g_object_class_install_property (gobject_class, PROP_BROADCAST,
891 g_param_spec_boolean ("broadcast",
893 P_("Whether to allow sending to broadcast addresses"),
896 G_PARAM_STATIC_STRINGS));
901 * Time-to-live for outgoing unicast packets
905 g_object_class_install_property (gobject_class, PROP_TTL,
906 g_param_spec_uint ("ttl",
908 P_("Time-to-live of outgoing unicast packets"),
911 G_PARAM_STATIC_STRINGS));
914 * GSocket:multicast-loopback:
916 * Whether outgoing multicast packets loop back to the local host.
920 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
921 g_param_spec_boolean ("multicast-loopback",
922 P_("Multicast loopback"),
923 P_("Whether outgoing multicast packets loop back to the local host"),
926 G_PARAM_STATIC_STRINGS));
929 * GSocket:multicast-ttl:
931 * Time-to-live out outgoing multicast packets
935 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
936 g_param_spec_uint ("multicast-ttl",
938 P_("Time-to-live of outgoing multicast packets"),
941 G_PARAM_STATIC_STRINGS));
945 g_socket_initable_iface_init (GInitableIface *iface)
947 iface->init = g_socket_initable_init;
951 g_socket_init (GSocket *socket)
953 socket->priv = g_socket_get_instance_private (socket);
955 socket->priv->fd = -1;
956 socket->priv->blocking = TRUE;
957 socket->priv->listen_backlog = 10;
958 socket->priv->construct_error = NULL;
960 socket->priv->event = WSA_INVALID_EVENT;
961 g_mutex_init (&socket->priv->win32_source_lock);
966 g_socket_initable_init (GInitable *initable,
967 GCancellable *cancellable,
972 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
974 socket = G_SOCKET (initable);
976 if (cancellable != NULL)
978 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
979 _("Cancellable initialization not supported"));
983 socket->priv->inited = TRUE;
985 if (socket->priv->construct_error)
988 *error = g_error_copy (socket->priv->construct_error);
998 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
999 * @type: the socket type to use.
1000 * @protocol: the id of the protocol to use, or 0 for default.
1001 * @error: #GError for error reporting, or %NULL to ignore.
1003 * Creates a new #GSocket with the defined family, type and protocol.
1004 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1005 * for the family and type is used.
1007 * The @protocol is a family and type specific int that specifies what
1008 * kind of protocol to use. #GSocketProtocol lists several common ones.
1009 * Many families only support one protocol, and use 0 for this, others
1010 * support several and using 0 means to use the default protocol for
1011 * the family and type.
1013 * The protocol id is passed directly to the operating
1014 * system, so you can use protocols not listed in #GSocketProtocol if you
1015 * know the protocol number used for it.
1017 * Returns: a #GSocket or %NULL on error.
1018 * Free the returned object with g_object_unref().
1023 g_socket_new (GSocketFamily family,
1025 GSocketProtocol protocol,
1028 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1032 "protocol", protocol,
1037 * g_socket_new_from_fd:
1038 * @fd: a native socket file descriptor.
1039 * @error: #GError for error reporting, or %NULL to ignore.
1041 * Creates a new #GSocket from a native file descriptor
1042 * or winsock SOCKET handle.
1044 * This reads all the settings from the file descriptor so that
1045 * all properties should work. Note that the file descriptor
1046 * will be set to non-blocking mode, independent on the blocking
1047 * mode of the #GSocket.
1049 * Returns: a #GSocket or %NULL on error.
1050 * Free the returned object with g_object_unref().
1055 g_socket_new_from_fd (gint fd,
1058 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1065 * g_socket_set_blocking:
1066 * @socket: a #GSocket.
1067 * @blocking: Whether to use blocking I/O or not.
1069 * Sets the blocking mode of the socket. In blocking mode
1070 * all operations block until they succeed or there is an error. In
1071 * non-blocking mode all functions return results immediately or
1072 * with a %G_IO_ERROR_WOULD_BLOCK error.
1074 * All sockets are created in blocking mode. However, note that the
1075 * platform level socket is always non-blocking, and blocking mode
1076 * is a GSocket level feature.
1081 g_socket_set_blocking (GSocket *socket,
1084 g_return_if_fail (G_IS_SOCKET (socket));
1086 blocking = !!blocking;
1088 if (socket->priv->blocking == blocking)
1091 socket->priv->blocking = blocking;
1092 g_object_notify (G_OBJECT (socket), "blocking");
1096 * g_socket_get_blocking:
1097 * @socket: a #GSocket.
1099 * Gets the blocking mode of the socket. For details on blocking I/O,
1100 * see g_socket_set_blocking().
1102 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1107 g_socket_get_blocking (GSocket *socket)
1109 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1111 return socket->priv->blocking;
1115 * g_socket_set_keepalive:
1116 * @socket: a #GSocket.
1117 * @keepalive: Value for the keepalive flag
1119 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1120 * this flag is set on a socket, the system will attempt to verify that the
1121 * remote socket endpoint is still present if a sufficiently long period of
1122 * time passes with no data being exchanged. If the system is unable to
1123 * verify the presence of the remote endpoint, it will automatically close
1126 * This option is only functional on certain kinds of sockets. (Notably,
1127 * %G_SOCKET_PROTOCOL_TCP sockets.)
1129 * The exact time between pings is system- and protocol-dependent, but will
1130 * normally be at least two hours. Most commonly, you would set this flag
1131 * on a server socket if you want to allow clients to remain idle for long
1132 * periods of time, but also want to ensure that connections are eventually
1133 * garbage-collected if clients crash or become unreachable.
1138 g_socket_set_keepalive (GSocket *socket,
1141 GError *error = NULL;
1143 g_return_if_fail (G_IS_SOCKET (socket));
1145 keepalive = !!keepalive;
1146 if (socket->priv->keepalive == keepalive)
1149 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1152 g_warning ("error setting keepalive: %s", error->message);
1153 g_error_free (error);
1157 socket->priv->keepalive = keepalive;
1158 g_object_notify (G_OBJECT (socket), "keepalive");
1162 * g_socket_get_keepalive:
1163 * @socket: a #GSocket.
1165 * Gets the keepalive mode of the socket. For details on this,
1166 * see g_socket_set_keepalive().
1168 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1173 g_socket_get_keepalive (GSocket *socket)
1175 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1177 return socket->priv->keepalive;
1181 * g_socket_get_listen_backlog:
1182 * @socket: a #GSocket.
1184 * Gets the listen backlog setting of the socket. For details on this,
1185 * see g_socket_set_listen_backlog().
1187 * Returns: the maximum number of pending connections.
1192 g_socket_get_listen_backlog (GSocket *socket)
1194 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1196 return socket->priv->listen_backlog;
1200 * g_socket_set_listen_backlog:
1201 * @socket: a #GSocket.
1202 * @backlog: the maximum number of pending connections.
1204 * Sets the maximum number of outstanding connections allowed
1205 * when listening on this socket. If more clients than this are
1206 * connecting to the socket and the application is not handling them
1207 * on time then the new connections will be refused.
1209 * Note that this must be called before g_socket_listen() and has no
1210 * effect if called after that.
1215 g_socket_set_listen_backlog (GSocket *socket,
1218 g_return_if_fail (G_IS_SOCKET (socket));
1219 g_return_if_fail (!socket->priv->listening);
1221 if (backlog != socket->priv->listen_backlog)
1223 socket->priv->listen_backlog = backlog;
1224 g_object_notify (G_OBJECT (socket), "listen-backlog");
1229 * g_socket_get_timeout:
1230 * @socket: a #GSocket.
1232 * Gets the timeout setting of the socket. For details on this, see
1233 * g_socket_set_timeout().
1235 * Returns: the timeout in seconds
1240 g_socket_get_timeout (GSocket *socket)
1242 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1244 return socket->priv->timeout;
1248 * g_socket_set_timeout:
1249 * @socket: a #GSocket.
1250 * @timeout: the timeout for @socket, in seconds, or 0 for none
1252 * Sets the time in seconds after which I/O operations on @socket will
1253 * time out if they have not yet completed.
1255 * On a blocking socket, this means that any blocking #GSocket
1256 * operation will time out after @timeout seconds of inactivity,
1257 * returning %G_IO_ERROR_TIMED_OUT.
1259 * On a non-blocking socket, calls to g_socket_condition_wait() will
1260 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1261 * created with g_socket_create_source() will trigger after
1262 * @timeout seconds of inactivity, with the requested condition
1263 * set, at which point calling g_socket_receive(), g_socket_send(),
1264 * g_socket_check_connect_result(), etc, will fail with
1265 * %G_IO_ERROR_TIMED_OUT.
1267 * If @timeout is 0 (the default), operations will never time out
1270 * Note that if an I/O operation is interrupted by a signal, this may
1271 * cause the timeout to be reset.
1276 g_socket_set_timeout (GSocket *socket,
1279 g_return_if_fail (G_IS_SOCKET (socket));
1281 if (timeout != socket->priv->timeout)
1283 socket->priv->timeout = timeout;
1284 g_object_notify (G_OBJECT (socket), "timeout");
1290 * @socket: a #GSocket.
1292 * Gets the unicast time-to-live setting on @socket; see
1293 * g_socket_set_ttl() for more details.
1295 * Returns: the time-to-live setting on @socket
1300 g_socket_get_ttl (GSocket *socket)
1302 GError *error = NULL;
1305 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1307 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1309 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1312 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1314 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1318 g_return_val_if_reached (0);
1322 g_warning ("error getting unicast ttl: %s", error->message);
1323 g_error_free (error);
1332 * @socket: a #GSocket.
1333 * @ttl: the time-to-live value for all unicast packets on @socket
1335 * Sets the time-to-live for outgoing unicast packets on @socket.
1336 * By default the platform-specific default value is used.
1341 g_socket_set_ttl (GSocket *socket,
1344 GError *error = NULL;
1346 g_return_if_fail (G_IS_SOCKET (socket));
1348 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1350 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1353 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1355 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1357 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1361 g_return_if_reached ();
1365 g_warning ("error setting unicast ttl: %s", error->message);
1366 g_error_free (error);
1370 g_object_notify (G_OBJECT (socket), "ttl");
1374 * g_socket_get_broadcast:
1375 * @socket: a #GSocket.
1377 * Gets the broadcast setting on @socket; if %TRUE,
1378 * it is possible to send packets to broadcast
1381 * Returns: the broadcast setting on @socket
1386 g_socket_get_broadcast (GSocket *socket)
1388 GError *error = NULL;
1391 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1393 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1396 g_warning ("error getting broadcast: %s", error->message);
1397 g_error_free (error);
1405 * g_socket_set_broadcast:
1406 * @socket: a #GSocket.
1407 * @broadcast: whether @socket should allow sending to broadcast
1410 * Sets whether @socket should allow sending to broadcast addresses.
1411 * This is %FALSE by default.
1416 g_socket_set_broadcast (GSocket *socket,
1419 GError *error = NULL;
1421 g_return_if_fail (G_IS_SOCKET (socket));
1423 broadcast = !!broadcast;
1425 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1428 g_warning ("error setting broadcast: %s", error->message);
1429 g_error_free (error);
1433 g_object_notify (G_OBJECT (socket), "broadcast");
1437 * g_socket_get_multicast_loopback:
1438 * @socket: a #GSocket.
1440 * Gets the multicast loopback setting on @socket; if %TRUE (the
1441 * default), outgoing multicast packets will be looped back to
1442 * multicast listeners on the same host.
1444 * Returns: the multicast loopback setting on @socket
1449 g_socket_get_multicast_loopback (GSocket *socket)
1451 GError *error = NULL;
1454 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1456 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1458 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1461 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1463 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1467 g_return_val_if_reached (FALSE);
1471 g_warning ("error getting multicast loopback: %s", error->message);
1472 g_error_free (error);
1480 * g_socket_set_multicast_loopback:
1481 * @socket: a #GSocket.
1482 * @loopback: whether @socket should receive messages sent to its
1483 * multicast groups from the local host
1485 * Sets whether outgoing multicast packets will be received by sockets
1486 * listening on that multicast address on the same host. This is %TRUE
1492 g_socket_set_multicast_loopback (GSocket *socket,
1495 GError *error = NULL;
1497 g_return_if_fail (G_IS_SOCKET (socket));
1499 loopback = !!loopback;
1501 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1503 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1506 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1508 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1510 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1514 g_return_if_reached ();
1518 g_warning ("error setting multicast loopback: %s", error->message);
1519 g_error_free (error);
1523 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1527 * g_socket_get_multicast_ttl:
1528 * @socket: a #GSocket.
1530 * Gets the multicast time-to-live setting on @socket; see
1531 * g_socket_set_multicast_ttl() for more details.
1533 * Returns: the multicast time-to-live setting on @socket
1538 g_socket_get_multicast_ttl (GSocket *socket)
1540 GError *error = NULL;
1543 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1545 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1547 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1550 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1552 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1556 g_return_val_if_reached (FALSE);
1560 g_warning ("error getting multicast ttl: %s", error->message);
1561 g_error_free (error);
1569 * g_socket_set_multicast_ttl:
1570 * @socket: a #GSocket.
1571 * @ttl: the time-to-live value for all multicast datagrams on @socket
1573 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1574 * By default, this is 1, meaning that multicast packets will not leave
1575 * the local network.
1580 g_socket_set_multicast_ttl (GSocket *socket,
1583 GError *error = NULL;
1585 g_return_if_fail (G_IS_SOCKET (socket));
1587 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1589 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1592 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1594 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1596 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1600 g_return_if_reached ();
1604 g_warning ("error setting multicast ttl: %s", error->message);
1605 g_error_free (error);
1609 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1613 * g_socket_get_family:
1614 * @socket: a #GSocket.
1616 * Gets the socket family of the socket.
1618 * Returns: a #GSocketFamily
1623 g_socket_get_family (GSocket *socket)
1625 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1627 return socket->priv->family;
1631 * g_socket_get_socket_type:
1632 * @socket: a #GSocket.
1634 * Gets the socket type of the socket.
1636 * Returns: a #GSocketType
1641 g_socket_get_socket_type (GSocket *socket)
1643 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1645 return socket->priv->type;
1649 * g_socket_get_protocol:
1650 * @socket: a #GSocket.
1652 * Gets the socket protocol id the socket was created with.
1653 * In case the protocol is unknown, -1 is returned.
1655 * Returns: a protocol id, or -1 if unknown
1660 g_socket_get_protocol (GSocket *socket)
1662 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1664 return socket->priv->protocol;
1669 * @socket: a #GSocket.
1671 * Returns the underlying OS socket object. On unix this
1672 * is a socket file descriptor, and on Windows this is
1673 * a Winsock2 SOCKET handle. This may be useful for
1674 * doing platform specific or otherwise unusual operations
1677 * Returns: the file descriptor of the socket.
1682 g_socket_get_fd (GSocket *socket)
1684 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1686 return socket->priv->fd;
1690 * g_socket_get_local_address:
1691 * @socket: a #GSocket.
1692 * @error: #GError for error reporting, or %NULL to ignore.
1694 * Try to get the local address of a bound socket. This is only
1695 * useful if the socket has been bound to a local address,
1696 * either explicitly or implicitly when connecting.
1698 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1699 * Free the returned object with g_object_unref().
1704 g_socket_get_local_address (GSocket *socket,
1707 struct sockaddr_storage buffer;
1708 guint len = sizeof (buffer);
1710 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1712 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1714 int errsv = get_socket_errno ();
1715 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1716 _("could not get local address: %s"), socket_strerror (errsv));
1720 return g_socket_address_new_from_native (&buffer, len);
1724 * g_socket_get_remote_address:
1725 * @socket: a #GSocket.
1726 * @error: #GError for error reporting, or %NULL to ignore.
1728 * Try to get the remove address of a connected socket. This is only
1729 * useful for connection oriented sockets that have been connected.
1731 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1732 * Free the returned object with g_object_unref().
1737 g_socket_get_remote_address (GSocket *socket,
1740 struct sockaddr_storage buffer;
1741 guint len = sizeof (buffer);
1743 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1745 if (socket->priv->connect_pending)
1747 if (!g_socket_check_connect_result (socket, error))
1750 socket->priv->connect_pending = FALSE;
1753 if (!socket->priv->remote_address)
1755 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1757 int errsv = get_socket_errno ();
1758 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1759 _("could not get remote address: %s"), socket_strerror (errsv));
1763 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1766 return g_object_ref (socket->priv->remote_address);
1770 * g_socket_is_connected:
1771 * @socket: a #GSocket.
1773 * Check whether the socket is connected. This is only useful for
1774 * connection-oriented sockets.
1776 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1781 g_socket_is_connected (GSocket *socket)
1783 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1785 return socket->priv->connected;
1790 * @socket: a #GSocket.
1791 * @error: #GError for error reporting, or %NULL to ignore.
1793 * Marks the socket as a server socket, i.e. a socket that is used
1794 * to accept incoming requests using g_socket_accept().
1796 * Before calling this the socket must be bound to a local address using
1799 * To set the maximum amount of outstanding clients, use
1800 * g_socket_set_listen_backlog().
1802 * Returns: %TRUE on success, %FALSE on error.
1807 g_socket_listen (GSocket *socket,
1810 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1812 if (!check_socket (socket, error))
1815 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1817 int errsv = get_socket_errno ();
1819 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1820 _("could not listen: %s"), socket_strerror (errsv));
1824 socket->priv->listening = TRUE;
1831 * @socket: a #GSocket.
1832 * @address: a #GSocketAddress specifying the local address.
1833 * @allow_reuse: whether to allow reusing this address
1834 * @error: #GError for error reporting, or %NULL to ignore.
1836 * When a socket is created it is attached to an address family, but it
1837 * doesn't have an address in this family. g_socket_bind() assigns the
1838 * address (sometimes called name) of the socket.
1840 * It is generally required to bind to a local address before you can
1841 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1842 * In certain situations, you may also want to bind a socket that will be
1843 * used to initiate connections, though this is not normally required.
1845 * If @socket is a TCP socket, then @allow_reuse controls the setting
1846 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
1847 * server sockets (sockets that you will eventually call
1848 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
1849 * set this flag on a server socket may cause g_socket_bind() to return
1850 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
1851 * immediately restarted.)
1853 * If @socket is a UDP socket, then @allow_reuse determines whether or
1854 * not other UDP sockets can be bound to the same address at the same
1855 * time. In particular, you can have several UDP sockets bound to the
1856 * same address, and they will all receive all of the multicast and
1857 * broadcast packets sent to that address. (The behavior of unicast
1858 * UDP packets to an address with multiple listeners is not defined.)
1860 * Returns: %TRUE on success, %FALSE on error.
1865 g_socket_bind (GSocket *socket,
1866 GSocketAddress *address,
1867 gboolean reuse_address,
1870 struct sockaddr_storage addr;
1871 gboolean so_reuseaddr;
1873 gboolean so_reuseport;
1876 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1878 if (!check_socket (socket, error))
1881 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1884 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
1885 * sockets, but has nasty side effects we don't want for TCP
1888 * On other platforms, we set SO_REUSEPORT, if it exists, for
1889 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
1890 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
1891 * the desired semantics on UDP (as it does on Linux, although
1892 * Linux has SO_REUSEPORT too as of 3.9).
1896 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1898 so_reuseaddr = !!reuse_address;
1902 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1905 /* Ignore errors here, the only likely error is "not supported", and
1906 * this is a "best effort" thing mainly.
1908 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
1910 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
1913 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1914 g_socket_address_get_native_size (address)) < 0)
1916 int errsv = get_socket_errno ();
1918 G_IO_ERROR, socket_io_error_from_errno (errsv),
1919 _("Error binding to address: %s"), socket_strerror (errsv));
1926 #if !defined(HAVE_IF_NAMETOINDEX) && defined(G_OS_WIN32)
1928 if_nametoindex (const gchar *iface)
1930 PIP_ADAPTER_ADDRESSES addresses = NULL, p;
1931 gulong addresses_len = 0;
1935 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, NULL, &addresses_len);
1936 if (res != NO_ERROR && res != ERROR_BUFFER_OVERFLOW)
1938 if (res == ERROR_NO_DATA)
1945 addresses = g_malloc (addresses_len);
1946 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, addresses, &addresses_len);
1948 if (res != NO_ERROR)
1951 if (res == ERROR_NO_DATA)
1961 if (strcmp (p->AdapterName, iface) == 0)
1977 #define HAVE_IF_NAMETOINDEX 1
1981 g_socket_multicast_group_operation (GSocket *socket,
1982 GInetAddress *group,
1983 gboolean source_specific,
1985 gboolean join_group,
1988 const guint8 *native_addr;
1989 gint optname, result;
1991 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1992 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
1993 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
1995 if (!check_socket (socket, error))
1998 native_addr = g_inet_address_to_bytes (group);
1999 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2001 #ifdef HAVE_IP_MREQN
2002 struct ip_mreqn mc_req;
2004 struct ip_mreq mc_req;
2007 memset (&mc_req, 0, sizeof (mc_req));
2008 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2010 #ifdef HAVE_IP_MREQN
2012 mc_req.imr_ifindex = if_nametoindex (iface);
2014 mc_req.imr_ifindex = 0; /* Pick any. */
2015 #elif defined(G_OS_WIN32)
2017 mc_req.imr_interface.s_addr = g_htonl (if_nametoindex (iface));
2019 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2021 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2024 if (source_specific)
2026 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2027 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2029 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2031 _("Error joining multicast group: %s") :
2032 _("Error leaving multicast group: %s"),
2033 _("No support for source-specific multicast"));
2038 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2039 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2040 &mc_req, sizeof (mc_req));
2042 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2044 struct ipv6_mreq mc_req_ipv6;
2046 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2047 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2048 #ifdef HAVE_IF_NAMETOINDEX
2050 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2053 mc_req_ipv6.ipv6mr_interface = 0;
2055 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2056 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2057 &mc_req_ipv6, sizeof (mc_req_ipv6));
2060 g_return_val_if_reached (FALSE);
2064 int errsv = get_socket_errno ();
2066 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2068 _("Error joining multicast group: %s") :
2069 _("Error leaving multicast group: %s"),
2070 socket_strerror (errsv));
2078 * g_socket_join_multicast_group:
2079 * @socket: a #GSocket.
2080 * @group: a #GInetAddress specifying the group address to join.
2081 * @iface: (allow-none): Name of the interface to use, or %NULL
2082 * @source_specific: %TRUE if source-specific multicast should be used
2083 * @error: #GError for error reporting, or %NULL to ignore.
2085 * Registers @socket to receive multicast messages sent to @group.
2086 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2087 * been bound to an appropriate interface and port with
2090 * If @iface is %NULL, the system will automatically pick an interface
2091 * to bind to based on @group.
2093 * If @source_specific is %TRUE, source-specific multicast as defined
2094 * in RFC 4604 is used. Note that on older platforms this may fail
2095 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2097 * Returns: %TRUE on success, %FALSE on error.
2102 g_socket_join_multicast_group (GSocket *socket,
2103 GInetAddress *group,
2104 gboolean source_specific,
2108 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2112 * g_socket_leave_multicast_group:
2113 * @socket: a #GSocket.
2114 * @group: a #GInetAddress specifying the group address to leave.
2115 * @iface: (allow-none): Interface used
2116 * @source_specific: %TRUE if source-specific multicast was used
2117 * @error: #GError for error reporting, or %NULL to ignore.
2119 * Removes @socket from the multicast group defined by @group, @iface,
2120 * and @source_specific (which must all have the same values they had
2121 * when you joined the group).
2123 * @socket remains bound to its address and port, and can still receive
2124 * unicast messages after calling this.
2126 * Returns: %TRUE on success, %FALSE on error.
2131 g_socket_leave_multicast_group (GSocket *socket,
2132 GInetAddress *group,
2133 gboolean source_specific,
2137 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2141 * g_socket_speaks_ipv4:
2142 * @socket: a #GSocket
2144 * Checks if a socket is capable of speaking IPv4.
2146 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2147 * and under some combinations of circumstances IPv6 sockets are also
2148 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2151 * No other types of sockets are currently considered as being capable
2154 * Returns: %TRUE if this socket can be used with IPv4.
2159 g_socket_speaks_ipv4 (GSocket *socket)
2161 switch (socket->priv->family)
2163 case G_SOCKET_FAMILY_IPV4:
2166 case G_SOCKET_FAMILY_IPV6:
2167 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2171 if (!g_socket_get_option (socket,
2172 IPPROTO_IPV6, IPV6_V6ONLY,
2189 * @socket: a #GSocket.
2190 * @cancellable: (allow-none): a %GCancellable or %NULL
2191 * @error: #GError for error reporting, or %NULL to ignore.
2193 * Accept incoming connections on a connection-based socket. This removes
2194 * the first outstanding connection request from the listening socket and
2195 * creates a #GSocket object for it.
2197 * The @socket must be bound to a local address with g_socket_bind() and
2198 * must be listening for incoming connections (g_socket_listen()).
2200 * If there are no outstanding connections then the operation will block
2201 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2202 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2204 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2205 * Free the returned object with g_object_unref().
2210 g_socket_accept (GSocket *socket,
2211 GCancellable *cancellable,
2214 GSocket *new_socket;
2217 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2219 if (!check_socket (socket, error))
2222 if (!check_timeout (socket, error))
2227 if (socket->priv->blocking &&
2228 !g_socket_condition_wait (socket,
2229 G_IO_IN, cancellable, error))
2232 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2234 int errsv = get_socket_errno ();
2236 win32_unset_event_mask (socket, FD_ACCEPT);
2241 if (socket->priv->blocking)
2243 #ifdef WSAEWOULDBLOCK
2244 if (errsv == WSAEWOULDBLOCK)
2247 if (errsv == EWOULDBLOCK ||
2253 g_set_error (error, G_IO_ERROR,
2254 socket_io_error_from_errno (errsv),
2255 _("Error accepting connection: %s"), socket_strerror (errsv));
2261 win32_unset_event_mask (socket, FD_ACCEPT);
2265 /* The socket inherits the accepting sockets event mask and even object,
2266 we need to remove that */
2267 WSAEventSelect (ret, NULL, 0);
2273 /* We always want to set close-on-exec to protect users. If you
2274 need to so some weird inheritance to exec you can re-enable this
2275 using lower level hacks with g_socket_get_fd(). */
2276 flags = fcntl (ret, F_GETFD, 0);
2278 (flags & FD_CLOEXEC) == 0)
2280 flags |= FD_CLOEXEC;
2281 fcntl (ret, F_SETFD, flags);
2286 new_socket = g_socket_new_from_fd (ret, error);
2287 if (new_socket == NULL)
2296 new_socket->priv->protocol = socket->priv->protocol;
2303 * @socket: a #GSocket.
2304 * @address: a #GSocketAddress specifying the remote address.
2305 * @cancellable: (allow-none): a %GCancellable or %NULL
2306 * @error: #GError for error reporting, or %NULL to ignore.
2308 * Connect the socket to the specified remote address.
2310 * For connection oriented socket this generally means we attempt to make
2311 * a connection to the @address. For a connection-less socket it sets
2312 * the default address for g_socket_send() and discards all incoming datagrams
2313 * from other sources.
2315 * Generally connection oriented sockets can only connect once, but
2316 * connection-less sockets can connect multiple times to change the
2319 * If the connect call needs to do network I/O it will block, unless
2320 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2321 * and the user can be notified of the connection finishing by waiting
2322 * for the G_IO_OUT condition. The result of the connection must then be
2323 * checked with g_socket_check_connect_result().
2325 * Returns: %TRUE if connected, %FALSE on error.
2330 g_socket_connect (GSocket *socket,
2331 GSocketAddress *address,
2332 GCancellable *cancellable,
2335 struct sockaddr_storage buffer;
2337 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2339 if (!check_socket (socket, error))
2342 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2345 if (socket->priv->remote_address)
2346 g_object_unref (socket->priv->remote_address);
2347 socket->priv->remote_address = g_object_ref (address);
2351 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2352 g_socket_address_get_native_size (address)) < 0)
2354 int errsv = get_socket_errno ();
2360 if (errsv == EINPROGRESS)
2362 if (errsv == WSAEWOULDBLOCK)
2365 if (socket->priv->blocking)
2367 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2369 if (g_socket_check_connect_result (socket, error))
2375 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2376 _("Connection in progress"));
2377 socket->priv->connect_pending = TRUE;
2381 g_set_error_literal (error, G_IO_ERROR,
2382 socket_io_error_from_errno (errsv),
2383 socket_strerror (errsv));
2390 win32_unset_event_mask (socket, FD_CONNECT);
2392 socket->priv->connected = TRUE;
2398 * g_socket_check_connect_result:
2399 * @socket: a #GSocket
2400 * @error: #GError for error reporting, or %NULL to ignore.
2402 * Checks and resets the pending connect error for the socket.
2403 * This is used to check for errors when g_socket_connect() is
2404 * used in non-blocking mode.
2406 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2411 g_socket_check_connect_result (GSocket *socket,
2416 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2418 if (!check_socket (socket, error))
2421 if (!check_timeout (socket, error))
2424 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
2426 g_prefix_error (error, _("Unable to get pending error: "));
2432 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2433 socket_strerror (value));
2434 if (socket->priv->remote_address)
2436 g_object_unref (socket->priv->remote_address);
2437 socket->priv->remote_address = NULL;
2442 socket->priv->connected = TRUE;
2447 * g_socket_get_available_bytes:
2448 * @socket: a #GSocket
2450 * Get the amount of data pending in the OS input buffer.
2452 * If @socket is a UDP or SCTP socket, this will return the size of
2453 * just the next packet, even if additional packets are buffered after
2456 * Note that on Windows, this function is rather inefficient in the
2457 * UDP case, and so if you know any plausible upper bound on the size
2458 * of the incoming packet, it is better to just do a
2459 * g_socket_receive() with a buffer of that size, rather than calling
2460 * g_socket_get_available_bytes() first and then doing a receive of
2461 * exactly the right size.
2463 * Returns: the number of bytes that can be read from the socket
2464 * without blocking or truncating, or -1 on error.
2469 g_socket_get_available_bytes (GSocket *socket)
2472 const gint bufsize = 64 * 1024;
2473 static guchar *buf = NULL;
2479 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2481 #if defined (SO_NREAD)
2482 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
2484 #elif !defined (G_OS_WIN32)
2485 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2488 if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
2490 if (G_UNLIKELY (g_once_init_enter (&buf)))
2491 g_once_init_leave (&buf, g_malloc (bufsize));
2493 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
2494 if (avail == -1 && get_socket_errno () == WSAEWOULDBLOCK)
2499 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
2509 * @socket: a #GSocket
2510 * @buffer: (array length=size) (element-type guint8): a buffer to
2511 * read data into (which should be at least @size bytes long).
2512 * @size: the number of bytes you want to read from the socket
2513 * @cancellable: (allow-none): a %GCancellable or %NULL
2514 * @error: #GError for error reporting, or %NULL to ignore.
2516 * Receive data (up to @size bytes) from a socket. This is mainly used by
2517 * connection-oriented sockets; it is identical to g_socket_receive_from()
2518 * with @address set to %NULL.
2520 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2521 * g_socket_receive() will always read either 0 or 1 complete messages from
2522 * the socket. If the received message is too large to fit in @buffer, then
2523 * the data beyond @size bytes will be discarded, without any explicit
2524 * indication that this has occurred.
2526 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2527 * number of bytes, up to @size. If more than @size bytes have been
2528 * received, the additional data will be returned in future calls to
2529 * g_socket_receive().
2531 * If the socket is in blocking mode the call will block until there
2532 * is some data to receive, the connection is closed, or there is an
2533 * error. If there is no data available and the socket is in
2534 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2535 * returned. To be notified when data is available, wait for the
2536 * %G_IO_IN condition.
2538 * On error -1 is returned and @error is set accordingly.
2540 * Returns: Number of bytes read, or 0 if the connection was closed by
2541 * the peer, or -1 on error
2546 g_socket_receive (GSocket *socket,
2549 GCancellable *cancellable,
2552 return g_socket_receive_with_blocking (socket, buffer, size,
2553 socket->priv->blocking,
2554 cancellable, error);
2558 * g_socket_receive_with_blocking:
2559 * @socket: a #GSocket
2560 * @buffer: (array length=size) (element-type guint8): a buffer to
2561 * read data into (which should be at least @size bytes long).
2562 * @size: the number of bytes you want to read from the socket
2563 * @blocking: whether to do blocking or non-blocking I/O
2564 * @cancellable: (allow-none): a %GCancellable or %NULL
2565 * @error: #GError for error reporting, or %NULL to ignore.
2567 * This behaves exactly the same as g_socket_receive(), except that
2568 * the choice of blocking or non-blocking behavior is determined by
2569 * the @blocking argument rather than by @socket's properties.
2571 * Returns: Number of bytes read, or 0 if the connection was closed by
2572 * the peer, or -1 on error
2577 g_socket_receive_with_blocking (GSocket *socket,
2581 GCancellable *cancellable,
2586 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2588 if (!check_socket (socket, error))
2591 if (!check_timeout (socket, error))
2594 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2600 !g_socket_condition_wait (socket,
2601 G_IO_IN, cancellable, error))
2604 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2606 int errsv = get_socket_errno ();
2613 #ifdef WSAEWOULDBLOCK
2614 if (errsv == WSAEWOULDBLOCK)
2617 if (errsv == EWOULDBLOCK ||
2623 win32_unset_event_mask (socket, FD_READ);
2625 g_set_error (error, G_IO_ERROR,
2626 socket_io_error_from_errno (errsv),
2627 _("Error receiving data: %s"), socket_strerror (errsv));
2631 win32_unset_event_mask (socket, FD_READ);
2640 * g_socket_receive_from:
2641 * @socket: a #GSocket
2642 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2644 * @buffer: (array length=size) (element-type guint8): a buffer to
2645 * read data into (which should be at least @size bytes long).
2646 * @size: the number of bytes you want to read from the socket
2647 * @cancellable: (allow-none): a %GCancellable or %NULL
2648 * @error: #GError for error reporting, or %NULL to ignore.
2650 * Receive data (up to @size bytes) from a socket.
2652 * If @address is non-%NULL then @address will be set equal to the
2653 * source address of the received packet.
2654 * @address is owned by the caller.
2656 * See g_socket_receive() for additional information.
2658 * Returns: Number of bytes read, or 0 if the connection was closed by
2659 * the peer, or -1 on error
2664 g_socket_receive_from (GSocket *socket,
2665 GSocketAddress **address,
2668 GCancellable *cancellable,
2676 return g_socket_receive_message (socket,
2684 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2685 * one, which can be confusing and annoying. So if possible, we want
2686 * to suppress the signal entirely.
2689 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2691 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2696 * @socket: a #GSocket
2697 * @buffer: (array length=size) (element-type guint8): the buffer
2698 * containing the data to send.
2699 * @size: the number of bytes to send
2700 * @cancellable: (allow-none): a %GCancellable or %NULL
2701 * @error: #GError for error reporting, or %NULL to ignore.
2703 * Tries to send @size bytes from @buffer on the socket. This is
2704 * mainly used by connection-oriented sockets; it is identical to
2705 * g_socket_send_to() with @address set to %NULL.
2707 * If the socket is in blocking mode the call will block until there is
2708 * space for the data in the socket queue. If there is no space available
2709 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2710 * will be returned. To be notified when space is available, wait for the
2711 * %G_IO_OUT condition. Note though that you may still receive
2712 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2713 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2714 * very common due to the way the underlying APIs work.)
2716 * On error -1 is returned and @error is set accordingly.
2718 * Returns: Number of bytes written (which may be less than @size), or -1
2724 g_socket_send (GSocket *socket,
2725 const gchar *buffer,
2727 GCancellable *cancellable,
2730 return g_socket_send_with_blocking (socket, buffer, size,
2731 socket->priv->blocking,
2732 cancellable, error);
2736 * g_socket_send_with_blocking:
2737 * @socket: a #GSocket
2738 * @buffer: (array length=size) (element-type guint8): the buffer
2739 * containing the data to send.
2740 * @size: the number of bytes to send
2741 * @blocking: whether to do blocking or non-blocking I/O
2742 * @cancellable: (allow-none): a %GCancellable or %NULL
2743 * @error: #GError for error reporting, or %NULL to ignore.
2745 * This behaves exactly the same as g_socket_send(), except that
2746 * the choice of blocking or non-blocking behavior is determined by
2747 * the @blocking argument rather than by @socket's properties.
2749 * Returns: Number of bytes written (which may be less than @size), or -1
2755 g_socket_send_with_blocking (GSocket *socket,
2756 const gchar *buffer,
2759 GCancellable *cancellable,
2764 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2766 if (!check_socket (socket, error))
2769 if (!check_timeout (socket, error))
2772 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2778 !g_socket_condition_wait (socket,
2779 G_IO_OUT, cancellable, error))
2782 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2784 int errsv = get_socket_errno ();
2789 #ifdef WSAEWOULDBLOCK
2790 if (errsv == WSAEWOULDBLOCK)
2791 win32_unset_event_mask (socket, FD_WRITE);
2796 #ifdef WSAEWOULDBLOCK
2797 if (errsv == WSAEWOULDBLOCK)
2800 if (errsv == EWOULDBLOCK ||
2806 g_set_error (error, G_IO_ERROR,
2807 socket_io_error_from_errno (errsv),
2808 _("Error sending data: %s"), socket_strerror (errsv));
2819 * @socket: a #GSocket
2820 * @address: (allow-none): a #GSocketAddress, or %NULL
2821 * @buffer: (array length=size) (element-type guint8): the buffer
2822 * containing the data to send.
2823 * @size: the number of bytes to send
2824 * @cancellable: (allow-none): a %GCancellable or %NULL
2825 * @error: #GError for error reporting, or %NULL to ignore.
2827 * Tries to send @size bytes from @buffer to @address. If @address is
2828 * %NULL then the message is sent to the default receiver (set by
2829 * g_socket_connect()).
2831 * See g_socket_send() for additional information.
2833 * Returns: Number of bytes written (which may be less than @size), or -1
2839 g_socket_send_to (GSocket *socket,
2840 GSocketAddress *address,
2841 const gchar *buffer,
2843 GCancellable *cancellable,
2851 return g_socket_send_message (socket,
2861 * g_socket_shutdown:
2862 * @socket: a #GSocket
2863 * @shutdown_read: whether to shut down the read side
2864 * @shutdown_write: whether to shut down the write side
2865 * @error: #GError for error reporting, or %NULL to ignore.
2867 * Shut down part of a full-duplex connection.
2869 * If @shutdown_read is %TRUE then the receiving side of the connection
2870 * is shut down, and further reading is disallowed.
2872 * If @shutdown_write is %TRUE then the sending side of the connection
2873 * is shut down, and further writing is disallowed.
2875 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2877 * One example where this is used is graceful disconnect for TCP connections
2878 * where you close the sending side, then wait for the other side to close
2879 * the connection, thus ensuring that the other side saw all sent data.
2881 * Returns: %TRUE on success, %FALSE on error
2886 g_socket_shutdown (GSocket *socket,
2887 gboolean shutdown_read,
2888 gboolean shutdown_write,
2893 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2895 if (!check_socket (socket, error))
2899 if (!shutdown_read && !shutdown_write)
2903 if (shutdown_read && shutdown_write)
2905 else if (shutdown_read)
2910 if (shutdown_read && shutdown_write)
2912 else if (shutdown_read)
2918 if (shutdown (socket->priv->fd, how) != 0)
2920 int errsv = get_socket_errno ();
2921 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2922 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2926 if (shutdown_read && shutdown_write)
2927 socket->priv->connected = FALSE;
2934 * @socket: a #GSocket
2935 * @error: #GError for error reporting, or %NULL to ignore.
2937 * Closes the socket, shutting down any active connection.
2939 * Closing a socket does not wait for all outstanding I/O operations
2940 * to finish, so the caller should not rely on them to be guaranteed
2941 * to complete even if the close returns with no error.
2943 * Once the socket is closed, all other operations will return
2944 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2947 * Sockets will be automatically closed when the last reference
2948 * is dropped, but you might want to call this function to make sure
2949 * resources are released as early as possible.
2951 * Beware that due to the way that TCP works, it is possible for
2952 * recently-sent data to be lost if either you close a socket while the
2953 * %G_IO_IN condition is set, or else if the remote connection tries to
2954 * send something to you after you close the socket but before it has
2955 * finished reading all of the data you sent. There is no easy generic
2956 * way to avoid this problem; the easiest fix is to design the network
2957 * protocol such that the client will never send data "out of turn".
2958 * Another solution is for the server to half-close the connection by
2959 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2960 * and then wait for the client to notice this and close its side of the
2961 * connection, after which the server can safely call g_socket_close().
2962 * (This is what #GTcpConnection does if you call
2963 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2964 * only works if the client will close its connection after the server
2967 * Returns: %TRUE on success, %FALSE on error
2972 g_socket_close (GSocket *socket,
2977 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2979 if (socket->priv->closed)
2980 return TRUE; /* Multiple close not an error */
2982 if (!check_socket (socket, error))
2988 res = closesocket (socket->priv->fd);
2990 res = close (socket->priv->fd);
2994 int errsv = get_socket_errno ();
2999 g_set_error (error, G_IO_ERROR,
3000 socket_io_error_from_errno (errsv),
3001 _("Error closing socket: %s"),
3002 socket_strerror (errsv));
3008 socket->priv->connected = FALSE;
3009 socket->priv->closed = TRUE;
3010 if (socket->priv->remote_address)
3012 g_object_unref (socket->priv->remote_address);
3013 socket->priv->remote_address = NULL;
3020 * g_socket_is_closed:
3021 * @socket: a #GSocket
3023 * Checks whether a socket is closed.
3025 * Returns: %TRUE if socket is closed, %FALSE otherwise
3030 g_socket_is_closed (GSocket *socket)
3032 return socket->priv->closed;
3036 /* Broken source, used on errors */
3038 broken_dispatch (GSource *source,
3039 GSourceFunc callback,
3045 static GSourceFuncs broken_funcs =
3054 network_events_for_condition (GIOCondition condition)
3058 if (condition & G_IO_IN)
3059 event_mask |= (FD_READ | FD_ACCEPT);
3060 if (condition & G_IO_OUT)
3061 event_mask |= (FD_WRITE | FD_CONNECT);
3062 event_mask |= FD_CLOSE;
3068 ensure_event (GSocket *socket)
3070 if (socket->priv->event == WSA_INVALID_EVENT)
3071 socket->priv->event = WSACreateEvent();
3075 update_select_events (GSocket *socket)
3082 ensure_event (socket);
3085 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3088 event_mask |= network_events_for_condition (*ptr);
3091 if (event_mask != socket->priv->selected_events)
3093 /* If no events selected, disable event so we can unset
3096 if (event_mask == 0)
3099 event = socket->priv->event;
3101 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3102 socket->priv->selected_events = event_mask;
3107 add_condition_watch (GSocket *socket,
3108 GIOCondition *condition)
3110 g_mutex_lock (&socket->priv->win32_source_lock);
3111 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3113 socket->priv->requested_conditions =
3114 g_list_prepend (socket->priv->requested_conditions, condition);
3116 update_select_events (socket);
3117 g_mutex_unlock (&socket->priv->win32_source_lock);
3121 remove_condition_watch (GSocket *socket,
3122 GIOCondition *condition)
3124 g_mutex_lock (&socket->priv->win32_source_lock);
3125 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3127 socket->priv->requested_conditions =
3128 g_list_remove (socket->priv->requested_conditions, condition);
3130 update_select_events (socket);
3131 g_mutex_unlock (&socket->priv->win32_source_lock);
3135 update_condition (GSocket *socket)
3137 WSANETWORKEVENTS events;
3138 GIOCondition condition;
3140 if (WSAEnumNetworkEvents (socket->priv->fd,
3141 socket->priv->event,
3144 socket->priv->current_events |= events.lNetworkEvents;
3145 if (events.lNetworkEvents & FD_WRITE &&
3146 events.iErrorCode[FD_WRITE_BIT] != 0)
3147 socket->priv->current_errors |= FD_WRITE;
3148 if (events.lNetworkEvents & FD_CONNECT &&
3149 events.iErrorCode[FD_CONNECT_BIT] != 0)
3150 socket->priv->current_errors |= FD_CONNECT;
3154 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3155 condition |= G_IO_IN;
3157 if (socket->priv->current_events & FD_CLOSE)
3159 int r, errsv, buffer;
3161 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3163 errsv = get_socket_errno ();
3166 (r < 0 && errsv == WSAENOTCONN))
3167 condition |= G_IO_IN;
3169 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3170 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3171 condition |= G_IO_HUP;
3173 condition |= G_IO_ERR;
3176 if (socket->priv->closed)
3177 condition |= G_IO_HUP;
3179 /* Never report both G_IO_OUT and HUP, these are
3180 mutually exclusive (can't write to a closed socket) */
3181 if ((condition & G_IO_HUP) == 0 &&
3182 socket->priv->current_events & FD_WRITE)
3184 if (socket->priv->current_errors & FD_WRITE)
3185 condition |= G_IO_ERR;
3187 condition |= G_IO_OUT;
3191 if (socket->priv->current_events & FD_CONNECT)
3193 if (socket->priv->current_errors & FD_CONNECT)
3194 condition |= (G_IO_HUP | G_IO_ERR);
3196 condition |= G_IO_OUT;
3212 GIOCondition condition;
3217 socket_source_prepare_win32 (GSource *source,
3220 GSocketSource *socket_source = (GSocketSource *)source;
3224 return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3228 socket_source_check_win32 (GSource *source)
3232 return socket_source_prepare_win32 (source, &timeout);
3237 socket_source_dispatch (GSource *source,
3238 GSourceFunc callback,
3241 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3242 GSocketSource *socket_source = (GSocketSource *)source;
3243 GSocket *socket = socket_source->socket;
3249 events = update_condition (socket_source->socket);
3251 events = g_source_query_unix_fd (source, socket_source->fd_tag);
3254 timeout = g_source_get_ready_time (source);
3255 if (timeout >= 0 && timeout < g_source_get_time (source))
3257 socket->priv->timed_out = TRUE;
3258 events |= (G_IO_IN | G_IO_OUT);
3261 ret = (*func) (socket, events & socket_source->condition, user_data);
3263 if (socket->priv->timeout)
3264 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3266 g_source_set_ready_time (source, -1);
3272 socket_source_finalize (GSource *source)
3274 GSocketSource *socket_source = (GSocketSource *)source;
3277 socket = socket_source->socket;
3280 remove_condition_watch (socket, &socket_source->condition);
3283 g_object_unref (socket);
3287 socket_source_closure_callback (GSocket *socket,
3288 GIOCondition condition,
3291 GClosure *closure = data;
3293 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3294 GValue result_value = G_VALUE_INIT;
3297 g_value_init (&result_value, G_TYPE_BOOLEAN);
3299 g_value_init (¶ms[0], G_TYPE_SOCKET);
3300 g_value_set_object (¶ms[0], socket);
3301 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
3302 g_value_set_flags (¶ms[1], condition);
3304 g_closure_invoke (closure, &result_value, 2, params, NULL);
3306 result = g_value_get_boolean (&result_value);
3307 g_value_unset (&result_value);
3308 g_value_unset (¶ms[0]);
3309 g_value_unset (¶ms[1]);
3314 static GSourceFuncs socket_source_funcs =
3317 socket_source_prepare_win32,
3318 socket_source_check_win32,
3320 NULL, NULL, /* check, prepare */
3322 socket_source_dispatch,
3323 socket_source_finalize,
3324 (GSourceFunc)socket_source_closure_callback,
3328 socket_source_new (GSocket *socket,
3329 GIOCondition condition,
3330 GCancellable *cancellable)
3333 GSocketSource *socket_source;
3336 ensure_event (socket);
3338 if (socket->priv->event == WSA_INVALID_EVENT)
3340 g_warning ("Failed to create WSAEvent");
3341 return g_source_new (&broken_funcs, sizeof (GSource));
3345 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
3347 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3348 g_source_set_name (source, "GSocket");
3349 socket_source = (GSocketSource *)source;
3351 socket_source->socket = g_object_ref (socket);
3352 socket_source->condition = condition;
3356 GSource *cancellable_source;
3358 cancellable_source = g_cancellable_source_new (cancellable);
3359 g_source_add_child_source (source, cancellable_source);
3360 g_source_set_dummy_callback (cancellable_source);
3361 g_source_unref (cancellable_source);
3365 add_condition_watch (socket, &socket_source->condition);
3366 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3367 socket_source->pollfd.events = condition;
3368 socket_source->pollfd.revents = 0;
3369 g_source_add_poll (source, &socket_source->pollfd);
3371 socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
3374 if (socket->priv->timeout)
3375 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3377 g_source_set_ready_time (source, -1);
3383 * g_socket_create_source: (skip)
3384 * @socket: a #GSocket
3385 * @condition: a #GIOCondition mask to monitor
3386 * @cancellable: (allow-none): a %GCancellable or %NULL
3388 * Creates a %GSource that can be attached to a %GMainContext to monitor
3389 * for the availability of the specified @condition on the socket.
3391 * The callback on the source is of the #GSocketSourceFunc type.
3393 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3394 * these conditions will always be reported output if they are true.
3396 * @cancellable if not %NULL can be used to cancel the source, which will
3397 * cause the source to trigger, reporting the current condition (which
3398 * is likely 0 unless cancellation happened at the same time as a
3399 * condition change). You can check for this in the callback using
3400 * g_cancellable_is_cancelled().
3402 * If @socket has a timeout set, and it is reached before @condition
3403 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3404 * %G_IO_OUT depending on @condition. However, @socket will have been
3405 * marked as having had a timeout, and so the next #GSocket I/O method
3406 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3408 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3413 g_socket_create_source (GSocket *socket,
3414 GIOCondition condition,
3415 GCancellable *cancellable)
3417 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3419 return socket_source_new (socket, condition, cancellable);
3423 * g_socket_condition_check:
3424 * @socket: a #GSocket
3425 * @condition: a #GIOCondition mask to check
3427 * Checks on the readiness of @socket to perform operations.
3428 * The operations specified in @condition are checked for and masked
3429 * against the currently-satisfied conditions on @socket. The result
3432 * Note that on Windows, it is possible for an operation to return
3433 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3434 * g_socket_condition_check() has claimed that the socket is ready for
3435 * writing. Rather than calling g_socket_condition_check() and then
3436 * writing to the socket if it succeeds, it is generally better to
3437 * simply try writing to the socket right away, and try again later if
3438 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3440 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3441 * these conditions will always be set in the output if they are true.
3443 * This call never blocks.
3445 * Returns: the @GIOCondition mask of the current state
3450 g_socket_condition_check (GSocket *socket,
3451 GIOCondition condition)
3453 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3455 if (!check_socket (socket, NULL))
3460 GIOCondition current_condition;
3462 condition |= G_IO_ERR | G_IO_HUP;
3464 add_condition_watch (socket, &condition);
3465 current_condition = update_condition (socket);
3466 remove_condition_watch (socket, &condition);
3467 return condition & current_condition;
3473 poll_fd.fd = socket->priv->fd;
3474 poll_fd.events = condition;
3475 poll_fd.revents = 0;
3478 result = g_poll (&poll_fd, 1, 0);
3479 while (result == -1 && get_socket_errno () == EINTR);
3481 return poll_fd.revents;
3487 * g_socket_condition_wait:
3488 * @socket: a #GSocket
3489 * @condition: a #GIOCondition mask to wait for
3490 * @cancellable: (allow-none): a #GCancellable, or %NULL
3491 * @error: a #GError pointer, or %NULL
3493 * Waits for @condition to become true on @socket. When the condition
3494 * is met, %TRUE is returned.
3496 * If @cancellable is cancelled before the condition is met, or if the
3497 * socket has a timeout set and it is reached before the condition is
3498 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3499 * the appropriate value (%G_IO_ERROR_CANCELLED or
3500 * %G_IO_ERROR_TIMED_OUT).
3502 * See also g_socket_condition_timed_wait().
3504 * Returns: %TRUE if the condition was met, %FALSE otherwise
3509 g_socket_condition_wait (GSocket *socket,
3510 GIOCondition condition,
3511 GCancellable *cancellable,
3514 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3516 return g_socket_condition_timed_wait (socket, condition, -1,
3517 cancellable, error);
3521 * g_socket_condition_timed_wait:
3522 * @socket: a #GSocket
3523 * @condition: a #GIOCondition mask to wait for
3524 * @timeout: the maximum time (in microseconds) to wait, or -1
3525 * @cancellable: (allow-none): a #GCancellable, or %NULL
3526 * @error: a #GError pointer, or %NULL
3528 * Waits for up to @timeout microseconds for @condition to become true
3529 * on @socket. If the condition is met, %TRUE is returned.
3531 * If @cancellable is cancelled before the condition is met, or if
3532 * @timeout (or the socket's #GSocket:timeout) is reached before the
3533 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3534 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3535 * %G_IO_ERROR_TIMED_OUT).
3537 * If you don't want a timeout, use g_socket_condition_wait().
3538 * (Alternatively, you can pass -1 for @timeout.)
3540 * Note that although @timeout is in microseconds for consistency with
3541 * other GLib APIs, this function actually only has millisecond
3542 * resolution, and the behavior is undefined if @timeout is not an
3543 * exact number of milliseconds.
3545 * Returns: %TRUE if the condition was met, %FALSE otherwise
3550 g_socket_condition_timed_wait (GSocket *socket,
3551 GIOCondition condition,
3553 GCancellable *cancellable,
3558 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3560 if (!check_socket (socket, error))
3563 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3566 if (socket->priv->timeout &&
3567 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3568 timeout = socket->priv->timeout * 1000;
3569 else if (timeout != -1)
3570 timeout = timeout / 1000;
3572 start_time = g_get_monotonic_time ();
3576 GIOCondition current_condition;
3582 /* Always check these */
3583 condition |= G_IO_ERR | G_IO_HUP;
3585 add_condition_watch (socket, &condition);
3588 events[num_events++] = socket->priv->event;
3590 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3591 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3594 timeout = WSA_INFINITE;
3596 current_condition = update_condition (socket);
3597 while ((condition & current_condition) == 0)
3599 res = WSAWaitForMultipleEvents (num_events, events,
3600 FALSE, timeout, FALSE);
3601 if (res == WSA_WAIT_FAILED)
3603 int errsv = get_socket_errno ();
3605 g_set_error (error, G_IO_ERROR,
3606 socket_io_error_from_errno (errsv),
3607 _("Waiting for socket condition: %s"),
3608 socket_strerror (errsv));
3611 else if (res == WSA_WAIT_TIMEOUT)
3613 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3614 _("Socket I/O timed out"));
3618 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3621 current_condition = update_condition (socket);
3623 if (timeout != WSA_INFINITE)
3625 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3630 remove_condition_watch (socket, &condition);
3632 g_cancellable_release_fd (cancellable);
3634 return (condition & current_condition) != 0;
3642 poll_fd[0].fd = socket->priv->fd;
3643 poll_fd[0].events = condition;
3646 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3651 result = g_poll (poll_fd, num, timeout);
3652 if (result != -1 || errno != EINTR)
3657 timeout -= (g_get_monotonic_time () - start_time) / 1000;
3664 g_cancellable_release_fd (cancellable);
3668 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3669 _("Socket I/O timed out"));
3673 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3679 * g_socket_send_message:
3680 * @socket: a #GSocket
3681 * @address: (allow-none): a #GSocketAddress, or %NULL
3682 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3683 * @num_vectors: the number of elements in @vectors, or -1
3684 * @messages: (array length=num_messages) (allow-none): a pointer to an
3685 * array of #GSocketControlMessages, or %NULL.
3686 * @num_messages: number of elements in @messages, or -1.
3687 * @flags: an int containing #GSocketMsgFlags flags
3688 * @cancellable: (allow-none): a %GCancellable or %NULL
3689 * @error: #GError for error reporting, or %NULL to ignore.
3691 * Send data to @address on @socket. This is the most complicated and
3692 * fully-featured version of this call. For easier use, see
3693 * g_socket_send() and g_socket_send_to().
3695 * If @address is %NULL then the message is sent to the default receiver
3696 * (set by g_socket_connect()).
3698 * @vectors must point to an array of #GOutputVector structs and
3699 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3700 * then @vectors is assumed to be terminated by a #GOutputVector with a
3701 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3702 * that the sent data will be gathered from. Using multiple
3703 * #GOutputVectors is more memory-efficient than manually copying
3704 * data from multiple sources into a single buffer, and more
3705 * network-efficient than making multiple calls to g_socket_send().
3707 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3708 * #GSocketControlMessage instances. These correspond to the control
3709 * messages to be sent on the socket.
3710 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3713 * @flags modify how the message is sent. The commonly available arguments
3714 * for this are available in the #GSocketMsgFlags enum, but the
3715 * values there are the same as the system values, and the flags
3716 * are passed in as-is, so you can pass in system-specific flags too.
3718 * If the socket is in blocking mode the call will block until there is
3719 * space for the data in the socket queue. If there is no space available
3720 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3721 * will be returned. To be notified when space is available, wait for the
3722 * %G_IO_OUT condition. Note though that you may still receive
3723 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3724 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3725 * very common due to the way the underlying APIs work.)
3727 * On error -1 is returned and @error is set accordingly.
3729 * Returns: Number of bytes written (which may be less than @size), or -1
3735 g_socket_send_message (GSocket *socket,
3736 GSocketAddress *address,
3737 GOutputVector *vectors,
3739 GSocketControlMessage **messages,
3742 GCancellable *cancellable,
3745 GOutputVector one_vector;
3748 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3749 g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), -1);
3750 g_return_val_if_fail (num_vectors == 0 || vectors != NULL, -1);
3751 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
3752 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
3753 g_return_val_if_fail (error == NULL || *error == NULL, -1);
3755 if (!check_socket (socket, error))
3758 if (!check_timeout (socket, error))
3761 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3764 if (num_vectors == -1)
3766 for (num_vectors = 0;
3767 vectors[num_vectors].buffer != NULL;
3772 if (num_messages == -1)
3774 for (num_messages = 0;
3775 messages != NULL && messages[num_messages] != NULL;
3780 if (num_vectors == 0)
3784 one_vector.buffer = &zero;
3785 one_vector.size = 1;
3787 vectors = &one_vector;
3800 msg.msg_namelen = g_socket_address_get_native_size (address);
3801 msg.msg_name = g_alloca (msg.msg_namelen);
3802 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3807 msg.msg_name = NULL;
3808 msg.msg_namelen = 0;
3813 /* this entire expression will be evaluated at compile time */
3814 if (sizeof *msg.msg_iov == sizeof *vectors &&
3815 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3816 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3817 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3818 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3819 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3820 G_STRUCT_OFFSET (GOutputVector, size))
3821 /* ABI is compatible */
3823 msg.msg_iov = (struct iovec *) vectors;
3824 msg.msg_iovlen = num_vectors;
3827 /* ABI is incompatible */
3831 msg.msg_iov = g_newa (struct iovec, num_vectors);
3832 for (i = 0; i < num_vectors; i++)
3834 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3835 msg.msg_iov[i].iov_len = vectors[i].size;
3837 msg.msg_iovlen = num_vectors;
3843 struct cmsghdr *cmsg;
3846 msg.msg_controllen = 0;
3847 for (i = 0; i < num_messages; i++)
3848 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3850 if (msg.msg_controllen == 0)
3851 msg.msg_control = NULL;
3854 msg.msg_control = g_alloca (msg.msg_controllen);
3855 memset (msg.msg_control, '\0', msg.msg_controllen);
3858 cmsg = CMSG_FIRSTHDR (&msg);
3859 for (i = 0; i < num_messages; i++)
3861 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3862 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3863 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3864 g_socket_control_message_serialize (messages[i],
3866 cmsg = CMSG_NXTHDR (&msg, cmsg);
3868 g_assert (cmsg == NULL);
3873 if (socket->priv->blocking &&
3874 !g_socket_condition_wait (socket,
3875 G_IO_OUT, cancellable, error))
3878 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3881 int errsv = get_socket_errno ();
3886 if (socket->priv->blocking &&
3887 (errsv == EWOULDBLOCK ||
3891 g_set_error (error, G_IO_ERROR,
3892 socket_io_error_from_errno (errsv),
3893 _("Error sending message: %s"), socket_strerror (errsv));
3904 struct sockaddr_storage addr;
3911 /* Win32 doesn't support control messages.
3912 Actually this is possible for raw and datagram sockets
3913 via WSASendMessage on Vista or later, but that doesn't
3915 if (num_messages != 0)
3917 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3918 _("GSocketControlMessage not supported on Windows"));
3923 bufs = g_newa (WSABUF, num_vectors);
3924 for (i = 0; i < num_vectors; i++)
3926 bufs[i].buf = (char *)vectors[i].buffer;
3927 bufs[i].len = (gulong)vectors[i].size;
3931 addrlen = 0; /* Avoid warning */
3934 addrlen = g_socket_address_get_native_size (address);
3935 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3941 if (socket->priv->blocking &&
3942 !g_socket_condition_wait (socket,
3943 G_IO_OUT, cancellable, error))
3947 result = WSASendTo (socket->priv->fd,
3950 (const struct sockaddr *)&addr, addrlen,
3953 result = WSASend (socket->priv->fd,
3960 int errsv = get_socket_errno ();
3962 if (errsv == WSAEINTR)
3965 if (errsv == WSAEWOULDBLOCK)
3966 win32_unset_event_mask (socket, FD_WRITE);
3968 if (socket->priv->blocking &&
3969 errsv == WSAEWOULDBLOCK)
3972 g_set_error (error, G_IO_ERROR,
3973 socket_io_error_from_errno (errsv),
3974 _("Error sending message: %s"), socket_strerror (errsv));
3986 static GSocketAddress *
3987 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
3989 GSocketAddress *saddr;
3991 guint64 oldest_time = G_MAXUINT64;
3992 gint oldest_index = 0;
3994 if (native_len <= 0)
3998 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
4000 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
4001 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
4002 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
4007 if (tmp_native_len != native_len)
4010 if (memcmp (tmp_native, native, native_len) == 0)
4012 saddr = g_object_ref (tmp);
4013 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
4017 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
4019 oldest_time = socket->priv->recv_addr_cache[i].last_used;
4024 saddr = g_socket_address_new_from_native (native, native_len);
4026 if (socket->priv->recv_addr_cache[oldest_index].addr)
4028 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
4029 g_free (socket->priv->recv_addr_cache[oldest_index].native);
4032 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
4033 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
4034 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
4035 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
4041 * g_socket_receive_message:
4042 * @socket: a #GSocket
4043 * @address: (out) (allow-none): a pointer to a #GSocketAddress
4045 * @vectors: (array length=num_vectors): an array of #GInputVector structs
4046 * @num_vectors: the number of elements in @vectors, or -1
4047 * @messages: (array length=num_messages) (allow-none): a pointer which
4048 * may be filled with an array of #GSocketControlMessages, or %NULL
4049 * @num_messages: a pointer which will be filled with the number of
4050 * elements in @messages, or %NULL
4051 * @flags: a pointer to an int containing #GSocketMsgFlags flags
4052 * @cancellable: (allow-none): a %GCancellable or %NULL
4053 * @error: a #GError pointer, or %NULL
4055 * Receive data from a socket. This is the most complicated and
4056 * fully-featured version of this call. For easier use, see
4057 * g_socket_receive() and g_socket_receive_from().
4059 * If @address is non-%NULL then @address will be set equal to the
4060 * source address of the received packet.
4061 * @address is owned by the caller.
4063 * @vector must point to an array of #GInputVector structs and
4064 * @num_vectors must be the length of this array. These structs
4065 * describe the buffers that received data will be scattered into.
4066 * If @num_vectors is -1, then @vectors is assumed to be terminated
4067 * by a #GInputVector with a %NULL buffer pointer.
4069 * As a special case, if @num_vectors is 0 (in which case, @vectors
4070 * may of course be %NULL), then a single byte is received and
4071 * discarded. This is to facilitate the common practice of sending a
4072 * single '\0' byte for the purposes of transferring ancillary data.
4074 * @messages, if non-%NULL, will be set to point to a newly-allocated
4075 * array of #GSocketControlMessage instances or %NULL if no such
4076 * messages was received. These correspond to the control messages
4077 * received from the kernel, one #GSocketControlMessage per message
4078 * from the kernel. This array is %NULL-terminated and must be freed
4079 * by the caller using g_free() after calling g_object_unref() on each
4080 * element. If @messages is %NULL, any control messages received will
4083 * @num_messages, if non-%NULL, will be set to the number of control
4084 * messages received.
4086 * If both @messages and @num_messages are non-%NULL, then
4087 * @num_messages gives the number of #GSocketControlMessage instances
4088 * in @messages (ie: not including the %NULL terminator).
4090 * @flags is an in/out parameter. The commonly available arguments
4091 * for this are available in the #GSocketMsgFlags enum, but the
4092 * values there are the same as the system values, and the flags
4093 * are passed in as-is, so you can pass in system-specific flags too
4094 * (and g_socket_receive_message() may pass system-specific flags out).
4096 * As with g_socket_receive(), data may be discarded if @socket is
4097 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
4098 * provide enough buffer space to read a complete message. You can pass
4099 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
4100 * removing it from the receive queue, but there is no portable way to find
4101 * out the length of the message other than by reading it into a
4102 * sufficiently-large buffer.
4104 * If the socket is in blocking mode the call will block until there
4105 * is some data to receive, the connection is closed, or there is an
4106 * error. If there is no data available and the socket is in
4107 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
4108 * returned. To be notified when data is available, wait for the
4109 * %G_IO_IN condition.
4111 * On error -1 is returned and @error is set accordingly.
4113 * Returns: Number of bytes read, or 0 if the connection was closed by
4114 * the peer, or -1 on error
4119 g_socket_receive_message (GSocket *socket,
4120 GSocketAddress **address,
4121 GInputVector *vectors,
4123 GSocketControlMessage ***messages,
4126 GCancellable *cancellable,
4129 GInputVector one_vector;
4132 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4134 if (!check_socket (socket, error))
4137 if (!check_timeout (socket, error))
4140 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4143 if (num_vectors == -1)
4145 for (num_vectors = 0;
4146 vectors[num_vectors].buffer != NULL;
4151 if (num_vectors == 0)
4153 one_vector.buffer = &one_byte;
4154 one_vector.size = 1;
4156 vectors = &one_vector;
4163 struct sockaddr_storage one_sockaddr;
4168 msg.msg_name = &one_sockaddr;
4169 msg.msg_namelen = sizeof (struct sockaddr_storage);
4173 msg.msg_name = NULL;
4174 msg.msg_namelen = 0;
4178 /* this entire expression will be evaluated at compile time */
4179 if (sizeof *msg.msg_iov == sizeof *vectors &&
4180 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4181 G_STRUCT_OFFSET (struct iovec, iov_base) ==
4182 G_STRUCT_OFFSET (GInputVector, buffer) &&
4183 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4184 G_STRUCT_OFFSET (struct iovec, iov_len) ==
4185 G_STRUCT_OFFSET (GInputVector, size))
4186 /* ABI is compatible */
4188 msg.msg_iov = (struct iovec *) vectors;
4189 msg.msg_iovlen = num_vectors;
4192 /* ABI is incompatible */
4196 msg.msg_iov = g_newa (struct iovec, num_vectors);
4197 for (i = 0; i < num_vectors; i++)
4199 msg.msg_iov[i].iov_base = vectors[i].buffer;
4200 msg.msg_iov[i].iov_len = vectors[i].size;
4202 msg.msg_iovlen = num_vectors;
4206 msg.msg_control = g_alloca (2048);
4207 msg.msg_controllen = 2048;
4211 msg.msg_flags = *flags;
4215 /* We always set the close-on-exec flag so we don't leak file
4216 * descriptors into child processes. Note that gunixfdmessage.c
4217 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4219 #ifdef MSG_CMSG_CLOEXEC
4220 msg.msg_flags |= MSG_CMSG_CLOEXEC;
4226 if (socket->priv->blocking &&
4227 !g_socket_condition_wait (socket,
4228 G_IO_IN, cancellable, error))
4231 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4232 #ifdef MSG_CMSG_CLOEXEC
4233 if (result < 0 && get_socket_errno () == EINVAL)
4235 /* We must be running on an old kernel. Call without the flag. */
4236 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4237 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4243 int errsv = get_socket_errno ();
4248 if (socket->priv->blocking &&
4249 (errsv == EWOULDBLOCK ||
4253 g_set_error (error, G_IO_ERROR,
4254 socket_io_error_from_errno (errsv),
4255 _("Error receiving message: %s"), socket_strerror (errsv));
4262 /* decode address */
4263 if (address != NULL)
4265 *address = cache_recv_address (socket, msg.msg_name, msg.msg_namelen);
4268 /* decode control messages */
4270 GPtrArray *my_messages = NULL;
4271 struct cmsghdr *cmsg;
4273 if (msg.msg_controllen >= sizeof (struct cmsghdr))
4275 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4277 GSocketControlMessage *message;
4279 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4281 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4283 if (message == NULL)
4284 /* We've already spewed about the problem in the
4285 deserialization code, so just continue */
4288 if (messages == NULL)
4290 /* we have to do it this way if the user ignores the
4291 * messages so that we will close any received fds.
4293 g_object_unref (message);
4297 if (my_messages == NULL)
4298 my_messages = g_ptr_array_new ();
4299 g_ptr_array_add (my_messages, message);
4305 *num_messages = my_messages != NULL ? my_messages->len : 0;
4309 if (my_messages == NULL)
4315 g_ptr_array_add (my_messages, NULL);
4316 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4321 g_assert (my_messages == NULL);
4325 /* capture the flags */
4327 *flags = msg.msg_flags;
4333 struct sockaddr_storage addr;
4335 DWORD bytes_received;
4342 bufs = g_newa (WSABUF, num_vectors);
4343 for (i = 0; i < num_vectors; i++)
4345 bufs[i].buf = (char *)vectors[i].buffer;
4346 bufs[i].len = (gulong)vectors[i].size;
4358 if (socket->priv->blocking &&
4359 !g_socket_condition_wait (socket,
4360 G_IO_IN, cancellable, error))
4363 addrlen = sizeof addr;
4365 result = WSARecvFrom (socket->priv->fd,
4367 &bytes_received, &win_flags,
4368 (struct sockaddr *)&addr, &addrlen,
4371 result = WSARecv (socket->priv->fd,
4373 &bytes_received, &win_flags,
4377 int errsv = get_socket_errno ();
4379 if (errsv == WSAEINTR)
4382 win32_unset_event_mask (socket, FD_READ);
4384 if (socket->priv->blocking &&
4385 errsv == WSAEWOULDBLOCK)
4388 g_set_error (error, G_IO_ERROR,
4389 socket_io_error_from_errno (errsv),
4390 _("Error receiving message: %s"), socket_strerror (errsv));
4394 win32_unset_event_mask (socket, FD_READ);
4398 /* decode address */
4399 if (address != NULL)
4401 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
4404 /* capture the flags */
4408 if (messages != NULL)
4410 if (num_messages != NULL)
4413 return bytes_received;
4419 * g_socket_get_credentials:
4420 * @socket: a #GSocket.
4421 * @error: #GError for error reporting, or %NULL to ignore.
4423 * Returns the credentials of the foreign process connected to this
4424 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4427 * If this operation isn't supported on the OS, the method fails with
4428 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4429 * by reading the %SO_PEERCRED option on the underlying socket.
4431 * Other ways to obtain credentials from a foreign peer includes the
4432 * #GUnixCredentialsMessage type and
4433 * g_unix_connection_send_credentials() /
4434 * g_unix_connection_receive_credentials() functions.
4436 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4437 * that must be freed with g_object_unref().
4442 g_socket_get_credentials (GSocket *socket,
4447 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4448 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4452 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
4456 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
4457 socklen_t optlen = sizeof (native_creds_buf);
4459 if (getsockopt (socket->priv->fd,
4465 ret = g_credentials_new ();
4466 g_credentials_set_native (ret,
4467 G_CREDENTIALS_NATIVE_TYPE,
4471 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
4473 ucred_t *ucred = NULL;
4475 if (getpeerucred (socket->priv->fd, &ucred) == 0)
4477 ret = g_credentials_new ();
4478 g_credentials_set_native (ret,
4479 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
4485 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
4490 int errsv = get_socket_errno ();
4494 socket_io_error_from_errno (errsv),
4495 _("Unable to read socket credentials: %s"),
4496 socket_strerror (errsv));
4501 g_set_error_literal (error,
4503 G_IO_ERROR_NOT_SUPPORTED,
4504 _("g_socket_get_credentials not implemented for this OS"));
4511 * g_socket_get_option:
4512 * @socket: a #GSocket
4513 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
4514 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
4515 * @value: (out): return location for the option value
4516 * @error: #GError for error reporting, or %NULL to ignore.
4518 * Gets the value of an integer-valued option on @socket, as with
4519 * getsockopt(). (If you need to fetch a non-integer-valued option,
4520 * you will need to call getsockopt() directly.)
4522 * The [<gio/gnetworking.h>][gio-gnetworking.h]
4523 * header pulls in system headers that will define most of the
4524 * standard/portable socket options. For unusual socket protocols or
4525 * platform-dependent options, you may need to include additional
4528 * Note that even for socket options that are a single byte in size,
4529 * @value is still a pointer to a #gint variable, not a #guchar;
4530 * g_socket_get_option() will handle the conversion internally.
4532 * Returns: success or failure. On failure, @error will be set, and
4533 * the system error value (`errno` or WSAGetLastError()) will still
4534 * be set to the result of the getsockopt() call.
4539 g_socket_get_option (GSocket *socket,
4547 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4550 size = sizeof (gint);
4551 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
4553 int errsv = get_socket_errno ();
4555 g_set_error_literal (error,
4557 socket_io_error_from_errno (errsv),
4558 socket_strerror (errsv));
4560 /* Reset errno in case the caller wants to look at it */
4566 #if G_BYTE_ORDER == G_BIG_ENDIAN
4567 /* If the returned value is smaller than an int then we need to
4568 * slide it over into the low-order bytes of *value.
4570 if (size != sizeof (gint))
4571 *value = *value >> (8 * (sizeof (gint) - size));
4578 * g_socket_set_option:
4579 * @socket: a #GSocket
4580 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
4581 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
4582 * @value: the value to set the option to
4583 * @error: #GError for error reporting, or %NULL to ignore.
4585 * Sets the value of an integer-valued option on @socket, as with
4586 * setsockopt(). (If you need to set a non-integer-valued option,
4587 * you will need to call setsockopt() directly.)
4589 * The [<gio/gnetworking.h>][gio-gnetworking.h]
4590 * header pulls in system headers that will define most of the
4591 * standard/portable socket options. For unusual socket protocols or
4592 * platform-dependent options, you may need to include additional
4595 * Returns: success or failure. On failure, @error will be set, and
4596 * the system error value (`errno` or WSAGetLastError()) will still
4597 * be set to the result of the setsockopt() call.
4602 g_socket_set_option (GSocket *socket,
4610 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4612 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
4615 #if !defined (__linux__) && !defined (G_OS_WIN32)
4616 /* Linux and Windows let you set a single-byte value from an int,
4617 * but most other platforms don't.
4619 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
4621 #if G_BYTE_ORDER == G_BIG_ENDIAN
4622 value = value << (8 * (sizeof (gint) - 1));
4624 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
4629 errsv = get_socket_errno ();
4631 g_set_error_literal (error,
4633 socket_io_error_from_errno (errsv),
4634 socket_strerror (errsv));