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.
123 static void g_socket_initable_iface_init (GInitableIface *iface);
124 static gboolean g_socket_initable_init (GInitable *initable,
125 GCancellable *cancellable,
143 PROP_MULTICAST_LOOPBACK,
147 /* Size of the receiver cache for g_socket_receive_from() */
148 #define RECV_ADDR_CACHE_SIZE 8
150 struct _GSocketPrivate
152 GSocketFamily family;
154 GSocketProtocol protocol;
158 GError *construct_error;
159 GSocketAddress *remote_address;
167 guint connect_pending : 1;
173 GList *requested_conditions; /* list of requested GIOCondition * */
174 GMutex win32_source_lock;
178 GSocketAddress *addr;
179 struct sockaddr *native;
182 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
185 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
186 G_ADD_PRIVATE (GSocket)
187 g_networking_init ();
188 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
189 g_socket_initable_iface_init));
192 get_socket_errno (void)
197 return WSAGetLastError ();
202 socket_io_error_from_errno (int err)
205 return g_io_error_from_win32_error (err);
207 return g_io_error_from_errno (err);
212 socket_strerror (int err)
215 return g_strerror (err);
220 msg = g_win32_error_message (err);
222 msg_ret = g_intern_string (msg);
230 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
232 _win32_unset_event_mask (GSocket *socket, int mask)
234 socket->priv->current_events &= ~mask;
235 socket->priv->current_errors &= ~mask;
238 #define win32_unset_event_mask(_socket, _mask)
241 /* Windows has broken prototypes... */
243 #define getsockopt(sockfd, level, optname, optval, optlen) \
244 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
245 #define setsockopt(sockfd, level, optname, optval, optlen) \
246 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
247 #define getsockname(sockfd, addr, addrlen) \
248 getsockname (sockfd, addr, (int *)addrlen)
249 #define getpeername(sockfd, addr, addrlen) \
250 getpeername (sockfd, addr, (int *)addrlen)
251 #define recv(sockfd, buf, len, flags) \
252 recv (sockfd, (gpointer)buf, len, flags)
256 set_fd_nonblocking (int fd)
259 GError *error = NULL;
265 if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
267 g_warning ("Error setting socket nonblocking: %s", error->message);
268 g_clear_error (&error);
273 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
275 int errsv = get_socket_errno ();
276 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
282 check_socket (GSocket *socket,
285 if (!socket->priv->inited)
287 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
288 _("Invalid socket, not initialized"));
292 if (socket->priv->construct_error)
294 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
295 _("Invalid socket, initialization failed due to: %s"),
296 socket->priv->construct_error->message);
300 if (socket->priv->closed)
302 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
303 _("Socket is already closed"));
311 check_timeout (GSocket *socket,
314 if (socket->priv->timed_out)
316 socket->priv->timed_out = FALSE;
317 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
318 _("Socket I/O timed out"));
326 g_socket_details_from_fd (GSocket *socket)
328 struct sockaddr_storage address;
334 fd = socket->priv->fd;
335 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
337 errsv = get_socket_errno ();
349 /* programmer error */
350 g_error ("creating GSocket from fd %d: %s\n",
351 fd, socket_strerror (errsv));
362 socket->priv->type = G_SOCKET_TYPE_STREAM;
366 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
370 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
374 socket->priv->type = G_SOCKET_TYPE_INVALID;
378 addrlen = sizeof address;
379 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
381 errsv = get_socket_errno ();
387 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
388 sizeof address.ss_family <= addrlen);
389 family = address.ss_family;
393 /* On Solaris, this happens if the socket is not yet connected.
394 * But we can use SO_DOMAIN as a workaround there.
397 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
399 errsv = get_socket_errno ();
403 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
411 case G_SOCKET_FAMILY_IPV4:
412 case G_SOCKET_FAMILY_IPV6:
413 socket->priv->family = address.ss_family;
414 switch (socket->priv->type)
416 case G_SOCKET_TYPE_STREAM:
417 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
420 case G_SOCKET_TYPE_DATAGRAM:
421 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
424 case G_SOCKET_TYPE_SEQPACKET:
425 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
433 case G_SOCKET_FAMILY_UNIX:
434 socket->priv->family = G_SOCKET_FAMILY_UNIX;
435 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
439 socket->priv->family = G_SOCKET_FAMILY_INVALID;
443 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
445 addrlen = sizeof address;
446 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
447 socket->priv->connected = TRUE;
450 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
452 socket->priv->keepalive = !!value;
456 /* Can't read, maybe not supported, assume FALSE */
457 socket->priv->keepalive = FALSE;
463 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
464 socket_io_error_from_errno (errsv),
465 _("creating GSocket from fd: %s"),
466 socket_strerror (errsv));
469 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
471 g_socket (gint domain,
479 fd = socket (domain, type | SOCK_CLOEXEC, protocol);
483 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
484 if (fd < 0 && (errno == EINVAL || errno == EPROTOTYPE))
486 fd = socket (domain, type, protocol);
490 int errsv = get_socket_errno ();
492 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
493 _("Unable to create socket: %s"), socket_strerror (errsv));
502 /* We always want to set close-on-exec to protect users. If you
503 need to so some weird inheritance to exec you can re-enable this
504 using lower level hacks with g_socket_get_fd(). */
505 flags = fcntl (fd, F_GETFD, 0);
507 (flags & FD_CLOEXEC) == 0)
510 fcntl (fd, F_SETFD, flags);
519 g_socket_create_socket (GSocketFamily family,
528 case G_SOCKET_TYPE_STREAM:
529 native_type = SOCK_STREAM;
532 case G_SOCKET_TYPE_DATAGRAM:
533 native_type = SOCK_DGRAM;
536 case G_SOCKET_TYPE_SEQPACKET:
537 native_type = SOCK_SEQPACKET;
541 g_assert_not_reached ();
546 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
547 _("Unable to create socket: %s"), _("Unknown family was specified"));
553 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
554 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
558 return g_socket (family, native_type, protocol, error);
562 g_socket_constructed (GObject *object)
564 GSocket *socket = G_SOCKET (object);
566 if (socket->priv->fd >= 0)
567 /* create socket->priv info from the fd */
568 g_socket_details_from_fd (socket);
571 /* create the fd from socket->priv info */
572 socket->priv->fd = g_socket_create_socket (socket->priv->family,
574 socket->priv->protocol,
575 &socket->priv->construct_error);
577 /* Always use native nonblocking sockets, as
578 windows sets sockets to nonblocking automatically
579 in certain operations. This way we make things work
580 the same on all platforms */
581 if (socket->priv->fd != -1)
582 set_fd_nonblocking (socket->priv->fd);
586 g_socket_get_property (GObject *object,
591 GSocket *socket = G_SOCKET (object);
592 GSocketAddress *address;
597 g_value_set_enum (value, socket->priv->family);
601 g_value_set_enum (value, socket->priv->type);
605 g_value_set_enum (value, socket->priv->protocol);
609 g_value_set_int (value, socket->priv->fd);
613 g_value_set_boolean (value, socket->priv->blocking);
616 case PROP_LISTEN_BACKLOG:
617 g_value_set_int (value, socket->priv->listen_backlog);
621 g_value_set_boolean (value, socket->priv->keepalive);
624 case PROP_LOCAL_ADDRESS:
625 address = g_socket_get_local_address (socket, NULL);
626 g_value_take_object (value, address);
629 case PROP_REMOTE_ADDRESS:
630 address = g_socket_get_remote_address (socket, NULL);
631 g_value_take_object (value, address);
635 g_value_set_uint (value, socket->priv->timeout);
639 g_value_set_uint (value, g_socket_get_ttl (socket));
643 g_value_set_boolean (value, g_socket_get_broadcast (socket));
646 case PROP_MULTICAST_LOOPBACK:
647 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
650 case PROP_MULTICAST_TTL:
651 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
655 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
660 g_socket_set_property (GObject *object,
665 GSocket *socket = G_SOCKET (object);
670 socket->priv->family = g_value_get_enum (value);
674 socket->priv->type = g_value_get_enum (value);
678 socket->priv->protocol = g_value_get_enum (value);
682 socket->priv->fd = g_value_get_int (value);
686 g_socket_set_blocking (socket, g_value_get_boolean (value));
689 case PROP_LISTEN_BACKLOG:
690 g_socket_set_listen_backlog (socket, g_value_get_int (value));
694 g_socket_set_keepalive (socket, g_value_get_boolean (value));
698 g_socket_set_timeout (socket, g_value_get_uint (value));
702 g_socket_set_ttl (socket, g_value_get_uint (value));
706 g_socket_set_broadcast (socket, g_value_get_boolean (value));
709 case PROP_MULTICAST_LOOPBACK:
710 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
713 case PROP_MULTICAST_TTL:
714 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
718 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
723 g_socket_finalize (GObject *object)
725 GSocket *socket = G_SOCKET (object);
728 g_clear_error (&socket->priv->construct_error);
730 if (socket->priv->fd != -1 &&
731 !socket->priv->closed)
732 g_socket_close (socket, NULL);
734 if (socket->priv->remote_address)
735 g_object_unref (socket->priv->remote_address);
738 if (socket->priv->event != WSA_INVALID_EVENT)
740 WSACloseEvent (socket->priv->event);
741 socket->priv->event = WSA_INVALID_EVENT;
744 g_assert (socket->priv->requested_conditions == NULL);
745 g_mutex_clear (&socket->priv->win32_source_lock);
748 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
750 if (socket->priv->recv_addr_cache[i].addr)
752 g_object_unref (socket->priv->recv_addr_cache[i].addr);
753 g_free (socket->priv->recv_addr_cache[i].native);
757 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
758 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
762 g_socket_class_init (GSocketClass *klass)
764 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
767 /* There is no portable, thread-safe way to avoid having the process
768 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
769 * forced to simply ignore the signal process-wide.
771 signal (SIGPIPE, SIG_IGN);
774 gobject_class->finalize = g_socket_finalize;
775 gobject_class->constructed = g_socket_constructed;
776 gobject_class->set_property = g_socket_set_property;
777 gobject_class->get_property = g_socket_get_property;
779 g_object_class_install_property (gobject_class, PROP_FAMILY,
780 g_param_spec_enum ("family",
782 P_("The sockets address family"),
783 G_TYPE_SOCKET_FAMILY,
784 G_SOCKET_FAMILY_INVALID,
785 G_PARAM_CONSTRUCT_ONLY |
787 G_PARAM_STATIC_STRINGS));
789 g_object_class_install_property (gobject_class, PROP_TYPE,
790 g_param_spec_enum ("type",
792 P_("The sockets type"),
794 G_SOCKET_TYPE_STREAM,
795 G_PARAM_CONSTRUCT_ONLY |
797 G_PARAM_STATIC_STRINGS));
799 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
800 g_param_spec_enum ("protocol",
801 P_("Socket protocol"),
802 P_("The id of the protocol to use, or -1 for unknown"),
803 G_TYPE_SOCKET_PROTOCOL,
804 G_SOCKET_PROTOCOL_UNKNOWN,
805 G_PARAM_CONSTRUCT_ONLY |
807 G_PARAM_STATIC_STRINGS));
809 g_object_class_install_property (gobject_class, PROP_FD,
810 g_param_spec_int ("fd",
811 P_("File descriptor"),
812 P_("The sockets file descriptor"),
816 G_PARAM_CONSTRUCT_ONLY |
818 G_PARAM_STATIC_STRINGS));
820 g_object_class_install_property (gobject_class, PROP_BLOCKING,
821 g_param_spec_boolean ("blocking",
823 P_("Whether or not I/O on this socket is blocking"),
826 G_PARAM_STATIC_STRINGS));
828 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
829 g_param_spec_int ("listen-backlog",
830 P_("Listen backlog"),
831 P_("Outstanding connections in the listen queue"),
836 G_PARAM_STATIC_STRINGS));
838 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
839 g_param_spec_boolean ("keepalive",
840 P_("Keep connection alive"),
841 P_("Keep connection alive by sending periodic pings"),
844 G_PARAM_STATIC_STRINGS));
846 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
847 g_param_spec_object ("local-address",
849 P_("The local address the socket is bound to"),
850 G_TYPE_SOCKET_ADDRESS,
852 G_PARAM_STATIC_STRINGS));
854 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
855 g_param_spec_object ("remote-address",
856 P_("Remote address"),
857 P_("The remote address the socket is connected to"),
858 G_TYPE_SOCKET_ADDRESS,
860 G_PARAM_STATIC_STRINGS));
865 * The timeout in seconds on socket I/O
869 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
870 g_param_spec_uint ("timeout",
872 P_("The timeout in seconds on socket I/O"),
877 G_PARAM_STATIC_STRINGS));
882 * Whether the socket should allow sending to broadcast addresses.
886 g_object_class_install_property (gobject_class, PROP_BROADCAST,
887 g_param_spec_boolean ("broadcast",
889 P_("Whether to allow sending to broadcast addresses"),
892 G_PARAM_STATIC_STRINGS));
897 * Time-to-live for outgoing unicast packets
901 g_object_class_install_property (gobject_class, PROP_TTL,
902 g_param_spec_uint ("ttl",
904 P_("Time-to-live of outgoing unicast packets"),
907 G_PARAM_STATIC_STRINGS));
910 * GSocket:multicast-loopback:
912 * Whether outgoing multicast packets loop back to the local host.
916 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
917 g_param_spec_boolean ("multicast-loopback",
918 P_("Multicast loopback"),
919 P_("Whether outgoing multicast packets loop back to the local host"),
922 G_PARAM_STATIC_STRINGS));
925 * GSocket:multicast-ttl:
927 * Time-to-live out outgoing multicast packets
931 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
932 g_param_spec_uint ("multicast-ttl",
934 P_("Time-to-live of outgoing multicast packets"),
937 G_PARAM_STATIC_STRINGS));
941 g_socket_initable_iface_init (GInitableIface *iface)
943 iface->init = g_socket_initable_init;
947 g_socket_init (GSocket *socket)
949 socket->priv = g_socket_get_instance_private (socket);
951 socket->priv->fd = -1;
952 socket->priv->blocking = TRUE;
953 socket->priv->listen_backlog = 10;
954 socket->priv->construct_error = NULL;
956 socket->priv->event = WSA_INVALID_EVENT;
957 g_mutex_init (&socket->priv->win32_source_lock);
962 g_socket_initable_init (GInitable *initable,
963 GCancellable *cancellable,
968 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
970 socket = G_SOCKET (initable);
972 if (cancellable != NULL)
974 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
975 _("Cancellable initialization not supported"));
979 socket->priv->inited = TRUE;
981 if (socket->priv->construct_error)
984 *error = g_error_copy (socket->priv->construct_error);
994 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
995 * @type: the socket type to use.
996 * @protocol: the id of the protocol to use, or 0 for default.
997 * @error: #GError for error reporting, or %NULL to ignore.
999 * Creates a new #GSocket with the defined family, type and protocol.
1000 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1001 * for the family and type is used.
1003 * The @protocol is a family and type specific int that specifies what
1004 * kind of protocol to use. #GSocketProtocol lists several common ones.
1005 * Many families only support one protocol, and use 0 for this, others
1006 * support several and using 0 means to use the default protocol for
1007 * the family and type.
1009 * The protocol id is passed directly to the operating
1010 * system, so you can use protocols not listed in #GSocketProtocol if you
1011 * know the protocol number used for it.
1013 * Returns: a #GSocket or %NULL on error.
1014 * Free the returned object with g_object_unref().
1019 g_socket_new (GSocketFamily family,
1021 GSocketProtocol protocol,
1024 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1028 "protocol", protocol,
1033 * g_socket_new_from_fd:
1034 * @fd: a native socket file descriptor.
1035 * @error: #GError for error reporting, or %NULL to ignore.
1037 * Creates a new #GSocket from a native file descriptor
1038 * or winsock SOCKET handle.
1040 * This reads all the settings from the file descriptor so that
1041 * all properties should work. Note that the file descriptor
1042 * will be set to non-blocking mode, independent on the blocking
1043 * mode of the #GSocket.
1045 * Returns: a #GSocket or %NULL on error.
1046 * Free the returned object with g_object_unref().
1051 g_socket_new_from_fd (gint fd,
1054 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1061 * g_socket_set_blocking:
1062 * @socket: a #GSocket.
1063 * @blocking: Whether to use blocking I/O or not.
1065 * Sets the blocking mode of the socket. In blocking mode
1066 * all operations block until they succeed or there is an error. In
1067 * non-blocking mode all functions return results immediately or
1068 * with a %G_IO_ERROR_WOULD_BLOCK error.
1070 * All sockets are created in blocking mode. However, note that the
1071 * platform level socket is always non-blocking, and blocking mode
1072 * is a GSocket level feature.
1077 g_socket_set_blocking (GSocket *socket,
1080 g_return_if_fail (G_IS_SOCKET (socket));
1082 blocking = !!blocking;
1084 if (socket->priv->blocking == blocking)
1087 socket->priv->blocking = blocking;
1088 g_object_notify (G_OBJECT (socket), "blocking");
1092 * g_socket_get_blocking:
1093 * @socket: a #GSocket.
1095 * Gets the blocking mode of the socket. For details on blocking I/O,
1096 * see g_socket_set_blocking().
1098 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1103 g_socket_get_blocking (GSocket *socket)
1105 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1107 return socket->priv->blocking;
1111 * g_socket_set_keepalive:
1112 * @socket: a #GSocket.
1113 * @keepalive: Value for the keepalive flag
1115 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1116 * this flag is set on a socket, the system will attempt to verify that the
1117 * remote socket endpoint is still present if a sufficiently long period of
1118 * time passes with no data being exchanged. If the system is unable to
1119 * verify the presence of the remote endpoint, it will automatically close
1122 * This option is only functional on certain kinds of sockets. (Notably,
1123 * %G_SOCKET_PROTOCOL_TCP sockets.)
1125 * The exact time between pings is system- and protocol-dependent, but will
1126 * normally be at least two hours. Most commonly, you would set this flag
1127 * on a server socket if you want to allow clients to remain idle for long
1128 * periods of time, but also want to ensure that connections are eventually
1129 * garbage-collected if clients crash or become unreachable.
1134 g_socket_set_keepalive (GSocket *socket,
1137 GError *error = NULL;
1139 g_return_if_fail (G_IS_SOCKET (socket));
1141 keepalive = !!keepalive;
1142 if (socket->priv->keepalive == keepalive)
1145 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1148 g_warning ("error setting keepalive: %s", error->message);
1149 g_error_free (error);
1153 socket->priv->keepalive = keepalive;
1154 g_object_notify (G_OBJECT (socket), "keepalive");
1158 * g_socket_get_keepalive:
1159 * @socket: a #GSocket.
1161 * Gets the keepalive mode of the socket. For details on this,
1162 * see g_socket_set_keepalive().
1164 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1169 g_socket_get_keepalive (GSocket *socket)
1171 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1173 return socket->priv->keepalive;
1177 * g_socket_get_listen_backlog:
1178 * @socket: a #GSocket.
1180 * Gets the listen backlog setting of the socket. For details on this,
1181 * see g_socket_set_listen_backlog().
1183 * Returns: the maximum number of pending connections.
1188 g_socket_get_listen_backlog (GSocket *socket)
1190 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1192 return socket->priv->listen_backlog;
1196 * g_socket_set_listen_backlog:
1197 * @socket: a #GSocket.
1198 * @backlog: the maximum number of pending connections.
1200 * Sets the maximum number of outstanding connections allowed
1201 * when listening on this socket. If more clients than this are
1202 * connecting to the socket and the application is not handling them
1203 * on time then the new connections will be refused.
1205 * Note that this must be called before g_socket_listen() and has no
1206 * effect if called after that.
1211 g_socket_set_listen_backlog (GSocket *socket,
1214 g_return_if_fail (G_IS_SOCKET (socket));
1215 g_return_if_fail (!socket->priv->listening);
1217 if (backlog != socket->priv->listen_backlog)
1219 socket->priv->listen_backlog = backlog;
1220 g_object_notify (G_OBJECT (socket), "listen-backlog");
1225 * g_socket_get_timeout:
1226 * @socket: a #GSocket.
1228 * Gets the timeout setting of the socket. For details on this, see
1229 * g_socket_set_timeout().
1231 * Returns: the timeout in seconds
1236 g_socket_get_timeout (GSocket *socket)
1238 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1240 return socket->priv->timeout;
1244 * g_socket_set_timeout:
1245 * @socket: a #GSocket.
1246 * @timeout: the timeout for @socket, in seconds, or 0 for none
1248 * Sets the time in seconds after which I/O operations on @socket will
1249 * time out if they have not yet completed.
1251 * On a blocking socket, this means that any blocking #GSocket
1252 * operation will time out after @timeout seconds of inactivity,
1253 * returning %G_IO_ERROR_TIMED_OUT.
1255 * On a non-blocking socket, calls to g_socket_condition_wait() will
1256 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1257 * created with g_socket_create_source() will trigger after
1258 * @timeout seconds of inactivity, with the requested condition
1259 * set, at which point calling g_socket_receive(), g_socket_send(),
1260 * g_socket_check_connect_result(), etc, will fail with
1261 * %G_IO_ERROR_TIMED_OUT.
1263 * If @timeout is 0 (the default), operations will never time out
1266 * Note that if an I/O operation is interrupted by a signal, this may
1267 * cause the timeout to be reset.
1272 g_socket_set_timeout (GSocket *socket,
1275 g_return_if_fail (G_IS_SOCKET (socket));
1277 if (timeout != socket->priv->timeout)
1279 socket->priv->timeout = timeout;
1280 g_object_notify (G_OBJECT (socket), "timeout");
1286 * @socket: a #GSocket.
1288 * Gets the unicast time-to-live setting on @socket; see
1289 * g_socket_set_ttl() for more details.
1291 * Returns: the time-to-live setting on @socket
1296 g_socket_get_ttl (GSocket *socket)
1298 GError *error = NULL;
1301 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1303 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1305 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1308 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1310 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1314 g_return_val_if_reached (0);
1318 g_warning ("error getting unicast ttl: %s", error->message);
1319 g_error_free (error);
1328 * @socket: a #GSocket.
1329 * @ttl: the time-to-live value for all unicast packets on @socket
1331 * Sets the time-to-live for outgoing unicast packets on @socket.
1332 * By default the platform-specific default value is used.
1337 g_socket_set_ttl (GSocket *socket,
1340 GError *error = NULL;
1342 g_return_if_fail (G_IS_SOCKET (socket));
1344 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1346 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1349 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1351 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1353 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1357 g_return_if_reached ();
1361 g_warning ("error setting unicast ttl: %s", error->message);
1362 g_error_free (error);
1366 g_object_notify (G_OBJECT (socket), "ttl");
1370 * g_socket_get_broadcast:
1371 * @socket: a #GSocket.
1373 * Gets the broadcast setting on @socket; if %TRUE,
1374 * it is possible to send packets to broadcast
1377 * Returns: the broadcast setting on @socket
1382 g_socket_get_broadcast (GSocket *socket)
1384 GError *error = NULL;
1387 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1389 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1392 g_warning ("error getting broadcast: %s", error->message);
1393 g_error_free (error);
1401 * g_socket_set_broadcast:
1402 * @socket: a #GSocket.
1403 * @broadcast: whether @socket should allow sending to broadcast
1406 * Sets whether @socket should allow sending to broadcast addresses.
1407 * This is %FALSE by default.
1412 g_socket_set_broadcast (GSocket *socket,
1415 GError *error = NULL;
1417 g_return_if_fail (G_IS_SOCKET (socket));
1419 broadcast = !!broadcast;
1421 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1424 g_warning ("error setting broadcast: %s", error->message);
1425 g_error_free (error);
1429 g_object_notify (G_OBJECT (socket), "broadcast");
1433 * g_socket_get_multicast_loopback:
1434 * @socket: a #GSocket.
1436 * Gets the multicast loopback setting on @socket; if %TRUE (the
1437 * default), outgoing multicast packets will be looped back to
1438 * multicast listeners on the same host.
1440 * Returns: the multicast loopback setting on @socket
1445 g_socket_get_multicast_loopback (GSocket *socket)
1447 GError *error = NULL;
1450 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1452 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1454 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1457 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1459 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1463 g_return_val_if_reached (FALSE);
1467 g_warning ("error getting multicast loopback: %s", error->message);
1468 g_error_free (error);
1476 * g_socket_set_multicast_loopback:
1477 * @socket: a #GSocket.
1478 * @loopback: whether @socket should receive messages sent to its
1479 * multicast groups from the local host
1481 * Sets whether outgoing multicast packets will be received by sockets
1482 * listening on that multicast address on the same host. This is %TRUE
1488 g_socket_set_multicast_loopback (GSocket *socket,
1491 GError *error = NULL;
1493 g_return_if_fail (G_IS_SOCKET (socket));
1495 loopback = !!loopback;
1497 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1499 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1502 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1504 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1506 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1510 g_return_if_reached ();
1514 g_warning ("error setting multicast loopback: %s", error->message);
1515 g_error_free (error);
1519 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1523 * g_socket_get_multicast_ttl:
1524 * @socket: a #GSocket.
1526 * Gets the multicast time-to-live setting on @socket; see
1527 * g_socket_set_multicast_ttl() for more details.
1529 * Returns: the multicast time-to-live setting on @socket
1534 g_socket_get_multicast_ttl (GSocket *socket)
1536 GError *error = NULL;
1539 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1541 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1543 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1546 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1548 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1552 g_return_val_if_reached (FALSE);
1556 g_warning ("error getting multicast ttl: %s", error->message);
1557 g_error_free (error);
1565 * g_socket_set_multicast_ttl:
1566 * @socket: a #GSocket.
1567 * @ttl: the time-to-live value for all multicast datagrams on @socket
1569 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1570 * By default, this is 1, meaning that multicast packets will not leave
1571 * the local network.
1576 g_socket_set_multicast_ttl (GSocket *socket,
1579 GError *error = NULL;
1581 g_return_if_fail (G_IS_SOCKET (socket));
1583 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1585 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1588 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1590 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1592 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1596 g_return_if_reached ();
1600 g_warning ("error setting multicast ttl: %s", error->message);
1601 g_error_free (error);
1605 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1609 * g_socket_get_family:
1610 * @socket: a #GSocket.
1612 * Gets the socket family of the socket.
1614 * Returns: a #GSocketFamily
1619 g_socket_get_family (GSocket *socket)
1621 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1623 return socket->priv->family;
1627 * g_socket_get_socket_type:
1628 * @socket: a #GSocket.
1630 * Gets the socket type of the socket.
1632 * Returns: a #GSocketType
1637 g_socket_get_socket_type (GSocket *socket)
1639 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1641 return socket->priv->type;
1645 * g_socket_get_protocol:
1646 * @socket: a #GSocket.
1648 * Gets the socket protocol id the socket was created with.
1649 * In case the protocol is unknown, -1 is returned.
1651 * Returns: a protocol id, or -1 if unknown
1656 g_socket_get_protocol (GSocket *socket)
1658 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1660 return socket->priv->protocol;
1665 * @socket: a #GSocket.
1667 * Returns the underlying OS socket object. On unix this
1668 * is a socket file descriptor, and on Windows this is
1669 * a Winsock2 SOCKET handle. This may be useful for
1670 * doing platform specific or otherwise unusual operations
1673 * Returns: the file descriptor of the socket.
1678 g_socket_get_fd (GSocket *socket)
1680 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1682 return socket->priv->fd;
1686 * g_socket_get_local_address:
1687 * @socket: a #GSocket.
1688 * @error: #GError for error reporting, or %NULL to ignore.
1690 * Try to get the local address of a bound socket. This is only
1691 * useful if the socket has been bound to a local address,
1692 * either explicitly or implicitly when connecting.
1694 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1695 * Free the returned object with g_object_unref().
1700 g_socket_get_local_address (GSocket *socket,
1703 struct sockaddr_storage buffer;
1704 guint len = sizeof (buffer);
1706 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1708 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1710 int errsv = get_socket_errno ();
1711 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1712 _("could not get local address: %s"), socket_strerror (errsv));
1716 return g_socket_address_new_from_native (&buffer, len);
1720 * g_socket_get_remote_address:
1721 * @socket: a #GSocket.
1722 * @error: #GError for error reporting, or %NULL to ignore.
1724 * Try to get the remove address of a connected socket. This is only
1725 * useful for connection oriented sockets that have been connected.
1727 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1728 * Free the returned object with g_object_unref().
1733 g_socket_get_remote_address (GSocket *socket,
1736 struct sockaddr_storage buffer;
1737 guint len = sizeof (buffer);
1739 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1741 if (socket->priv->connect_pending)
1743 if (!g_socket_check_connect_result (socket, error))
1746 socket->priv->connect_pending = FALSE;
1749 if (!socket->priv->remote_address)
1751 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1753 int errsv = get_socket_errno ();
1754 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1755 _("could not get remote address: %s"), socket_strerror (errsv));
1759 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1762 return g_object_ref (socket->priv->remote_address);
1766 * g_socket_is_connected:
1767 * @socket: a #GSocket.
1769 * Check whether the socket is connected. This is only useful for
1770 * connection-oriented sockets.
1772 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1777 g_socket_is_connected (GSocket *socket)
1779 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1781 return socket->priv->connected;
1786 * @socket: a #GSocket.
1787 * @error: #GError for error reporting, or %NULL to ignore.
1789 * Marks the socket as a server socket, i.e. a socket that is used
1790 * to accept incoming requests using g_socket_accept().
1792 * Before calling this the socket must be bound to a local address using
1795 * To set the maximum amount of outstanding clients, use
1796 * g_socket_set_listen_backlog().
1798 * Returns: %TRUE on success, %FALSE on error.
1803 g_socket_listen (GSocket *socket,
1806 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1808 if (!check_socket (socket, error))
1811 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1813 int errsv = get_socket_errno ();
1815 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1816 _("could not listen: %s"), socket_strerror (errsv));
1820 socket->priv->listening = TRUE;
1827 * @socket: a #GSocket.
1828 * @address: a #GSocketAddress specifying the local address.
1829 * @allow_reuse: whether to allow reusing this address
1830 * @error: #GError for error reporting, or %NULL to ignore.
1832 * When a socket is created it is attached to an address family, but it
1833 * doesn't have an address in this family. g_socket_bind() assigns the
1834 * address (sometimes called name) of the socket.
1836 * It is generally required to bind to a local address before you can
1837 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1838 * In certain situations, you may also want to bind a socket that will be
1839 * used to initiate connections, though this is not normally required.
1841 * If @socket is a TCP socket, then @allow_reuse controls the setting
1842 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
1843 * server sockets (sockets that you will eventually call
1844 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
1845 * set this flag on a server socket may cause g_socket_bind() to return
1846 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
1847 * immediately restarted.)
1849 * If @socket is a UDP socket, then @allow_reuse determines whether or
1850 * not other UDP sockets can be bound to the same address at the same
1851 * time. In particular, you can have several UDP sockets bound to the
1852 * same address, and they will all receive all of the multicast and
1853 * broadcast packets sent to that address. (The behavior of unicast
1854 * UDP packets to an address with multiple listeners is not defined.)
1856 * Returns: %TRUE on success, %FALSE on error.
1861 g_socket_bind (GSocket *socket,
1862 GSocketAddress *address,
1863 gboolean reuse_address,
1866 struct sockaddr_storage addr;
1867 gboolean so_reuseaddr;
1869 gboolean so_reuseport;
1872 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1874 if (!check_socket (socket, error))
1877 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1880 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
1881 * sockets, but has nasty side effects we don't want for TCP
1884 * On other platforms, we set SO_REUSEPORT, if it exists, for
1885 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
1886 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
1887 * the desired semantics on UDP (as it does on Linux, although
1888 * Linux has SO_REUSEPORT too as of 3.9).
1892 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1894 so_reuseaddr = !!reuse_address;
1898 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1901 /* Ignore errors here, the only likely error is "not supported", and
1902 * this is a "best effort" thing mainly.
1904 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
1906 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
1909 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1910 g_socket_address_get_native_size (address)) < 0)
1912 int errsv = get_socket_errno ();
1914 G_IO_ERROR, socket_io_error_from_errno (errsv),
1915 _("Error binding to address: %s"), socket_strerror (errsv));
1922 #if !defined(HAVE_IF_NAMETOINDEX) && defined(G_OS_WIN32)
1924 if_nametoindex (const gchar *iface)
1926 PIP_ADAPTER_ADDRESSES addresses = NULL, p;
1927 gulong addresses_len = 0;
1931 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, NULL, &addresses_len);
1932 if (res != NO_ERROR && res != ERROR_BUFFER_OVERFLOW)
1934 if (res == ERROR_NO_DATA)
1941 addresses = g_malloc (addresses_len);
1942 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, addresses, &addresses_len);
1944 if (res != NO_ERROR)
1947 if (res == ERROR_NO_DATA)
1957 if (strcmp (p->AdapterName, iface) == 0)
1973 #define HAVE_IF_NAMETOINDEX 1
1977 g_socket_multicast_group_operation (GSocket *socket,
1978 GInetAddress *group,
1979 gboolean source_specific,
1981 gboolean join_group,
1984 const guint8 *native_addr;
1985 gint optname, result;
1987 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1988 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
1989 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
1991 if (!check_socket (socket, error))
1994 native_addr = g_inet_address_to_bytes (group);
1995 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
1997 #ifdef HAVE_IP_MREQN
1998 struct ip_mreqn mc_req;
2000 struct ip_mreq mc_req;
2003 memset (&mc_req, 0, sizeof (mc_req));
2004 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2006 #ifdef HAVE_IP_MREQN
2008 mc_req.imr_ifindex = if_nametoindex (iface);
2010 mc_req.imr_ifindex = 0; /* Pick any. */
2011 #elif defined(G_OS_WIN32)
2013 mc_req.imr_interface.s_addr = g_htonl (if_nametoindex (iface));
2015 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2017 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2020 if (source_specific)
2022 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2023 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2025 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2027 _("Error joining multicast group: %s") :
2028 _("Error leaving multicast group: %s"),
2029 _("No support for source-specific multicast"));
2034 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2035 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2036 &mc_req, sizeof (mc_req));
2038 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2040 struct ipv6_mreq mc_req_ipv6;
2042 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2043 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2044 #ifdef HAVE_IF_NAMETOINDEX
2046 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2049 mc_req_ipv6.ipv6mr_interface = 0;
2051 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2052 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2053 &mc_req_ipv6, sizeof (mc_req_ipv6));
2056 g_return_val_if_reached (FALSE);
2060 int errsv = get_socket_errno ();
2062 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2064 _("Error joining multicast group: %s") :
2065 _("Error leaving multicast group: %s"),
2066 socket_strerror (errsv));
2074 * g_socket_join_multicast_group:
2075 * @socket: a #GSocket.
2076 * @group: a #GInetAddress specifying the group address to join.
2077 * @iface: (allow-none): Name of the interface to use, or %NULL
2078 * @source_specific: %TRUE if source-specific multicast should be used
2079 * @error: #GError for error reporting, or %NULL to ignore.
2081 * Registers @socket to receive multicast messages sent to @group.
2082 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2083 * been bound to an appropriate interface and port with
2086 * If @iface is %NULL, the system will automatically pick an interface
2087 * to bind to based on @group.
2089 * If @source_specific is %TRUE, source-specific multicast as defined
2090 * in RFC 4604 is used. Note that on older platforms this may fail
2091 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2093 * Returns: %TRUE on success, %FALSE on error.
2098 g_socket_join_multicast_group (GSocket *socket,
2099 GInetAddress *group,
2100 gboolean source_specific,
2104 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2108 * g_socket_leave_multicast_group:
2109 * @socket: a #GSocket.
2110 * @group: a #GInetAddress specifying the group address to leave.
2111 * @iface: (allow-none): Interface used
2112 * @source_specific: %TRUE if source-specific multicast was used
2113 * @error: #GError for error reporting, or %NULL to ignore.
2115 * Removes @socket from the multicast group defined by @group, @iface,
2116 * and @source_specific (which must all have the same values they had
2117 * when you joined the group).
2119 * @socket remains bound to its address and port, and can still receive
2120 * unicast messages after calling this.
2122 * Returns: %TRUE on success, %FALSE on error.
2127 g_socket_leave_multicast_group (GSocket *socket,
2128 GInetAddress *group,
2129 gboolean source_specific,
2133 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2137 * g_socket_speaks_ipv4:
2138 * @socket: a #GSocket
2140 * Checks if a socket is capable of speaking IPv4.
2142 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2143 * and under some combinations of circumstances IPv6 sockets are also
2144 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2147 * No other types of sockets are currently considered as being capable
2150 * Returns: %TRUE if this socket can be used with IPv4.
2155 g_socket_speaks_ipv4 (GSocket *socket)
2157 switch (socket->priv->family)
2159 case G_SOCKET_FAMILY_IPV4:
2162 case G_SOCKET_FAMILY_IPV6:
2163 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2167 if (!g_socket_get_option (socket,
2168 IPPROTO_IPV6, IPV6_V6ONLY,
2185 * @socket: a #GSocket.
2186 * @cancellable: (allow-none): a %GCancellable or %NULL
2187 * @error: #GError for error reporting, or %NULL to ignore.
2189 * Accept incoming connections on a connection-based socket. This removes
2190 * the first outstanding connection request from the listening socket and
2191 * creates a #GSocket object for it.
2193 * The @socket must be bound to a local address with g_socket_bind() and
2194 * must be listening for incoming connections (g_socket_listen()).
2196 * If there are no outstanding connections then the operation will block
2197 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2198 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2200 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2201 * Free the returned object with g_object_unref().
2206 g_socket_accept (GSocket *socket,
2207 GCancellable *cancellable,
2210 GSocket *new_socket;
2213 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2215 if (!check_socket (socket, error))
2218 if (!check_timeout (socket, error))
2223 if (socket->priv->blocking &&
2224 !g_socket_condition_wait (socket,
2225 G_IO_IN, cancellable, error))
2228 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2230 int errsv = get_socket_errno ();
2232 win32_unset_event_mask (socket, FD_ACCEPT);
2237 if (socket->priv->blocking)
2239 #ifdef WSAEWOULDBLOCK
2240 if (errsv == WSAEWOULDBLOCK)
2243 if (errsv == EWOULDBLOCK ||
2249 g_set_error (error, G_IO_ERROR,
2250 socket_io_error_from_errno (errsv),
2251 _("Error accepting connection: %s"), socket_strerror (errsv));
2257 win32_unset_event_mask (socket, FD_ACCEPT);
2261 /* The socket inherits the accepting sockets event mask and even object,
2262 we need to remove that */
2263 WSAEventSelect (ret, NULL, 0);
2269 /* We always want to set close-on-exec to protect users. If you
2270 need to so some weird inheritance to exec you can re-enable this
2271 using lower level hacks with g_socket_get_fd(). */
2272 flags = fcntl (ret, F_GETFD, 0);
2274 (flags & FD_CLOEXEC) == 0)
2276 flags |= FD_CLOEXEC;
2277 fcntl (ret, F_SETFD, flags);
2282 new_socket = g_socket_new_from_fd (ret, error);
2283 if (new_socket == NULL)
2292 new_socket->priv->protocol = socket->priv->protocol;
2299 * @socket: a #GSocket.
2300 * @address: a #GSocketAddress specifying the remote address.
2301 * @cancellable: (allow-none): a %GCancellable or %NULL
2302 * @error: #GError for error reporting, or %NULL to ignore.
2304 * Connect the socket to the specified remote address.
2306 * For connection oriented socket this generally means we attempt to make
2307 * a connection to the @address. For a connection-less socket it sets
2308 * the default address for g_socket_send() and discards all incoming datagrams
2309 * from other sources.
2311 * Generally connection oriented sockets can only connect once, but
2312 * connection-less sockets can connect multiple times to change the
2315 * If the connect call needs to do network I/O it will block, unless
2316 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2317 * and the user can be notified of the connection finishing by waiting
2318 * for the G_IO_OUT condition. The result of the connection must then be
2319 * checked with g_socket_check_connect_result().
2321 * Returns: %TRUE if connected, %FALSE on error.
2326 g_socket_connect (GSocket *socket,
2327 GSocketAddress *address,
2328 GCancellable *cancellable,
2331 struct sockaddr_storage buffer;
2333 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2335 if (!check_socket (socket, error))
2338 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2341 if (socket->priv->remote_address)
2342 g_object_unref (socket->priv->remote_address);
2343 socket->priv->remote_address = g_object_ref (address);
2347 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2348 g_socket_address_get_native_size (address)) < 0)
2350 int errsv = get_socket_errno ();
2356 if (errsv == EINPROGRESS)
2358 if (errsv == WSAEWOULDBLOCK)
2361 if (socket->priv->blocking)
2363 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2365 if (g_socket_check_connect_result (socket, error))
2371 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2372 _("Connection in progress"));
2373 socket->priv->connect_pending = TRUE;
2377 g_set_error_literal (error, G_IO_ERROR,
2378 socket_io_error_from_errno (errsv),
2379 socket_strerror (errsv));
2386 win32_unset_event_mask (socket, FD_CONNECT);
2388 socket->priv->connected = TRUE;
2394 * g_socket_check_connect_result:
2395 * @socket: a #GSocket
2396 * @error: #GError for error reporting, or %NULL to ignore.
2398 * Checks and resets the pending connect error for the socket.
2399 * This is used to check for errors when g_socket_connect() is
2400 * used in non-blocking mode.
2402 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2407 g_socket_check_connect_result (GSocket *socket,
2412 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2414 if (!check_socket (socket, error))
2417 if (!check_timeout (socket, error))
2420 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
2422 g_prefix_error (error, _("Unable to get pending error: "));
2428 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2429 socket_strerror (value));
2430 if (socket->priv->remote_address)
2432 g_object_unref (socket->priv->remote_address);
2433 socket->priv->remote_address = NULL;
2438 socket->priv->connected = TRUE;
2443 * g_socket_get_available_bytes:
2444 * @socket: a #GSocket
2446 * Get the amount of data pending in the OS input buffer.
2448 * If @socket is a UDP or SCTP socket, this will return the size of
2449 * just the next packet, even if additional packets are buffered after
2452 * Note that on Windows, this function is rather inefficient in the
2453 * UDP case, and so if you know any plausible upper bound on the size
2454 * of the incoming packet, it is better to just do a
2455 * g_socket_receive() with a buffer of that size, rather than calling
2456 * g_socket_get_available_bytes() first and then doing a receive of
2457 * exactly the right size.
2459 * Returns: the number of bytes that can be read from the socket
2460 * without blocking or truncating, or -1 on error.
2465 g_socket_get_available_bytes (GSocket *socket)
2468 const gint bufsize = 64 * 1024;
2469 static guchar *buf = NULL;
2475 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2477 #if defined (SO_NREAD)
2478 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
2480 #elif !defined (G_OS_WIN32)
2481 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2484 if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
2486 if (G_UNLIKELY (g_once_init_enter (&buf)))
2487 g_once_init_leave (&buf, g_malloc (bufsize));
2489 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
2490 if (avail == -1 && get_socket_errno () == WSAEWOULDBLOCK)
2495 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
2505 * @socket: a #GSocket
2506 * @buffer: (array length=size) (element-type guint8): a buffer to
2507 * read data into (which should be at least @size bytes long).
2508 * @size: the number of bytes you want to read from the socket
2509 * @cancellable: (allow-none): a %GCancellable or %NULL
2510 * @error: #GError for error reporting, or %NULL to ignore.
2512 * Receive data (up to @size bytes) from a socket. This is mainly used by
2513 * connection-oriented sockets; it is identical to g_socket_receive_from()
2514 * with @address set to %NULL.
2516 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2517 * g_socket_receive() will always read either 0 or 1 complete messages from
2518 * the socket. If the received message is too large to fit in @buffer, then
2519 * the data beyond @size bytes will be discarded, without any explicit
2520 * indication that this has occurred.
2522 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2523 * number of bytes, up to @size. If more than @size bytes have been
2524 * received, the additional data will be returned in future calls to
2525 * g_socket_receive().
2527 * If the socket is in blocking mode the call will block until there
2528 * is some data to receive, the connection is closed, or there is an
2529 * error. If there is no data available and the socket is in
2530 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2531 * returned. To be notified when data is available, wait for the
2532 * %G_IO_IN condition.
2534 * On error -1 is returned and @error is set accordingly.
2536 * Returns: Number of bytes read, or 0 if the connection was closed by
2537 * the peer, or -1 on error
2542 g_socket_receive (GSocket *socket,
2545 GCancellable *cancellable,
2548 return g_socket_receive_with_blocking (socket, buffer, size,
2549 socket->priv->blocking,
2550 cancellable, error);
2554 * g_socket_receive_with_blocking:
2555 * @socket: a #GSocket
2556 * @buffer: (array length=size) (element-type guint8): a buffer to
2557 * read data into (which should be at least @size bytes long).
2558 * @size: the number of bytes you want to read from the socket
2559 * @blocking: whether to do blocking or non-blocking I/O
2560 * @cancellable: (allow-none): a %GCancellable or %NULL
2561 * @error: #GError for error reporting, or %NULL to ignore.
2563 * This behaves exactly the same as g_socket_receive(), except that
2564 * the choice of blocking or non-blocking behavior is determined by
2565 * the @blocking argument rather than by @socket's properties.
2567 * Returns: Number of bytes read, or 0 if the connection was closed by
2568 * the peer, or -1 on error
2573 g_socket_receive_with_blocking (GSocket *socket,
2577 GCancellable *cancellable,
2582 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2584 if (!check_socket (socket, error))
2587 if (!check_timeout (socket, error))
2590 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2596 !g_socket_condition_wait (socket,
2597 G_IO_IN, cancellable, error))
2600 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2602 int errsv = get_socket_errno ();
2609 #ifdef WSAEWOULDBLOCK
2610 if (errsv == WSAEWOULDBLOCK)
2613 if (errsv == EWOULDBLOCK ||
2619 win32_unset_event_mask (socket, FD_READ);
2621 g_set_error (error, G_IO_ERROR,
2622 socket_io_error_from_errno (errsv),
2623 _("Error receiving data: %s"), socket_strerror (errsv));
2627 win32_unset_event_mask (socket, FD_READ);
2636 * g_socket_receive_from:
2637 * @socket: a #GSocket
2638 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2640 * @buffer: (array length=size) (element-type guint8): a buffer to
2641 * read data into (which should be at least @size bytes long).
2642 * @size: the number of bytes you want to read from the socket
2643 * @cancellable: (allow-none): a %GCancellable or %NULL
2644 * @error: #GError for error reporting, or %NULL to ignore.
2646 * Receive data (up to @size bytes) from a socket.
2648 * If @address is non-%NULL then @address will be set equal to the
2649 * source address of the received packet.
2650 * @address is owned by the caller.
2652 * See g_socket_receive() for additional information.
2654 * Returns: Number of bytes read, or 0 if the connection was closed by
2655 * the peer, or -1 on error
2660 g_socket_receive_from (GSocket *socket,
2661 GSocketAddress **address,
2664 GCancellable *cancellable,
2672 return g_socket_receive_message (socket,
2680 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2681 * one, which can be confusing and annoying. So if possible, we want
2682 * to suppress the signal entirely.
2685 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2687 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2692 * @socket: a #GSocket
2693 * @buffer: (array length=size) (element-type guint8): the buffer
2694 * containing the data to send.
2695 * @size: the number of bytes to send
2696 * @cancellable: (allow-none): a %GCancellable or %NULL
2697 * @error: #GError for error reporting, or %NULL to ignore.
2699 * Tries to send @size bytes from @buffer on the socket. This is
2700 * mainly used by connection-oriented sockets; it is identical to
2701 * g_socket_send_to() with @address set to %NULL.
2703 * If the socket is in blocking mode the call will block until there is
2704 * space for the data in the socket queue. If there is no space available
2705 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2706 * will be returned. To be notified when space is available, wait for the
2707 * %G_IO_OUT condition. Note though that you may still receive
2708 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2709 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2710 * very common due to the way the underlying APIs work.)
2712 * On error -1 is returned and @error is set accordingly.
2714 * Returns: Number of bytes written (which may be less than @size), or -1
2720 g_socket_send (GSocket *socket,
2721 const gchar *buffer,
2723 GCancellable *cancellable,
2726 return g_socket_send_with_blocking (socket, buffer, size,
2727 socket->priv->blocking,
2728 cancellable, error);
2732 * g_socket_send_with_blocking:
2733 * @socket: a #GSocket
2734 * @buffer: (array length=size) (element-type guint8): the buffer
2735 * containing the data to send.
2736 * @size: the number of bytes to send
2737 * @blocking: whether to do blocking or non-blocking I/O
2738 * @cancellable: (allow-none): a %GCancellable or %NULL
2739 * @error: #GError for error reporting, or %NULL to ignore.
2741 * This behaves exactly the same as g_socket_send(), except that
2742 * the choice of blocking or non-blocking behavior is determined by
2743 * the @blocking argument rather than by @socket's properties.
2745 * Returns: Number of bytes written (which may be less than @size), or -1
2751 g_socket_send_with_blocking (GSocket *socket,
2752 const gchar *buffer,
2755 GCancellable *cancellable,
2760 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2762 if (!check_socket (socket, error))
2765 if (!check_timeout (socket, error))
2768 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2774 !g_socket_condition_wait (socket,
2775 G_IO_OUT, cancellable, error))
2778 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2780 int errsv = get_socket_errno ();
2785 #ifdef WSAEWOULDBLOCK
2786 if (errsv == WSAEWOULDBLOCK)
2787 win32_unset_event_mask (socket, FD_WRITE);
2792 #ifdef WSAEWOULDBLOCK
2793 if (errsv == WSAEWOULDBLOCK)
2796 if (errsv == EWOULDBLOCK ||
2802 g_set_error (error, G_IO_ERROR,
2803 socket_io_error_from_errno (errsv),
2804 _("Error sending data: %s"), socket_strerror (errsv));
2815 * @socket: a #GSocket
2816 * @address: (allow-none): a #GSocketAddress, or %NULL
2817 * @buffer: (array length=size) (element-type guint8): the buffer
2818 * containing the data to send.
2819 * @size: the number of bytes to send
2820 * @cancellable: (allow-none): a %GCancellable or %NULL
2821 * @error: #GError for error reporting, or %NULL to ignore.
2823 * Tries to send @size bytes from @buffer to @address. If @address is
2824 * %NULL then the message is sent to the default receiver (set by
2825 * g_socket_connect()).
2827 * See g_socket_send() for additional information.
2829 * Returns: Number of bytes written (which may be less than @size), or -1
2835 g_socket_send_to (GSocket *socket,
2836 GSocketAddress *address,
2837 const gchar *buffer,
2839 GCancellable *cancellable,
2847 return g_socket_send_message (socket,
2857 * g_socket_shutdown:
2858 * @socket: a #GSocket
2859 * @shutdown_read: whether to shut down the read side
2860 * @shutdown_write: whether to shut down the write side
2861 * @error: #GError for error reporting, or %NULL to ignore.
2863 * Shut down part of a full-duplex connection.
2865 * If @shutdown_read is %TRUE then the receiving side of the connection
2866 * is shut down, and further reading is disallowed.
2868 * If @shutdown_write is %TRUE then the sending side of the connection
2869 * is shut down, and further writing is disallowed.
2871 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2873 * One example where this is used is graceful disconnect for TCP connections
2874 * where you close the sending side, then wait for the other side to close
2875 * the connection, thus ensuring that the other side saw all sent data.
2877 * Returns: %TRUE on success, %FALSE on error
2882 g_socket_shutdown (GSocket *socket,
2883 gboolean shutdown_read,
2884 gboolean shutdown_write,
2889 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2891 if (!check_socket (socket, error))
2895 if (!shutdown_read && !shutdown_write)
2899 if (shutdown_read && shutdown_write)
2901 else if (shutdown_read)
2906 if (shutdown_read && shutdown_write)
2908 else if (shutdown_read)
2914 if (shutdown (socket->priv->fd, how) != 0)
2916 int errsv = get_socket_errno ();
2917 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2918 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2922 if (shutdown_read && shutdown_write)
2923 socket->priv->connected = FALSE;
2930 * @socket: a #GSocket
2931 * @error: #GError for error reporting, or %NULL to ignore.
2933 * Closes the socket, shutting down any active connection.
2935 * Closing a socket does not wait for all outstanding I/O operations
2936 * to finish, so the caller should not rely on them to be guaranteed
2937 * to complete even if the close returns with no error.
2939 * Once the socket is closed, all other operations will return
2940 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2943 * Sockets will be automatically closed when the last reference
2944 * is dropped, but you might want to call this function to make sure
2945 * resources are released as early as possible.
2947 * Beware that due to the way that TCP works, it is possible for
2948 * recently-sent data to be lost if either you close a socket while the
2949 * %G_IO_IN condition is set, or else if the remote connection tries to
2950 * send something to you after you close the socket but before it has
2951 * finished reading all of the data you sent. There is no easy generic
2952 * way to avoid this problem; the easiest fix is to design the network
2953 * protocol such that the client will never send data "out of turn".
2954 * Another solution is for the server to half-close the connection by
2955 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2956 * and then wait for the client to notice this and close its side of the
2957 * connection, after which the server can safely call g_socket_close().
2958 * (This is what #GTcpConnection does if you call
2959 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2960 * only works if the client will close its connection after the server
2963 * Returns: %TRUE on success, %FALSE on error
2968 g_socket_close (GSocket *socket,
2973 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2975 if (socket->priv->closed)
2976 return TRUE; /* Multiple close not an error */
2978 if (!check_socket (socket, error))
2984 res = closesocket (socket->priv->fd);
2986 res = close (socket->priv->fd);
2990 int errsv = get_socket_errno ();
2995 g_set_error (error, G_IO_ERROR,
2996 socket_io_error_from_errno (errsv),
2997 _("Error closing socket: %s"),
2998 socket_strerror (errsv));
3004 socket->priv->connected = FALSE;
3005 socket->priv->closed = TRUE;
3006 if (socket->priv->remote_address)
3008 g_object_unref (socket->priv->remote_address);
3009 socket->priv->remote_address = NULL;
3016 * g_socket_is_closed:
3017 * @socket: a #GSocket
3019 * Checks whether a socket is closed.
3021 * Returns: %TRUE if socket is closed, %FALSE otherwise
3026 g_socket_is_closed (GSocket *socket)
3028 return socket->priv->closed;
3032 /* Broken source, used on errors */
3034 broken_dispatch (GSource *source,
3035 GSourceFunc callback,
3041 static GSourceFuncs broken_funcs =
3050 network_events_for_condition (GIOCondition condition)
3054 if (condition & G_IO_IN)
3055 event_mask |= (FD_READ | FD_ACCEPT);
3056 if (condition & G_IO_OUT)
3057 event_mask |= (FD_WRITE | FD_CONNECT);
3058 event_mask |= FD_CLOSE;
3064 ensure_event (GSocket *socket)
3066 if (socket->priv->event == WSA_INVALID_EVENT)
3067 socket->priv->event = WSACreateEvent();
3071 update_select_events (GSocket *socket)
3078 ensure_event (socket);
3081 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3084 event_mask |= network_events_for_condition (*ptr);
3087 if (event_mask != socket->priv->selected_events)
3089 /* If no events selected, disable event so we can unset
3092 if (event_mask == 0)
3095 event = socket->priv->event;
3097 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3098 socket->priv->selected_events = event_mask;
3103 add_condition_watch (GSocket *socket,
3104 GIOCondition *condition)
3106 g_mutex_lock (&socket->priv->win32_source_lock);
3107 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3109 socket->priv->requested_conditions =
3110 g_list_prepend (socket->priv->requested_conditions, condition);
3112 update_select_events (socket);
3113 g_mutex_unlock (&socket->priv->win32_source_lock);
3117 remove_condition_watch (GSocket *socket,
3118 GIOCondition *condition)
3120 g_mutex_lock (&socket->priv->win32_source_lock);
3121 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3123 socket->priv->requested_conditions =
3124 g_list_remove (socket->priv->requested_conditions, condition);
3126 update_select_events (socket);
3127 g_mutex_unlock (&socket->priv->win32_source_lock);
3131 update_condition (GSocket *socket)
3133 WSANETWORKEVENTS events;
3134 GIOCondition condition;
3136 if (WSAEnumNetworkEvents (socket->priv->fd,
3137 socket->priv->event,
3140 socket->priv->current_events |= events.lNetworkEvents;
3141 if (events.lNetworkEvents & FD_WRITE &&
3142 events.iErrorCode[FD_WRITE_BIT] != 0)
3143 socket->priv->current_errors |= FD_WRITE;
3144 if (events.lNetworkEvents & FD_CONNECT &&
3145 events.iErrorCode[FD_CONNECT_BIT] != 0)
3146 socket->priv->current_errors |= FD_CONNECT;
3150 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3151 condition |= G_IO_IN;
3153 if (socket->priv->current_events & FD_CLOSE)
3155 int r, errsv, buffer;
3157 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3159 errsv = get_socket_errno ();
3162 (r < 0 && errsv == WSAENOTCONN))
3163 condition |= G_IO_IN;
3165 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3166 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3167 condition |= G_IO_HUP;
3169 condition |= G_IO_ERR;
3172 if (socket->priv->closed)
3173 condition |= G_IO_HUP;
3175 /* Never report both G_IO_OUT and HUP, these are
3176 mutually exclusive (can't write to a closed socket) */
3177 if ((condition & G_IO_HUP) == 0 &&
3178 socket->priv->current_events & FD_WRITE)
3180 if (socket->priv->current_errors & FD_WRITE)
3181 condition |= G_IO_ERR;
3183 condition |= G_IO_OUT;
3187 if (socket->priv->current_events & FD_CONNECT)
3189 if (socket->priv->current_errors & FD_CONNECT)
3190 condition |= (G_IO_HUP | G_IO_ERR);
3192 condition |= G_IO_OUT;
3208 GIOCondition condition;
3213 socket_source_prepare_win32 (GSource *source,
3216 GSocketSource *socket_source = (GSocketSource *)source;
3220 return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3224 socket_source_check_win32 (GSource *source)
3228 return socket_source_prepare_win32 (source, &timeout);
3233 socket_source_dispatch (GSource *source,
3234 GSourceFunc callback,
3237 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3238 GSocketSource *socket_source = (GSocketSource *)source;
3239 GSocket *socket = socket_source->socket;
3245 events = update_condition (socket_source->socket);
3247 events = g_source_query_unix_fd (source, socket_source->fd_tag);
3250 timeout = g_source_get_ready_time (source);
3251 if (timeout >= 0 && timeout < g_source_get_time (source))
3253 socket->priv->timed_out = TRUE;
3254 events |= (G_IO_IN | G_IO_OUT);
3257 ret = (*func) (socket, events & socket_source->condition, user_data);
3259 if (socket->priv->timeout)
3260 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3262 g_source_set_ready_time (source, -1);
3268 socket_source_finalize (GSource *source)
3270 GSocketSource *socket_source = (GSocketSource *)source;
3273 socket = socket_source->socket;
3276 remove_condition_watch (socket, &socket_source->condition);
3279 g_object_unref (socket);
3283 socket_source_closure_callback (GSocket *socket,
3284 GIOCondition condition,
3287 GClosure *closure = data;
3289 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3290 GValue result_value = G_VALUE_INIT;
3293 g_value_init (&result_value, G_TYPE_BOOLEAN);
3295 g_value_init (¶ms[0], G_TYPE_SOCKET);
3296 g_value_set_object (¶ms[0], socket);
3297 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
3298 g_value_set_flags (¶ms[1], condition);
3300 g_closure_invoke (closure, &result_value, 2, params, NULL);
3302 result = g_value_get_boolean (&result_value);
3303 g_value_unset (&result_value);
3304 g_value_unset (¶ms[0]);
3305 g_value_unset (¶ms[1]);
3310 static GSourceFuncs socket_source_funcs =
3313 socket_source_prepare_win32,
3314 socket_source_check_win32,
3316 NULL, NULL, /* check, prepare */
3318 socket_source_dispatch,
3319 socket_source_finalize,
3320 (GSourceFunc)socket_source_closure_callback,
3324 socket_source_new (GSocket *socket,
3325 GIOCondition condition,
3326 GCancellable *cancellable)
3329 GSocketSource *socket_source;
3332 ensure_event (socket);
3334 if (socket->priv->event == WSA_INVALID_EVENT)
3336 g_warning ("Failed to create WSAEvent");
3337 return g_source_new (&broken_funcs, sizeof (GSource));
3341 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
3343 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3344 g_source_set_name (source, "GSocket");
3345 socket_source = (GSocketSource *)source;
3347 socket_source->socket = g_object_ref (socket);
3348 socket_source->condition = condition;
3352 GSource *cancellable_source;
3354 cancellable_source = g_cancellable_source_new (cancellable);
3355 g_source_add_child_source (source, cancellable_source);
3356 g_source_set_dummy_callback (cancellable_source);
3357 g_source_unref (cancellable_source);
3361 add_condition_watch (socket, &socket_source->condition);
3362 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3363 socket_source->pollfd.events = condition;
3364 socket_source->pollfd.revents = 0;
3365 g_source_add_poll (source, &socket_source->pollfd);
3367 socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
3370 if (socket->priv->timeout)
3371 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3373 g_source_set_ready_time (source, -1);
3379 * g_socket_create_source: (skip)
3380 * @socket: a #GSocket
3381 * @condition: a #GIOCondition mask to monitor
3382 * @cancellable: (allow-none): a %GCancellable or %NULL
3384 * Creates a %GSource that can be attached to a %GMainContext to monitor
3385 * for the availability of the specified @condition on the socket.
3387 * The callback on the source is of the #GSocketSourceFunc type.
3389 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3390 * these conditions will always be reported output if they are true.
3392 * @cancellable if not %NULL can be used to cancel the source, which will
3393 * cause the source to trigger, reporting the current condition (which
3394 * is likely 0 unless cancellation happened at the same time as a
3395 * condition change). You can check for this in the callback using
3396 * g_cancellable_is_cancelled().
3398 * If @socket has a timeout set, and it is reached before @condition
3399 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3400 * %G_IO_OUT depending on @condition. However, @socket will have been
3401 * marked as having had a timeout, and so the next #GSocket I/O method
3402 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3404 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3409 g_socket_create_source (GSocket *socket,
3410 GIOCondition condition,
3411 GCancellable *cancellable)
3413 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3415 return socket_source_new (socket, condition, cancellable);
3419 * g_socket_condition_check:
3420 * @socket: a #GSocket
3421 * @condition: a #GIOCondition mask to check
3423 * Checks on the readiness of @socket to perform operations.
3424 * The operations specified in @condition are checked for and masked
3425 * against the currently-satisfied conditions on @socket. The result
3428 * Note that on Windows, it is possible for an operation to return
3429 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3430 * g_socket_condition_check() has claimed that the socket is ready for
3431 * writing. Rather than calling g_socket_condition_check() and then
3432 * writing to the socket if it succeeds, it is generally better to
3433 * simply try writing to the socket right away, and try again later if
3434 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3436 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3437 * these conditions will always be set in the output if they are true.
3439 * This call never blocks.
3441 * Returns: the @GIOCondition mask of the current state
3446 g_socket_condition_check (GSocket *socket,
3447 GIOCondition condition)
3449 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3451 if (!check_socket (socket, NULL))
3456 GIOCondition current_condition;
3458 condition |= G_IO_ERR | G_IO_HUP;
3460 add_condition_watch (socket, &condition);
3461 current_condition = update_condition (socket);
3462 remove_condition_watch (socket, &condition);
3463 return condition & current_condition;
3469 poll_fd.fd = socket->priv->fd;
3470 poll_fd.events = condition;
3471 poll_fd.revents = 0;
3474 result = g_poll (&poll_fd, 1, 0);
3475 while (result == -1 && get_socket_errno () == EINTR);
3477 return poll_fd.revents;
3483 * g_socket_condition_wait:
3484 * @socket: a #GSocket
3485 * @condition: a #GIOCondition mask to wait for
3486 * @cancellable: (allow-none): a #GCancellable, or %NULL
3487 * @error: a #GError pointer, or %NULL
3489 * Waits for @condition to become true on @socket. When the condition
3490 * is met, %TRUE is returned.
3492 * If @cancellable is cancelled before the condition is met, or if the
3493 * socket has a timeout set and it is reached before the condition is
3494 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3495 * the appropriate value (%G_IO_ERROR_CANCELLED or
3496 * %G_IO_ERROR_TIMED_OUT).
3498 * See also g_socket_condition_timed_wait().
3500 * Returns: %TRUE if the condition was met, %FALSE otherwise
3505 g_socket_condition_wait (GSocket *socket,
3506 GIOCondition condition,
3507 GCancellable *cancellable,
3510 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3512 return g_socket_condition_timed_wait (socket, condition, -1,
3513 cancellable, error);
3517 * g_socket_condition_timed_wait:
3518 * @socket: a #GSocket
3519 * @condition: a #GIOCondition mask to wait for
3520 * @timeout: the maximum time (in microseconds) to wait, or -1
3521 * @cancellable: (allow-none): a #GCancellable, or %NULL
3522 * @error: a #GError pointer, or %NULL
3524 * Waits for up to @timeout microseconds for @condition to become true
3525 * on @socket. If the condition is met, %TRUE is returned.
3527 * If @cancellable is cancelled before the condition is met, or if
3528 * @timeout (or the socket's #GSocket:timeout) is reached before the
3529 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3530 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3531 * %G_IO_ERROR_TIMED_OUT).
3533 * If you don't want a timeout, use g_socket_condition_wait().
3534 * (Alternatively, you can pass -1 for @timeout.)
3536 * Note that although @timeout is in microseconds for consistency with
3537 * other GLib APIs, this function actually only has millisecond
3538 * resolution, and the behavior is undefined if @timeout is not an
3539 * exact number of milliseconds.
3541 * Returns: %TRUE if the condition was met, %FALSE otherwise
3546 g_socket_condition_timed_wait (GSocket *socket,
3547 GIOCondition condition,
3549 GCancellable *cancellable,
3554 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3556 if (!check_socket (socket, error))
3559 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3562 if (socket->priv->timeout &&
3563 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3564 timeout = socket->priv->timeout * 1000;
3565 else if (timeout != -1)
3566 timeout = timeout / 1000;
3568 start_time = g_get_monotonic_time ();
3572 GIOCondition current_condition;
3578 /* Always check these */
3579 condition |= G_IO_ERR | G_IO_HUP;
3581 add_condition_watch (socket, &condition);
3584 events[num_events++] = socket->priv->event;
3586 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3587 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3590 timeout = WSA_INFINITE;
3592 current_condition = update_condition (socket);
3593 while ((condition & current_condition) == 0)
3595 res = WSAWaitForMultipleEvents (num_events, events,
3596 FALSE, timeout, FALSE);
3597 if (res == WSA_WAIT_FAILED)
3599 int errsv = get_socket_errno ();
3601 g_set_error (error, G_IO_ERROR,
3602 socket_io_error_from_errno (errsv),
3603 _("Waiting for socket condition: %s"),
3604 socket_strerror (errsv));
3607 else if (res == WSA_WAIT_TIMEOUT)
3609 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3610 _("Socket I/O timed out"));
3614 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3617 current_condition = update_condition (socket);
3619 if (timeout != WSA_INFINITE)
3621 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3626 remove_condition_watch (socket, &condition);
3628 g_cancellable_release_fd (cancellable);
3630 return (condition & current_condition) != 0;
3638 poll_fd[0].fd = socket->priv->fd;
3639 poll_fd[0].events = condition;
3642 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3647 result = g_poll (poll_fd, num, timeout);
3648 if (result != -1 || errno != EINTR)
3653 timeout -= (g_get_monotonic_time () - start_time) / 1000;
3660 g_cancellable_release_fd (cancellable);
3664 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3665 _("Socket I/O timed out"));
3669 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3675 * g_socket_send_message:
3676 * @socket: a #GSocket
3677 * @address: (allow-none): a #GSocketAddress, or %NULL
3678 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3679 * @num_vectors: the number of elements in @vectors, or -1
3680 * @messages: (array length=num_messages) (allow-none): a pointer to an
3681 * array of #GSocketControlMessages, or %NULL.
3682 * @num_messages: number of elements in @messages, or -1.
3683 * @flags: an int containing #GSocketMsgFlags flags
3684 * @cancellable: (allow-none): a %GCancellable or %NULL
3685 * @error: #GError for error reporting, or %NULL to ignore.
3687 * Send data to @address on @socket. This is the most complicated and
3688 * fully-featured version of this call. For easier use, see
3689 * g_socket_send() and g_socket_send_to().
3691 * If @address is %NULL then the message is sent to the default receiver
3692 * (set by g_socket_connect()).
3694 * @vectors must point to an array of #GOutputVector structs and
3695 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3696 * then @vectors is assumed to be terminated by a #GOutputVector with a
3697 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3698 * that the sent data will be gathered from. Using multiple
3699 * #GOutputVectors is more memory-efficient than manually copying
3700 * data from multiple sources into a single buffer, and more
3701 * network-efficient than making multiple calls to g_socket_send().
3703 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3704 * #GSocketControlMessage instances. These correspond to the control
3705 * messages to be sent on the socket.
3706 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3709 * @flags modify how the message is sent. The commonly available arguments
3710 * for this are available in the #GSocketMsgFlags enum, but the
3711 * values there are the same as the system values, and the flags
3712 * are passed in as-is, so you can pass in system-specific flags too.
3714 * If the socket is in blocking mode the call will block until there is
3715 * space for the data in the socket queue. If there is no space available
3716 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3717 * will be returned. To be notified when space is available, wait for the
3718 * %G_IO_OUT condition. Note though that you may still receive
3719 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3720 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3721 * very common due to the way the underlying APIs work.)
3723 * On error -1 is returned and @error is set accordingly.
3725 * Returns: Number of bytes written (which may be less than @size), or -1
3731 g_socket_send_message (GSocket *socket,
3732 GSocketAddress *address,
3733 GOutputVector *vectors,
3735 GSocketControlMessage **messages,
3738 GCancellable *cancellable,
3741 GOutputVector one_vector;
3744 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3746 if (!check_socket (socket, error))
3749 if (!check_timeout (socket, error))
3752 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3755 if (num_vectors == -1)
3757 for (num_vectors = 0;
3758 vectors[num_vectors].buffer != NULL;
3763 if (num_messages == -1)
3765 for (num_messages = 0;
3766 messages != NULL && messages[num_messages] != NULL;
3771 if (num_vectors == 0)
3775 one_vector.buffer = &zero;
3776 one_vector.size = 1;
3778 vectors = &one_vector;
3791 msg.msg_namelen = g_socket_address_get_native_size (address);
3792 msg.msg_name = g_alloca (msg.msg_namelen);
3793 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3798 msg.msg_name = NULL;
3799 msg.msg_namelen = 0;
3804 /* this entire expression will be evaluated at compile time */
3805 if (sizeof *msg.msg_iov == sizeof *vectors &&
3806 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3807 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3808 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3809 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3810 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3811 G_STRUCT_OFFSET (GOutputVector, size))
3812 /* ABI is compatible */
3814 msg.msg_iov = (struct iovec *) vectors;
3815 msg.msg_iovlen = num_vectors;
3818 /* ABI is incompatible */
3822 msg.msg_iov = g_newa (struct iovec, num_vectors);
3823 for (i = 0; i < num_vectors; i++)
3825 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3826 msg.msg_iov[i].iov_len = vectors[i].size;
3828 msg.msg_iovlen = num_vectors;
3834 struct cmsghdr *cmsg;
3837 msg.msg_controllen = 0;
3838 for (i = 0; i < num_messages; i++)
3839 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3841 if (msg.msg_controllen == 0)
3842 msg.msg_control = NULL;
3845 msg.msg_control = g_alloca (msg.msg_controllen);
3846 memset (msg.msg_control, '\0', msg.msg_controllen);
3849 cmsg = CMSG_FIRSTHDR (&msg);
3850 for (i = 0; i < num_messages; i++)
3852 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3853 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3854 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3855 g_socket_control_message_serialize (messages[i],
3857 cmsg = CMSG_NXTHDR (&msg, cmsg);
3859 g_assert (cmsg == NULL);
3864 if (socket->priv->blocking &&
3865 !g_socket_condition_wait (socket,
3866 G_IO_OUT, cancellable, error))
3869 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3872 int errsv = get_socket_errno ();
3877 if (socket->priv->blocking &&
3878 (errsv == EWOULDBLOCK ||
3882 g_set_error (error, G_IO_ERROR,
3883 socket_io_error_from_errno (errsv),
3884 _("Error sending message: %s"), socket_strerror (errsv));
3895 struct sockaddr_storage addr;
3902 /* Win32 doesn't support control messages.
3903 Actually this is possible for raw and datagram sockets
3904 via WSASendMessage on Vista or later, but that doesn't
3906 if (num_messages != 0)
3908 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3909 _("GSocketControlMessage not supported on Windows"));
3914 bufs = g_newa (WSABUF, num_vectors);
3915 for (i = 0; i < num_vectors; i++)
3917 bufs[i].buf = (char *)vectors[i].buffer;
3918 bufs[i].len = (gulong)vectors[i].size;
3922 addrlen = 0; /* Avoid warning */
3925 addrlen = g_socket_address_get_native_size (address);
3926 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3932 if (socket->priv->blocking &&
3933 !g_socket_condition_wait (socket,
3934 G_IO_OUT, cancellable, error))
3938 result = WSASendTo (socket->priv->fd,
3941 (const struct sockaddr *)&addr, addrlen,
3944 result = WSASend (socket->priv->fd,
3951 int errsv = get_socket_errno ();
3953 if (errsv == WSAEINTR)
3956 if (errsv == WSAEWOULDBLOCK)
3957 win32_unset_event_mask (socket, FD_WRITE);
3959 if (socket->priv->blocking &&
3960 errsv == WSAEWOULDBLOCK)
3963 g_set_error (error, G_IO_ERROR,
3964 socket_io_error_from_errno (errsv),
3965 _("Error sending message: %s"), socket_strerror (errsv));
3977 static GSocketAddress *
3978 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
3980 GSocketAddress *saddr;
3982 guint64 oldest_time = G_MAXUINT64;
3983 gint oldest_index = 0;
3985 if (native_len <= 0)
3989 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
3991 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
3992 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
3993 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
3998 if (tmp_native_len != native_len)
4001 if (memcmp (tmp_native, native, native_len) == 0)
4003 saddr = g_object_ref (tmp);
4004 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
4008 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
4010 oldest_time = socket->priv->recv_addr_cache[i].last_used;
4015 saddr = g_socket_address_new_from_native (native, native_len);
4017 if (socket->priv->recv_addr_cache[oldest_index].addr)
4019 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
4020 g_free (socket->priv->recv_addr_cache[oldest_index].native);
4023 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
4024 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
4025 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
4026 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
4032 * g_socket_receive_message:
4033 * @socket: a #GSocket
4034 * @address: (out) (allow-none): a pointer to a #GSocketAddress
4036 * @vectors: (array length=num_vectors): an array of #GInputVector structs
4037 * @num_vectors: the number of elements in @vectors, or -1
4038 * @messages: (array length=num_messages) (allow-none): a pointer which
4039 * may be filled with an array of #GSocketControlMessages, or %NULL
4040 * @num_messages: a pointer which will be filled with the number of
4041 * elements in @messages, or %NULL
4042 * @flags: a pointer to an int containing #GSocketMsgFlags flags
4043 * @cancellable: (allow-none): a %GCancellable or %NULL
4044 * @error: a #GError pointer, or %NULL
4046 * Receive data from a socket. This is the most complicated and
4047 * fully-featured version of this call. For easier use, see
4048 * g_socket_receive() and g_socket_receive_from().
4050 * If @address is non-%NULL then @address will be set equal to the
4051 * source address of the received packet.
4052 * @address is owned by the caller.
4054 * @vector must point to an array of #GInputVector structs and
4055 * @num_vectors must be the length of this array. These structs
4056 * describe the buffers that received data will be scattered into.
4057 * If @num_vectors is -1, then @vectors is assumed to be terminated
4058 * by a #GInputVector with a %NULL buffer pointer.
4060 * As a special case, if @num_vectors is 0 (in which case, @vectors
4061 * may of course be %NULL), then a single byte is received and
4062 * discarded. This is to facilitate the common practice of sending a
4063 * single '\0' byte for the purposes of transferring ancillary data.
4065 * @messages, if non-%NULL, will be set to point to a newly-allocated
4066 * array of #GSocketControlMessage instances or %NULL if no such
4067 * messages was received. These correspond to the control messages
4068 * received from the kernel, one #GSocketControlMessage per message
4069 * from the kernel. This array is %NULL-terminated and must be freed
4070 * by the caller using g_free() after calling g_object_unref() on each
4071 * element. If @messages is %NULL, any control messages received will
4074 * @num_messages, if non-%NULL, will be set to the number of control
4075 * messages received.
4077 * If both @messages and @num_messages are non-%NULL, then
4078 * @num_messages gives the number of #GSocketControlMessage instances
4079 * in @messages (ie: not including the %NULL terminator).
4081 * @flags is an in/out parameter. The commonly available arguments
4082 * for this are available in the #GSocketMsgFlags enum, but the
4083 * values there are the same as the system values, and the flags
4084 * are passed in as-is, so you can pass in system-specific flags too
4085 * (and g_socket_receive_message() may pass system-specific flags out).
4087 * As with g_socket_receive(), data may be discarded if @socket is
4088 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
4089 * provide enough buffer space to read a complete message. You can pass
4090 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
4091 * removing it from the receive queue, but there is no portable way to find
4092 * out the length of the message other than by reading it into a
4093 * sufficiently-large buffer.
4095 * If the socket is in blocking mode the call will block until there
4096 * is some data to receive, the connection is closed, or there is an
4097 * error. If there is no data available and the socket is in
4098 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
4099 * returned. To be notified when data is available, wait for the
4100 * %G_IO_IN condition.
4102 * On error -1 is returned and @error is set accordingly.
4104 * Returns: Number of bytes read, or 0 if the connection was closed by
4105 * the peer, or -1 on error
4110 g_socket_receive_message (GSocket *socket,
4111 GSocketAddress **address,
4112 GInputVector *vectors,
4114 GSocketControlMessage ***messages,
4117 GCancellable *cancellable,
4120 GInputVector one_vector;
4123 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4125 if (!check_socket (socket, error))
4128 if (!check_timeout (socket, error))
4131 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4134 if (num_vectors == -1)
4136 for (num_vectors = 0;
4137 vectors[num_vectors].buffer != NULL;
4142 if (num_vectors == 0)
4144 one_vector.buffer = &one_byte;
4145 one_vector.size = 1;
4147 vectors = &one_vector;
4154 struct sockaddr_storage one_sockaddr;
4159 msg.msg_name = &one_sockaddr;
4160 msg.msg_namelen = sizeof (struct sockaddr_storage);
4164 msg.msg_name = NULL;
4165 msg.msg_namelen = 0;
4169 /* this entire expression will be evaluated at compile time */
4170 if (sizeof *msg.msg_iov == sizeof *vectors &&
4171 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4172 G_STRUCT_OFFSET (struct iovec, iov_base) ==
4173 G_STRUCT_OFFSET (GInputVector, buffer) &&
4174 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4175 G_STRUCT_OFFSET (struct iovec, iov_len) ==
4176 G_STRUCT_OFFSET (GInputVector, size))
4177 /* ABI is compatible */
4179 msg.msg_iov = (struct iovec *) vectors;
4180 msg.msg_iovlen = num_vectors;
4183 /* ABI is incompatible */
4187 msg.msg_iov = g_newa (struct iovec, num_vectors);
4188 for (i = 0; i < num_vectors; i++)
4190 msg.msg_iov[i].iov_base = vectors[i].buffer;
4191 msg.msg_iov[i].iov_len = vectors[i].size;
4193 msg.msg_iovlen = num_vectors;
4197 msg.msg_control = g_alloca (2048);
4198 msg.msg_controllen = 2048;
4202 msg.msg_flags = *flags;
4206 /* We always set the close-on-exec flag so we don't leak file
4207 * descriptors into child processes. Note that gunixfdmessage.c
4208 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4210 #ifdef MSG_CMSG_CLOEXEC
4211 msg.msg_flags |= MSG_CMSG_CLOEXEC;
4217 if (socket->priv->blocking &&
4218 !g_socket_condition_wait (socket,
4219 G_IO_IN, cancellable, error))
4222 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4223 #ifdef MSG_CMSG_CLOEXEC
4224 if (result < 0 && get_socket_errno () == EINVAL)
4226 /* We must be running on an old kernel. Call without the flag. */
4227 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4228 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4234 int errsv = get_socket_errno ();
4239 if (socket->priv->blocking &&
4240 (errsv == EWOULDBLOCK ||
4244 g_set_error (error, G_IO_ERROR,
4245 socket_io_error_from_errno (errsv),
4246 _("Error receiving message: %s"), socket_strerror (errsv));
4253 /* decode address */
4254 if (address != NULL)
4256 *address = cache_recv_address (socket, msg.msg_name, msg.msg_namelen);
4259 /* decode control messages */
4261 GPtrArray *my_messages = NULL;
4262 struct cmsghdr *cmsg;
4264 if (msg.msg_controllen >= sizeof (struct cmsghdr))
4266 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4268 GSocketControlMessage *message;
4270 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4272 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4274 if (message == NULL)
4275 /* We've already spewed about the problem in the
4276 deserialization code, so just continue */
4279 if (messages == NULL)
4281 /* we have to do it this way if the user ignores the
4282 * messages so that we will close any received fds.
4284 g_object_unref (message);
4288 if (my_messages == NULL)
4289 my_messages = g_ptr_array_new ();
4290 g_ptr_array_add (my_messages, message);
4296 *num_messages = my_messages != NULL ? my_messages->len : 0;
4300 if (my_messages == NULL)
4306 g_ptr_array_add (my_messages, NULL);
4307 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4312 g_assert (my_messages == NULL);
4316 /* capture the flags */
4318 *flags = msg.msg_flags;
4324 struct sockaddr_storage addr;
4326 DWORD bytes_received;
4333 bufs = g_newa (WSABUF, num_vectors);
4334 for (i = 0; i < num_vectors; i++)
4336 bufs[i].buf = (char *)vectors[i].buffer;
4337 bufs[i].len = (gulong)vectors[i].size;
4349 if (socket->priv->blocking &&
4350 !g_socket_condition_wait (socket,
4351 G_IO_IN, cancellable, error))
4354 addrlen = sizeof addr;
4356 result = WSARecvFrom (socket->priv->fd,
4358 &bytes_received, &win_flags,
4359 (struct sockaddr *)&addr, &addrlen,
4362 result = WSARecv (socket->priv->fd,
4364 &bytes_received, &win_flags,
4368 int errsv = get_socket_errno ();
4370 if (errsv == WSAEINTR)
4373 win32_unset_event_mask (socket, FD_READ);
4375 if (socket->priv->blocking &&
4376 errsv == WSAEWOULDBLOCK)
4379 g_set_error (error, G_IO_ERROR,
4380 socket_io_error_from_errno (errsv),
4381 _("Error receiving message: %s"), socket_strerror (errsv));
4385 win32_unset_event_mask (socket, FD_READ);
4389 /* decode address */
4390 if (address != NULL)
4392 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
4395 /* capture the flags */
4399 if (messages != NULL)
4401 if (num_messages != NULL)
4404 return bytes_received;
4410 * g_socket_get_credentials:
4411 * @socket: a #GSocket.
4412 * @error: #GError for error reporting, or %NULL to ignore.
4414 * Returns the credentials of the foreign process connected to this
4415 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4418 * If this operation isn't supported on the OS, the method fails with
4419 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4420 * by reading the %SO_PEERCRED option on the underlying socket.
4422 * Other ways to obtain credentials from a foreign peer includes the
4423 * #GUnixCredentialsMessage type and
4424 * g_unix_connection_send_credentials() /
4425 * g_unix_connection_receive_credentials() functions.
4427 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4428 * that must be freed with g_object_unref().
4433 g_socket_get_credentials (GSocket *socket,
4438 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4439 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4443 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
4447 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
4448 socklen_t optlen = sizeof (native_creds_buf);
4450 if (getsockopt (socket->priv->fd,
4456 ret = g_credentials_new ();
4457 g_credentials_set_native (ret,
4458 G_CREDENTIALS_NATIVE_TYPE,
4462 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
4464 ucred_t *ucred = NULL;
4466 if (getpeerucred (socket->priv->fd, &ucred) == 0)
4468 ret = g_credentials_new ();
4469 g_credentials_set_native (ret,
4470 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
4476 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
4481 int errsv = get_socket_errno ();
4485 socket_io_error_from_errno (errsv),
4486 _("Unable to read socket credentials: %s"),
4487 socket_strerror (errsv));
4492 g_set_error_literal (error,
4494 G_IO_ERROR_NOT_SUPPORTED,
4495 _("g_socket_get_credentials not implemented for this OS"));
4502 * g_socket_get_option:
4503 * @socket: a #GSocket
4504 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
4505 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
4506 * @value: (out): return location for the option value
4507 * @error: #GError for error reporting, or %NULL to ignore.
4509 * Gets the value of an integer-valued option on @socket, as with
4510 * getsockopt(). (If you need to fetch a non-integer-valued option,
4511 * you will need to call getsockopt() directly.)
4513 * The [<gio/gnetworking.h>][gio-gnetworking.h]
4514 * header pulls in system headers that will define most of the
4515 * standard/portable socket options. For unusual socket protocols or
4516 * platform-dependent options, you may need to include additional
4519 * Note that even for socket options that are a single byte in size,
4520 * @value is still a pointer to a #gint variable, not a #guchar;
4521 * g_socket_get_option() will handle the conversion internally.
4523 * Returns: success or failure. On failure, @error will be set, and
4524 * the system error value (`errno` or WSAGetLastError()) will still
4525 * be set to the result of the getsockopt() call.
4530 g_socket_get_option (GSocket *socket,
4538 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4541 size = sizeof (gint);
4542 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
4544 int errsv = get_socket_errno ();
4546 g_set_error_literal (error,
4548 socket_io_error_from_errno (errsv),
4549 socket_strerror (errsv));
4551 /* Reset errno in case the caller wants to look at it */
4557 #if G_BYTE_ORDER == G_BIG_ENDIAN
4558 /* If the returned value is smaller than an int then we need to
4559 * slide it over into the low-order bytes of *value.
4561 if (size != sizeof (gint))
4562 *value = *value >> (8 * (sizeof (gint) - size));
4569 * g_socket_set_option:
4570 * @socket: a #GSocket
4571 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
4572 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
4573 * @value: the value to set the option to
4574 * @error: #GError for error reporting, or %NULL to ignore.
4576 * Sets the value of an integer-valued option on @socket, as with
4577 * setsockopt(). (If you need to set a non-integer-valued option,
4578 * you will need to call setsockopt() directly.)
4580 * The [<gio/gnetworking.h>][gio-gnetworking.h]
4581 * header pulls in system headers that will define most of the
4582 * standard/portable socket options. For unusual socket protocols or
4583 * platform-dependent options, you may need to include additional
4586 * Returns: success or failure. On failure, @error will be set, and
4587 * the system error value (`errno` or WSAGetLastError()) will still
4588 * be set to the result of the setsockopt() call.
4593 g_socket_set_option (GSocket *socket,
4601 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4603 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
4606 #if !defined (__linux__) && !defined (G_OS_WIN32)
4607 /* Linux and Windows let you set a single-byte value from an int,
4608 * but most other platforms don't.
4610 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
4612 #if G_BYTE_ORDER == G_BIG_ENDIAN
4613 value = value << (8 * (sizeof (gint) - 1));
4615 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
4620 errsv = get_socket_errno ();
4622 g_set_error_literal (error,
4624 socket_io_error_from_errno (errsv),
4625 socket_strerror (errsv));