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, write to the
19 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20 * Boston, MA 02111-1307, USA.
22 * Authors: Christian Kellner <gicmo@gnome.org>
23 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
24 * Ryan Lortie <desrt@desrt.ca>
25 * Alexander Larsson <alexl@redhat.com>
33 #include "glib-unix.h"
44 # include <sys/ioctl.h>
47 #ifdef HAVE_SYS_FILIO_H
48 # include <sys/filio.h>
55 #include "gcancellable.h"
56 #include "gioenumtypes.h"
57 #include "ginetaddress.h"
58 #include "ginitable.h"
62 #include "gnetworkingprivate.h"
63 #include "gsocketaddress.h"
64 #include "gsocketcontrolmessage.h"
65 #include "gcredentials.h"
70 * @short_description: Low-level socket object
72 * @see_also: #GInitable, <link linkend="gio-gnetworking.h">gnetworking.h</link>
74 * A #GSocket is a low-level networking primitive. It is a more or less
75 * direct mapping of the BSD socket API in a portable GObject based API.
76 * It supports both the UNIX socket implementations and winsock2 on Windows.
78 * #GSocket is the platform independent base upon which the higher level
79 * network primitives are based. Applications are not typically meant to
80 * use it directly, but rather through classes like #GSocketClient,
81 * #GSocketService and #GSocketConnection. However there may be cases where
82 * direct use of #GSocket is useful.
84 * #GSocket implements the #GInitable interface, so if it is manually constructed
85 * by e.g. g_object_new() you must call g_initable_init() and check the
86 * results before using the object. This is done automatically in
87 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
90 * Sockets operate in two general modes, blocking or non-blocking. When
91 * in blocking mode all operations block until the requested operation
92 * is finished or there is an error. In non-blocking mode all calls that
93 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
94 * To know when a call would successfully run you can call g_socket_condition_check(),
95 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
96 * attach it to a #GMainContext to get callbacks when I/O is possible.
97 * Note that all sockets are always set to non blocking mode in the system, and
98 * blocking mode is emulated in GSocket.
100 * When working in non-blocking mode applications should always be able to
101 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
102 * function said that I/O was possible. This can easily happen in case
103 * of a race condition in the application, but it can also happen for other
104 * reasons. For instance, on Windows a socket is always seen as writable
105 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
107 * #GSocket<!-- -->s can be either connection oriented or datagram based.
108 * For connection oriented types you must first establish a connection by
109 * either connecting to an address or accepting a connection from another
110 * address. For connectionless socket types the target/source address is
111 * specified or received in each I/O operation.
113 * All socket file descriptors are set to be close-on-exec.
115 * Note that creating a #GSocket causes the signal %SIGPIPE to be
116 * ignored for the remainder of the program. If you are writing a
117 * command-line utility that uses #GSocket, you may need to take into
118 * account the fact that your program will not automatically be killed
119 * if it tries to write to %stdout after it has been closed.
124 static void g_socket_initable_iface_init (GInitableIface *iface);
125 static gboolean g_socket_initable_init (GInitable *initable,
126 GCancellable *cancellable,
144 PROP_MULTICAST_LOOPBACK,
148 /* Size of the receiver cache for g_socket_receive_from() */
149 #define RECV_ADDR_CACHE_SIZE 8
151 struct _GSocketPrivate
153 GSocketFamily family;
155 GSocketProtocol protocol;
159 GError *construct_error;
160 GSocketAddress *remote_address;
168 guint connect_pending : 1;
174 GList *requested_conditions; /* list of requested GIOCondition * */
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_errno (err);
210 return G_IO_ERROR_ADDRESS_IN_USE;
212 return G_IO_ERROR_WOULD_BLOCK;
214 return G_IO_ERROR_PERMISSION_DENIED;
215 case WSA_INVALID_HANDLE:
216 case WSA_INVALID_PARAMETER:
219 return G_IO_ERROR_INVALID_ARGUMENT;
220 case WSAEPROTONOSUPPORT:
221 return G_IO_ERROR_NOT_SUPPORTED;
223 return G_IO_ERROR_CANCELLED;
224 case WSAESOCKTNOSUPPORT:
226 case WSAEPFNOSUPPORT:
227 case WSAEAFNOSUPPORT:
228 return G_IO_ERROR_NOT_SUPPORTED;
230 return G_IO_ERROR_FAILED;
236 socket_strerror (int err)
239 return g_strerror (err);
244 msg = g_win32_error_message (err);
246 msg_ret = g_intern_string (msg);
254 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
256 _win32_unset_event_mask (GSocket *socket, int mask)
258 socket->priv->current_events &= ~mask;
259 socket->priv->current_errors &= ~mask;
262 #define win32_unset_event_mask(_socket, _mask)
265 /* Windows has broken prototypes... */
267 #define getsockopt(sockfd, level, optname, optval, optlen) \
268 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
269 #define setsockopt(sockfd, level, optname, optval, optlen) \
270 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
271 #define getsockname(sockfd, addr, addrlen) \
272 getsockname (sockfd, addr, (int *)addrlen)
273 #define getpeername(sockfd, addr, addrlen) \
274 getpeername (sockfd, addr, (int *)addrlen)
275 #define recv(sockfd, buf, len, flags) \
276 recv (sockfd, (gpointer)buf, len, flags)
280 set_fd_nonblocking (int fd)
283 GError *error = NULL;
289 if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
291 g_warning ("Error setting socket nonblocking: %s", error->message);
292 g_clear_error (&error);
297 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
299 int errsv = get_socket_errno ();
300 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
306 check_socket (GSocket *socket,
309 if (!socket->priv->inited)
311 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
312 _("Invalid socket, not initialized"));
316 if (socket->priv->construct_error)
318 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
319 _("Invalid socket, initialization failed due to: %s"),
320 socket->priv->construct_error->message);
324 if (socket->priv->closed)
326 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
327 _("Socket is already closed"));
331 if (socket->priv->timed_out)
333 socket->priv->timed_out = FALSE;
334 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
335 _("Socket I/O timed out"));
343 g_socket_details_from_fd (GSocket *socket)
345 struct sockaddr_storage address;
351 fd = socket->priv->fd;
352 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
354 errsv = get_socket_errno ();
366 /* programmer error */
367 g_error ("creating GSocket from fd %d: %s\n",
368 fd, socket_strerror (errsv));
379 socket->priv->type = G_SOCKET_TYPE_STREAM;
383 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
387 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
391 socket->priv->type = G_SOCKET_TYPE_INVALID;
395 addrlen = sizeof address;
396 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
398 errsv = get_socket_errno ();
404 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
405 sizeof address.ss_family <= addrlen);
406 family = address.ss_family;
410 /* On Solaris, this happens if the socket is not yet connected.
411 * But we can use SO_DOMAIN as a workaround there.
414 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
416 errsv = get_socket_errno ();
420 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
428 case G_SOCKET_FAMILY_IPV4:
429 case G_SOCKET_FAMILY_IPV6:
430 socket->priv->family = address.ss_family;
431 switch (socket->priv->type)
433 case G_SOCKET_TYPE_STREAM:
434 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
437 case G_SOCKET_TYPE_DATAGRAM:
438 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
441 case G_SOCKET_TYPE_SEQPACKET:
442 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
450 case G_SOCKET_FAMILY_UNIX:
451 socket->priv->family = G_SOCKET_FAMILY_UNIX;
452 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
456 socket->priv->family = G_SOCKET_FAMILY_INVALID;
460 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
462 addrlen = sizeof address;
463 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
464 socket->priv->connected = TRUE;
467 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
469 socket->priv->keepalive = !!value;
473 /* Can't read, maybe not supported, assume FALSE */
474 socket->priv->keepalive = FALSE;
480 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
481 socket_io_error_from_errno (errsv),
482 _("creating GSocket from fd: %s"),
483 socket_strerror (errsv));
486 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
488 g_socket (gint domain,
496 fd = socket (domain, type | SOCK_CLOEXEC, protocol);
500 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
501 if (fd < 0 && errno == EINVAL)
503 fd = socket (domain, type, protocol);
507 int errsv = get_socket_errno ();
509 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
510 _("Unable to create socket: %s"), socket_strerror (errsv));
519 /* We always want to set close-on-exec to protect users. If you
520 need to so some weird inheritance to exec you can re-enable this
521 using lower level hacks with g_socket_get_fd(). */
522 flags = fcntl (fd, F_GETFD, 0);
524 (flags & FD_CLOEXEC) == 0)
527 fcntl (fd, F_SETFD, flags);
536 g_socket_create_socket (GSocketFamily family,
545 case G_SOCKET_TYPE_STREAM:
546 native_type = SOCK_STREAM;
549 case G_SOCKET_TYPE_DATAGRAM:
550 native_type = SOCK_DGRAM;
553 case G_SOCKET_TYPE_SEQPACKET:
554 native_type = SOCK_SEQPACKET;
558 g_assert_not_reached ();
563 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
564 _("Unable to create socket: %s"), _("Unknown family was specified"));
570 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
571 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
575 return g_socket (family, native_type, protocol, error);
579 g_socket_constructed (GObject *object)
581 GSocket *socket = G_SOCKET (object);
583 if (socket->priv->fd >= 0)
584 /* create socket->priv info from the fd */
585 g_socket_details_from_fd (socket);
588 /* create the fd from socket->priv info */
589 socket->priv->fd = g_socket_create_socket (socket->priv->family,
591 socket->priv->protocol,
592 &socket->priv->construct_error);
594 /* Always use native nonblocking sockets, as
595 windows sets sockets to nonblocking automatically
596 in certain operations. This way we make things work
597 the same on all platforms */
598 if (socket->priv->fd != -1)
599 set_fd_nonblocking (socket->priv->fd);
603 g_socket_get_property (GObject *object,
608 GSocket *socket = G_SOCKET (object);
609 GSocketAddress *address;
614 g_value_set_enum (value, socket->priv->family);
618 g_value_set_enum (value, socket->priv->type);
622 g_value_set_enum (value, socket->priv->protocol);
626 g_value_set_int (value, socket->priv->fd);
630 g_value_set_boolean (value, socket->priv->blocking);
633 case PROP_LISTEN_BACKLOG:
634 g_value_set_int (value, socket->priv->listen_backlog);
638 g_value_set_boolean (value, socket->priv->keepalive);
641 case PROP_LOCAL_ADDRESS:
642 address = g_socket_get_local_address (socket, NULL);
643 g_value_take_object (value, address);
646 case PROP_REMOTE_ADDRESS:
647 address = g_socket_get_remote_address (socket, NULL);
648 g_value_take_object (value, address);
652 g_value_set_uint (value, socket->priv->timeout);
656 g_value_set_uint (value, g_socket_get_ttl (socket));
660 g_value_set_boolean (value, g_socket_get_broadcast (socket));
663 case PROP_MULTICAST_LOOPBACK:
664 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
667 case PROP_MULTICAST_TTL:
668 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
672 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
677 g_socket_set_property (GObject *object,
682 GSocket *socket = G_SOCKET (object);
687 socket->priv->family = g_value_get_enum (value);
691 socket->priv->type = g_value_get_enum (value);
695 socket->priv->protocol = g_value_get_enum (value);
699 socket->priv->fd = g_value_get_int (value);
703 g_socket_set_blocking (socket, g_value_get_boolean (value));
706 case PROP_LISTEN_BACKLOG:
707 g_socket_set_listen_backlog (socket, g_value_get_int (value));
711 g_socket_set_keepalive (socket, g_value_get_boolean (value));
715 g_socket_set_timeout (socket, g_value_get_uint (value));
719 g_socket_set_ttl (socket, g_value_get_uint (value));
723 g_socket_set_broadcast (socket, g_value_get_boolean (value));
726 case PROP_MULTICAST_LOOPBACK:
727 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
730 case PROP_MULTICAST_TTL:
731 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
735 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
740 g_socket_finalize (GObject *object)
742 GSocket *socket = G_SOCKET (object);
745 g_clear_error (&socket->priv->construct_error);
747 if (socket->priv->fd != -1 &&
748 !socket->priv->closed)
749 g_socket_close (socket, NULL);
751 if (socket->priv->remote_address)
752 g_object_unref (socket->priv->remote_address);
755 if (socket->priv->event != WSA_INVALID_EVENT)
757 WSACloseEvent (socket->priv->event);
758 socket->priv->event = WSA_INVALID_EVENT;
761 g_assert (socket->priv->requested_conditions == NULL);
764 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
766 if (socket->priv->recv_addr_cache[i].addr)
768 g_object_unref (socket->priv->recv_addr_cache[i].addr);
769 g_free (socket->priv->recv_addr_cache[i].native);
773 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
774 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
778 g_socket_class_init (GSocketClass *klass)
780 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
783 /* There is no portable, thread-safe way to avoid having the process
784 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
785 * forced to simply ignore the signal process-wide.
787 signal (SIGPIPE, SIG_IGN);
790 gobject_class->finalize = g_socket_finalize;
791 gobject_class->constructed = g_socket_constructed;
792 gobject_class->set_property = g_socket_set_property;
793 gobject_class->get_property = g_socket_get_property;
795 g_object_class_install_property (gobject_class, PROP_FAMILY,
796 g_param_spec_enum ("family",
798 P_("The sockets address family"),
799 G_TYPE_SOCKET_FAMILY,
800 G_SOCKET_FAMILY_INVALID,
801 G_PARAM_CONSTRUCT_ONLY |
803 G_PARAM_STATIC_STRINGS));
805 g_object_class_install_property (gobject_class, PROP_TYPE,
806 g_param_spec_enum ("type",
808 P_("The sockets type"),
810 G_SOCKET_TYPE_STREAM,
811 G_PARAM_CONSTRUCT_ONLY |
813 G_PARAM_STATIC_STRINGS));
815 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
816 g_param_spec_enum ("protocol",
817 P_("Socket protocol"),
818 P_("The id of the protocol to use, or -1 for unknown"),
819 G_TYPE_SOCKET_PROTOCOL,
820 G_SOCKET_PROTOCOL_UNKNOWN,
821 G_PARAM_CONSTRUCT_ONLY |
823 G_PARAM_STATIC_STRINGS));
825 g_object_class_install_property (gobject_class, PROP_FD,
826 g_param_spec_int ("fd",
827 P_("File descriptor"),
828 P_("The sockets file descriptor"),
832 G_PARAM_CONSTRUCT_ONLY |
834 G_PARAM_STATIC_STRINGS));
836 g_object_class_install_property (gobject_class, PROP_BLOCKING,
837 g_param_spec_boolean ("blocking",
839 P_("Whether or not I/O on this socket is blocking"),
842 G_PARAM_STATIC_STRINGS));
844 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
845 g_param_spec_int ("listen-backlog",
846 P_("Listen backlog"),
847 P_("Outstanding connections in the listen queue"),
852 G_PARAM_STATIC_STRINGS));
854 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
855 g_param_spec_boolean ("keepalive",
856 P_("Keep connection alive"),
857 P_("Keep connection alive by sending periodic pings"),
860 G_PARAM_STATIC_STRINGS));
862 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
863 g_param_spec_object ("local-address",
865 P_("The local address the socket is bound to"),
866 G_TYPE_SOCKET_ADDRESS,
868 G_PARAM_STATIC_STRINGS));
870 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
871 g_param_spec_object ("remote-address",
872 P_("Remote address"),
873 P_("The remote address the socket is connected to"),
874 G_TYPE_SOCKET_ADDRESS,
876 G_PARAM_STATIC_STRINGS));
881 * The timeout in seconds on socket I/O
885 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
886 g_param_spec_uint ("timeout",
888 P_("The timeout in seconds on socket I/O"),
893 G_PARAM_STATIC_STRINGS));
898 * Whether the socket should allow sending to broadcast addresses.
902 g_object_class_install_property (gobject_class, PROP_BROADCAST,
903 g_param_spec_boolean ("broadcast",
905 P_("Whether to allow sending to broadcast addresses"),
908 G_PARAM_STATIC_STRINGS));
913 * Time-to-live for outgoing unicast packets
917 g_object_class_install_property (gobject_class, PROP_TTL,
918 g_param_spec_uint ("ttl",
920 P_("Time-to-live of outgoing unicast packets"),
923 G_PARAM_STATIC_STRINGS));
926 * GSocket:multicast-loopback:
928 * Whether outgoing multicast packets loop back to the local host.
932 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
933 g_param_spec_boolean ("multicast-loopback",
934 P_("Multicast loopback"),
935 P_("Whether outgoing multicast packets loop back to the local host"),
938 G_PARAM_STATIC_STRINGS));
941 * GSocket:multicast-ttl:
943 * Time-to-live out outgoing multicast packets
947 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
948 g_param_spec_uint ("multicast-ttl",
950 P_("Time-to-live of outgoing multicast packets"),
953 G_PARAM_STATIC_STRINGS));
957 g_socket_initable_iface_init (GInitableIface *iface)
959 iface->init = g_socket_initable_init;
963 g_socket_init (GSocket *socket)
965 socket->priv = g_socket_get_instance_private (socket);
967 socket->priv->fd = -1;
968 socket->priv->blocking = TRUE;
969 socket->priv->listen_backlog = 10;
970 socket->priv->construct_error = NULL;
972 socket->priv->event = WSA_INVALID_EVENT;
977 g_socket_initable_init (GInitable *initable,
978 GCancellable *cancellable,
983 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
985 socket = G_SOCKET (initable);
987 if (cancellable != NULL)
989 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
990 _("Cancellable initialization not supported"));
994 socket->priv->inited = TRUE;
996 if (socket->priv->construct_error)
999 *error = g_error_copy (socket->priv->construct_error);
1009 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1010 * @type: the socket type to use.
1011 * @protocol: the id of the protocol to use, or 0 for default.
1012 * @error: #GError for error reporting, or %NULL to ignore.
1014 * Creates a new #GSocket with the defined family, type and protocol.
1015 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1016 * for the family and type is used.
1018 * The @protocol is a family and type specific int that specifies what
1019 * kind of protocol to use. #GSocketProtocol lists several common ones.
1020 * Many families only support one protocol, and use 0 for this, others
1021 * support several and using 0 means to use the default protocol for
1022 * the family and type.
1024 * The protocol id is passed directly to the operating
1025 * system, so you can use protocols not listed in #GSocketProtocol if you
1026 * know the protocol number used for it.
1028 * Returns: a #GSocket or %NULL on error.
1029 * Free the returned object with g_object_unref().
1034 g_socket_new (GSocketFamily family,
1036 GSocketProtocol protocol,
1039 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1043 "protocol", protocol,
1048 * g_socket_new_from_fd:
1049 * @fd: a native socket file descriptor.
1050 * @error: #GError for error reporting, or %NULL to ignore.
1052 * Creates a new #GSocket from a native file descriptor
1053 * or winsock SOCKET handle.
1055 * This reads all the settings from the file descriptor so that
1056 * all properties should work. Note that the file descriptor
1057 * will be set to non-blocking mode, independent on the blocking
1058 * mode of the #GSocket.
1060 * Returns: a #GSocket or %NULL on error.
1061 * Free the returned object with g_object_unref().
1066 g_socket_new_from_fd (gint fd,
1069 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1076 * g_socket_set_blocking:
1077 * @socket: a #GSocket.
1078 * @blocking: Whether to use blocking I/O or not.
1080 * Sets the blocking mode of the socket. In blocking mode
1081 * all operations block until they succeed or there is an error. In
1082 * non-blocking mode all functions return results immediately or
1083 * with a %G_IO_ERROR_WOULD_BLOCK error.
1085 * All sockets are created in blocking mode. However, note that the
1086 * platform level socket is always non-blocking, and blocking mode
1087 * is a GSocket level feature.
1092 g_socket_set_blocking (GSocket *socket,
1095 g_return_if_fail (G_IS_SOCKET (socket));
1097 blocking = !!blocking;
1099 if (socket->priv->blocking == blocking)
1102 socket->priv->blocking = blocking;
1103 g_object_notify (G_OBJECT (socket), "blocking");
1107 * g_socket_get_blocking:
1108 * @socket: a #GSocket.
1110 * Gets the blocking mode of the socket. For details on blocking I/O,
1111 * see g_socket_set_blocking().
1113 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1118 g_socket_get_blocking (GSocket *socket)
1120 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1122 return socket->priv->blocking;
1126 * g_socket_set_keepalive:
1127 * @socket: a #GSocket.
1128 * @keepalive: Value for the keepalive flag
1130 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1131 * this flag is set on a socket, the system will attempt to verify that the
1132 * remote socket endpoint is still present if a sufficiently long period of
1133 * time passes with no data being exchanged. If the system is unable to
1134 * verify the presence of the remote endpoint, it will automatically close
1137 * This option is only functional on certain kinds of sockets. (Notably,
1138 * %G_SOCKET_PROTOCOL_TCP sockets.)
1140 * The exact time between pings is system- and protocol-dependent, but will
1141 * normally be at least two hours. Most commonly, you would set this flag
1142 * on a server socket if you want to allow clients to remain idle for long
1143 * periods of time, but also want to ensure that connections are eventually
1144 * garbage-collected if clients crash or become unreachable.
1149 g_socket_set_keepalive (GSocket *socket,
1152 GError *error = NULL;
1154 g_return_if_fail (G_IS_SOCKET (socket));
1156 keepalive = !!keepalive;
1157 if (socket->priv->keepalive == keepalive)
1160 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1163 g_warning ("error setting keepalive: %s", error->message);
1164 g_error_free (error);
1168 socket->priv->keepalive = keepalive;
1169 g_object_notify (G_OBJECT (socket), "keepalive");
1173 * g_socket_get_keepalive:
1174 * @socket: a #GSocket.
1176 * Gets the keepalive mode of the socket. For details on this,
1177 * see g_socket_set_keepalive().
1179 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1184 g_socket_get_keepalive (GSocket *socket)
1186 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1188 return socket->priv->keepalive;
1192 * g_socket_get_listen_backlog:
1193 * @socket: a #GSocket.
1195 * Gets the listen backlog setting of the socket. For details on this,
1196 * see g_socket_set_listen_backlog().
1198 * Returns: the maximum number of pending connections.
1203 g_socket_get_listen_backlog (GSocket *socket)
1205 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1207 return socket->priv->listen_backlog;
1211 * g_socket_set_listen_backlog:
1212 * @socket: a #GSocket.
1213 * @backlog: the maximum number of pending connections.
1215 * Sets the maximum number of outstanding connections allowed
1216 * when listening on this socket. If more clients than this are
1217 * connecting to the socket and the application is not handling them
1218 * on time then the new connections will be refused.
1220 * Note that this must be called before g_socket_listen() and has no
1221 * effect if called after that.
1226 g_socket_set_listen_backlog (GSocket *socket,
1229 g_return_if_fail (G_IS_SOCKET (socket));
1230 g_return_if_fail (!socket->priv->listening);
1232 if (backlog != socket->priv->listen_backlog)
1234 socket->priv->listen_backlog = backlog;
1235 g_object_notify (G_OBJECT (socket), "listen-backlog");
1240 * g_socket_get_timeout:
1241 * @socket: a #GSocket.
1243 * Gets the timeout setting of the socket. For details on this, see
1244 * g_socket_set_timeout().
1246 * Returns: the timeout in seconds
1251 g_socket_get_timeout (GSocket *socket)
1253 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1255 return socket->priv->timeout;
1259 * g_socket_set_timeout:
1260 * @socket: a #GSocket.
1261 * @timeout: the timeout for @socket, in seconds, or 0 for none
1263 * Sets the time in seconds after which I/O operations on @socket will
1264 * time out if they have not yet completed.
1266 * On a blocking socket, this means that any blocking #GSocket
1267 * operation will time out after @timeout seconds of inactivity,
1268 * returning %G_IO_ERROR_TIMED_OUT.
1270 * On a non-blocking socket, calls to g_socket_condition_wait() will
1271 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1272 * created with g_socket_create_source() will trigger after
1273 * @timeout seconds of inactivity, with the requested condition
1274 * set, at which point calling g_socket_receive(), g_socket_send(),
1275 * g_socket_check_connect_result(), etc, will fail with
1276 * %G_IO_ERROR_TIMED_OUT.
1278 * If @timeout is 0 (the default), operations will never time out
1281 * Note that if an I/O operation is interrupted by a signal, this may
1282 * cause the timeout to be reset.
1287 g_socket_set_timeout (GSocket *socket,
1290 g_return_if_fail (G_IS_SOCKET (socket));
1292 if (timeout != socket->priv->timeout)
1294 socket->priv->timeout = timeout;
1295 g_object_notify (G_OBJECT (socket), "timeout");
1301 * @socket: a #GSocket.
1303 * Gets the unicast time-to-live setting on @socket; see
1304 * g_socket_set_ttl() for more details.
1306 * Returns: the time-to-live setting on @socket
1311 g_socket_get_ttl (GSocket *socket)
1313 GError *error = NULL;
1316 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1318 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1320 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1323 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1325 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1329 g_return_val_if_reached (0);
1333 g_warning ("error getting unicast ttl: %s", error->message);
1334 g_error_free (error);
1343 * @socket: a #GSocket.
1344 * @ttl: the time-to-live value for all unicast packets on @socket
1346 * Sets the time-to-live for outgoing unicast packets on @socket.
1347 * By default the platform-specific default value is used.
1352 g_socket_set_ttl (GSocket *socket,
1355 GError *error = NULL;
1357 g_return_if_fail (G_IS_SOCKET (socket));
1359 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1361 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1364 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1366 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1368 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1372 g_return_if_reached ();
1376 g_warning ("error setting unicast ttl: %s", error->message);
1377 g_error_free (error);
1381 g_object_notify (G_OBJECT (socket), "ttl");
1385 * g_socket_get_broadcast:
1386 * @socket: a #GSocket.
1388 * Gets the broadcast setting on @socket; if %TRUE,
1389 * it is possible to send packets to broadcast
1392 * Returns: the broadcast setting on @socket
1397 g_socket_get_broadcast (GSocket *socket)
1399 GError *error = NULL;
1402 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1404 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1407 g_warning ("error getting broadcast: %s", error->message);
1408 g_error_free (error);
1416 * g_socket_set_broadcast:
1417 * @socket: a #GSocket.
1418 * @broadcast: whether @socket should allow sending to broadcast
1421 * Sets whether @socket should allow sending to broadcast addresses.
1422 * This is %FALSE by default.
1427 g_socket_set_broadcast (GSocket *socket,
1430 GError *error = NULL;
1432 g_return_if_fail (G_IS_SOCKET (socket));
1434 broadcast = !!broadcast;
1436 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1439 g_warning ("error setting broadcast: %s", error->message);
1440 g_error_free (error);
1444 g_object_notify (G_OBJECT (socket), "broadcast");
1448 * g_socket_get_multicast_loopback:
1449 * @socket: a #GSocket.
1451 * Gets the multicast loopback setting on @socket; if %TRUE (the
1452 * default), outgoing multicast packets will be looped back to
1453 * multicast listeners on the same host.
1455 * Returns: the multicast loopback setting on @socket
1460 g_socket_get_multicast_loopback (GSocket *socket)
1462 GError *error = NULL;
1465 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1467 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1469 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1472 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1474 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1478 g_return_val_if_reached (FALSE);
1482 g_warning ("error getting multicast loopback: %s", error->message);
1483 g_error_free (error);
1491 * g_socket_set_multicast_loopback:
1492 * @socket: a #GSocket.
1493 * @loopback: whether @socket should receive messages sent to its
1494 * multicast groups from the local host
1496 * Sets whether outgoing multicast packets will be received by sockets
1497 * listening on that multicast address on the same host. This is %TRUE
1503 g_socket_set_multicast_loopback (GSocket *socket,
1506 GError *error = NULL;
1508 g_return_if_fail (G_IS_SOCKET (socket));
1510 loopback = !!loopback;
1512 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1514 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1517 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1519 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1521 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1525 g_return_if_reached ();
1529 g_warning ("error setting multicast loopback: %s", error->message);
1530 g_error_free (error);
1534 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1538 * g_socket_get_multicast_ttl:
1539 * @socket: a #GSocket.
1541 * Gets the multicast time-to-live setting on @socket; see
1542 * g_socket_set_multicast_ttl() for more details.
1544 * Returns: the multicast time-to-live setting on @socket
1549 g_socket_get_multicast_ttl (GSocket *socket)
1551 GError *error = NULL;
1554 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1556 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1558 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1561 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1563 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1567 g_return_val_if_reached (FALSE);
1571 g_warning ("error getting multicast ttl: %s", error->message);
1572 g_error_free (error);
1580 * g_socket_set_multicast_ttl:
1581 * @socket: a #GSocket.
1582 * @ttl: the time-to-live value for all multicast datagrams on @socket
1584 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1585 * By default, this is 1, meaning that multicast packets will not leave
1586 * the local network.
1591 g_socket_set_multicast_ttl (GSocket *socket,
1594 GError *error = NULL;
1596 g_return_if_fail (G_IS_SOCKET (socket));
1598 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1600 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1603 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1605 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1607 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1611 g_return_if_reached ();
1615 g_warning ("error setting multicast ttl: %s", error->message);
1616 g_error_free (error);
1620 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1624 * g_socket_get_family:
1625 * @socket: a #GSocket.
1627 * Gets the socket family of the socket.
1629 * Returns: a #GSocketFamily
1634 g_socket_get_family (GSocket *socket)
1636 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1638 return socket->priv->family;
1642 * g_socket_get_socket_type:
1643 * @socket: a #GSocket.
1645 * Gets the socket type of the socket.
1647 * Returns: a #GSocketType
1652 g_socket_get_socket_type (GSocket *socket)
1654 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1656 return socket->priv->type;
1660 * g_socket_get_protocol:
1661 * @socket: a #GSocket.
1663 * Gets the socket protocol id the socket was created with.
1664 * In case the protocol is unknown, -1 is returned.
1666 * Returns: a protocol id, or -1 if unknown
1671 g_socket_get_protocol (GSocket *socket)
1673 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1675 return socket->priv->protocol;
1680 * @socket: a #GSocket.
1682 * Returns the underlying OS socket object. On unix this
1683 * is a socket file descriptor, and on Windows this is
1684 * a Winsock2 SOCKET handle. This may be useful for
1685 * doing platform specific or otherwise unusual operations
1688 * Returns: the file descriptor of the socket.
1693 g_socket_get_fd (GSocket *socket)
1695 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1697 return socket->priv->fd;
1701 * g_socket_get_local_address:
1702 * @socket: a #GSocket.
1703 * @error: #GError for error reporting, or %NULL to ignore.
1705 * Try to get the local address of a bound socket. This is only
1706 * useful if the socket has been bound to a local address,
1707 * either explicitly or implicitly when connecting.
1709 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1710 * Free the returned object with g_object_unref().
1715 g_socket_get_local_address (GSocket *socket,
1718 struct sockaddr_storage buffer;
1719 guint len = sizeof (buffer);
1721 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1723 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1725 int errsv = get_socket_errno ();
1726 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1727 _("could not get local address: %s"), socket_strerror (errsv));
1731 return g_socket_address_new_from_native (&buffer, len);
1735 * g_socket_get_remote_address:
1736 * @socket: a #GSocket.
1737 * @error: #GError for error reporting, or %NULL to ignore.
1739 * Try to get the remove address of a connected socket. This is only
1740 * useful for connection oriented sockets that have been connected.
1742 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1743 * Free the returned object with g_object_unref().
1748 g_socket_get_remote_address (GSocket *socket,
1751 struct sockaddr_storage buffer;
1752 guint len = sizeof (buffer);
1754 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1756 if (socket->priv->connect_pending)
1758 if (!g_socket_check_connect_result (socket, error))
1761 socket->priv->connect_pending = FALSE;
1764 if (!socket->priv->remote_address)
1766 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1768 int errsv = get_socket_errno ();
1769 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1770 _("could not get remote address: %s"), socket_strerror (errsv));
1774 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1777 return g_object_ref (socket->priv->remote_address);
1781 * g_socket_is_connected:
1782 * @socket: a #GSocket.
1784 * Check whether the socket is connected. This is only useful for
1785 * connection-oriented sockets.
1787 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1792 g_socket_is_connected (GSocket *socket)
1794 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1796 return socket->priv->connected;
1801 * @socket: a #GSocket.
1802 * @error: #GError for error reporting, or %NULL to ignore.
1804 * Marks the socket as a server socket, i.e. a socket that is used
1805 * to accept incoming requests using g_socket_accept().
1807 * Before calling this the socket must be bound to a local address using
1810 * To set the maximum amount of outstanding clients, use
1811 * g_socket_set_listen_backlog().
1813 * Returns: %TRUE on success, %FALSE on error.
1818 g_socket_listen (GSocket *socket,
1821 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1823 if (!check_socket (socket, error))
1826 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1828 int errsv = get_socket_errno ();
1830 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1831 _("could not listen: %s"), socket_strerror (errsv));
1835 socket->priv->listening = TRUE;
1842 * @socket: a #GSocket.
1843 * @address: a #GSocketAddress specifying the local address.
1844 * @allow_reuse: whether to allow reusing this address
1845 * @error: #GError for error reporting, or %NULL to ignore.
1847 * When a socket is created it is attached to an address family, but it
1848 * doesn't have an address in this family. g_socket_bind() assigns the
1849 * address (sometimes called name) of the socket.
1851 * It is generally required to bind to a local address before you can
1852 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1853 * In certain situations, you may also want to bind a socket that will be
1854 * used to initiate connections, though this is not normally required.
1856 * If @socket is a TCP socket, then @allow_reuse controls the setting
1857 * of the <literal>SO_REUSEADDR</literal> socket option; normally it
1858 * should be %TRUE for server sockets (sockets that you will
1859 * eventually call g_socket_accept() on), and %FALSE for client
1860 * sockets. (Failing to set this flag on a server socket may cause
1861 * g_socket_bind() to return %G_IO_ERROR_ADDRESS_IN_USE if the server
1862 * program is stopped and then immediately restarted.)
1864 * If @socket is a UDP socket, then @allow_reuse determines whether or
1865 * not other UDP sockets can be bound to the same address at the same
1866 * time. In particular, you can have several UDP sockets bound to the
1867 * same address, and they will all receive all of the multicast and
1868 * broadcast packets sent to that address. (The behavior of unicast
1869 * UDP packets to an address with multiple listeners is not defined.)
1871 * Returns: %TRUE on success, %FALSE on error.
1876 g_socket_bind (GSocket *socket,
1877 GSocketAddress *address,
1878 gboolean reuse_address,
1881 struct sockaddr_storage addr;
1882 gboolean so_reuseaddr;
1884 gboolean so_reuseport;
1887 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1889 if (!check_socket (socket, error))
1892 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1895 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
1896 * sockets, but has nasty side effects we don't want for TCP
1899 * On other platforms, we set SO_REUSEPORT, if it exists, for
1900 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
1901 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
1902 * the desired semantics on UDP (as it does on Linux, although
1903 * Linux has SO_REUSEPORT too as of 3.9).
1907 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1909 so_reuseaddr = !!reuse_address;
1913 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1916 /* Ignore errors here, the only likely error is "not supported", and
1917 * this is a "best effort" thing mainly.
1919 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
1921 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
1924 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1925 g_socket_address_get_native_size (address)) < 0)
1927 int errsv = get_socket_errno ();
1929 G_IO_ERROR, socket_io_error_from_errno (errsv),
1930 _("Error binding to address: %s"), socket_strerror (errsv));
1938 g_socket_multicast_group_operation (GSocket *socket,
1939 GInetAddress *group,
1940 gboolean source_specific,
1942 gboolean join_group,
1945 const guint8 *native_addr;
1946 gint optname, result;
1948 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1949 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
1950 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
1952 if (!check_socket (socket, error))
1955 native_addr = g_inet_address_to_bytes (group);
1956 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
1958 #ifdef HAVE_IP_MREQN
1959 struct ip_mreqn mc_req;
1961 struct ip_mreq mc_req;
1964 memset (&mc_req, 0, sizeof (mc_req));
1965 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
1967 #ifdef HAVE_IP_MREQN
1969 mc_req.imr_ifindex = if_nametoindex (iface);
1971 mc_req.imr_ifindex = 0; /* Pick any. */
1973 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
1976 if (source_specific)
1978 #ifdef IP_ADD_SOURCE_MEMBERSHIP
1979 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
1981 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1983 _("Error joining multicast group: %s") :
1984 _("Error leaving multicast group: %s"),
1985 _("No support for source-specific multicast"));
1990 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
1991 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
1992 &mc_req, sizeof (mc_req));
1994 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
1996 struct ipv6_mreq mc_req_ipv6;
1998 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
1999 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2000 #ifdef HAVE_IF_NAMETOINDEX
2002 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2005 mc_req_ipv6.ipv6mr_interface = 0;
2007 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2008 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2009 &mc_req_ipv6, sizeof (mc_req_ipv6));
2012 g_return_val_if_reached (FALSE);
2016 int errsv = get_socket_errno ();
2018 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2020 _("Error joining multicast group: %s") :
2021 _("Error leaving multicast group: %s"),
2022 socket_strerror (errsv));
2030 * g_socket_join_multicast_group:
2031 * @socket: a #GSocket.
2032 * @group: a #GInetAddress specifying the group address to join.
2033 * @iface: (allow-none): Name of the interface to use, or %NULL
2034 * @source_specific: %TRUE if source-specific multicast should be used
2035 * @error: #GError for error reporting, or %NULL to ignore.
2037 * Registers @socket to receive multicast messages sent to @group.
2038 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2039 * been bound to an appropriate interface and port with
2042 * If @iface is %NULL, the system will automatically pick an interface
2043 * to bind to based on @group.
2045 * If @source_specific is %TRUE, source-specific multicast as defined
2046 * in RFC 4604 is used. Note that on older platforms this may fail
2047 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2049 * Returns: %TRUE on success, %FALSE on error.
2054 g_socket_join_multicast_group (GSocket *socket,
2055 GInetAddress *group,
2056 gboolean source_specific,
2060 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2064 * g_socket_leave_multicast_group:
2065 * @socket: a #GSocket.
2066 * @group: a #GInetAddress specifying the group address to leave.
2067 * @iface: (allow-none): Interface used
2068 * @source_specific: %TRUE if source-specific multicast was used
2069 * @error: #GError for error reporting, or %NULL to ignore.
2071 * Removes @socket from the multicast group defined by @group, @iface,
2072 * and @source_specific (which must all have the same values they had
2073 * when you joined the group).
2075 * @socket remains bound to its address and port, and can still receive
2076 * unicast messages after calling this.
2078 * Returns: %TRUE on success, %FALSE on error.
2083 g_socket_leave_multicast_group (GSocket *socket,
2084 GInetAddress *group,
2085 gboolean source_specific,
2089 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2093 * g_socket_speaks_ipv4:
2094 * @socket: a #GSocket
2096 * Checks if a socket is capable of speaking IPv4.
2098 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2099 * and under some combinations of circumstances IPv6 sockets are also
2100 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2103 * No other types of sockets are currently considered as being capable
2106 * Returns: %TRUE if this socket can be used with IPv4.
2111 g_socket_speaks_ipv4 (GSocket *socket)
2113 switch (socket->priv->family)
2115 case G_SOCKET_FAMILY_IPV4:
2118 case G_SOCKET_FAMILY_IPV6:
2119 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2123 if (!g_socket_get_option (socket,
2124 IPPROTO_IPV6, IPV6_V6ONLY,
2141 * @socket: a #GSocket.
2142 * @cancellable: (allow-none): a %GCancellable or %NULL
2143 * @error: #GError for error reporting, or %NULL to ignore.
2145 * Accept incoming connections on a connection-based socket. This removes
2146 * the first outstanding connection request from the listening socket and
2147 * creates a #GSocket object for it.
2149 * The @socket must be bound to a local address with g_socket_bind() and
2150 * must be listening for incoming connections (g_socket_listen()).
2152 * If there are no outstanding connections then the operation will block
2153 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2154 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2156 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2157 * Free the returned object with g_object_unref().
2162 g_socket_accept (GSocket *socket,
2163 GCancellable *cancellable,
2166 GSocket *new_socket;
2169 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2171 if (!check_socket (socket, error))
2176 if (socket->priv->blocking &&
2177 !g_socket_condition_wait (socket,
2178 G_IO_IN, cancellable, error))
2181 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2183 int errsv = get_socket_errno ();
2185 win32_unset_event_mask (socket, FD_ACCEPT);
2190 if (socket->priv->blocking)
2192 #ifdef WSAEWOULDBLOCK
2193 if (errsv == WSAEWOULDBLOCK)
2196 if (errsv == EWOULDBLOCK ||
2202 g_set_error (error, G_IO_ERROR,
2203 socket_io_error_from_errno (errsv),
2204 _("Error accepting connection: %s"), socket_strerror (errsv));
2210 win32_unset_event_mask (socket, FD_ACCEPT);
2214 /* The socket inherits the accepting sockets event mask and even object,
2215 we need to remove that */
2216 WSAEventSelect (ret, NULL, 0);
2222 /* We always want to set close-on-exec to protect users. If you
2223 need to so some weird inheritance to exec you can re-enable this
2224 using lower level hacks with g_socket_get_fd(). */
2225 flags = fcntl (ret, F_GETFD, 0);
2227 (flags & FD_CLOEXEC) == 0)
2229 flags |= FD_CLOEXEC;
2230 fcntl (ret, F_SETFD, flags);
2235 new_socket = g_socket_new_from_fd (ret, error);
2236 if (new_socket == NULL)
2245 new_socket->priv->protocol = socket->priv->protocol;
2252 * @socket: a #GSocket.
2253 * @address: a #GSocketAddress specifying the remote address.
2254 * @cancellable: (allow-none): a %GCancellable or %NULL
2255 * @error: #GError for error reporting, or %NULL to ignore.
2257 * Connect the socket to the specified remote address.
2259 * For connection oriented socket this generally means we attempt to make
2260 * a connection to the @address. For a connection-less socket it sets
2261 * the default address for g_socket_send() and discards all incoming datagrams
2262 * from other sources.
2264 * Generally connection oriented sockets can only connect once, but
2265 * connection-less sockets can connect multiple times to change the
2268 * If the connect call needs to do network I/O it will block, unless
2269 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2270 * and the user can be notified of the connection finishing by waiting
2271 * for the G_IO_OUT condition. The result of the connection must then be
2272 * checked with g_socket_check_connect_result().
2274 * Returns: %TRUE if connected, %FALSE on error.
2279 g_socket_connect (GSocket *socket,
2280 GSocketAddress *address,
2281 GCancellable *cancellable,
2284 struct sockaddr_storage buffer;
2286 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2288 if (!check_socket (socket, error))
2291 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2294 if (socket->priv->remote_address)
2295 g_object_unref (socket->priv->remote_address);
2296 socket->priv->remote_address = g_object_ref (address);
2300 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2301 g_socket_address_get_native_size (address)) < 0)
2303 int errsv = get_socket_errno ();
2309 if (errsv == EINPROGRESS)
2311 if (errsv == WSAEWOULDBLOCK)
2314 if (socket->priv->blocking)
2316 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2318 if (g_socket_check_connect_result (socket, error))
2324 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2325 _("Connection in progress"));
2326 socket->priv->connect_pending = TRUE;
2330 g_set_error_literal (error, G_IO_ERROR,
2331 socket_io_error_from_errno (errsv),
2332 socket_strerror (errsv));
2339 win32_unset_event_mask (socket, FD_CONNECT);
2341 socket->priv->connected = TRUE;
2347 * g_socket_check_connect_result:
2348 * @socket: a #GSocket
2349 * @error: #GError for error reporting, or %NULL to ignore.
2351 * Checks and resets the pending connect error for the socket.
2352 * This is used to check for errors when g_socket_connect() is
2353 * used in non-blocking mode.
2355 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2360 g_socket_check_connect_result (GSocket *socket,
2365 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2367 if (!check_socket (socket, error))
2370 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
2372 g_prefix_error (error, _("Unable to get pending error: "));
2378 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2379 socket_strerror (value));
2380 if (socket->priv->remote_address)
2382 g_object_unref (socket->priv->remote_address);
2383 socket->priv->remote_address = NULL;
2388 socket->priv->connected = TRUE;
2393 * g_socket_get_available_bytes:
2394 * @socket: a #GSocket
2396 * Get the amount of data pending in the OS input buffer.
2398 * Returns: the number of bytes that can be read from the socket
2399 * without blocking or -1 on error.
2404 g_socket_get_available_bytes (GSocket *socket)
2408 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2411 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2414 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) == SOCKET_ERROR)
2423 * @socket: a #GSocket
2424 * @buffer: (array length=size) (element-type guint8): a buffer to
2425 * read data into (which should be at least @size bytes long).
2426 * @size: the number of bytes you want to read from the socket
2427 * @cancellable: (allow-none): a %GCancellable or %NULL
2428 * @error: #GError for error reporting, or %NULL to ignore.
2430 * Receive data (up to @size bytes) from a socket. This is mainly used by
2431 * connection-oriented sockets; it is identical to g_socket_receive_from()
2432 * with @address set to %NULL.
2434 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2435 * g_socket_receive() will always read either 0 or 1 complete messages from
2436 * the socket. If the received message is too large to fit in @buffer, then
2437 * the data beyond @size bytes will be discarded, without any explicit
2438 * indication that this has occurred.
2440 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2441 * number of bytes, up to @size. If more than @size bytes have been
2442 * received, the additional data will be returned in future calls to
2443 * g_socket_receive().
2445 * If the socket is in blocking mode the call will block until there
2446 * is some data to receive, the connection is closed, or there is an
2447 * error. If there is no data available and the socket is in
2448 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2449 * returned. To be notified when data is available, wait for the
2450 * %G_IO_IN condition.
2452 * On error -1 is returned and @error is set accordingly.
2454 * Returns: Number of bytes read, or 0 if the connection was closed by
2455 * the peer, or -1 on error
2460 g_socket_receive (GSocket *socket,
2463 GCancellable *cancellable,
2466 return g_socket_receive_with_blocking (socket, buffer, size,
2467 socket->priv->blocking,
2468 cancellable, error);
2472 * g_socket_receive_with_blocking:
2473 * @socket: a #GSocket
2474 * @buffer: (array length=size) (element-type guint8): a buffer to
2475 * read data into (which should be at least @size bytes long).
2476 * @size: the number of bytes you want to read from the socket
2477 * @blocking: whether to do blocking or non-blocking I/O
2478 * @cancellable: (allow-none): a %GCancellable or %NULL
2479 * @error: #GError for error reporting, or %NULL to ignore.
2481 * This behaves exactly the same as g_socket_receive(), except that
2482 * the choice of blocking or non-blocking behavior is determined by
2483 * the @blocking argument rather than by @socket's properties.
2485 * Returns: Number of bytes read, or 0 if the connection was closed by
2486 * the peer, or -1 on error
2491 g_socket_receive_with_blocking (GSocket *socket,
2495 GCancellable *cancellable,
2500 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2502 if (!check_socket (socket, error))
2505 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2511 !g_socket_condition_wait (socket,
2512 G_IO_IN, cancellable, error))
2515 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2517 int errsv = get_socket_errno ();
2524 #ifdef WSAEWOULDBLOCK
2525 if (errsv == WSAEWOULDBLOCK)
2528 if (errsv == EWOULDBLOCK ||
2534 win32_unset_event_mask (socket, FD_READ);
2536 g_set_error (error, G_IO_ERROR,
2537 socket_io_error_from_errno (errsv),
2538 _("Error receiving data: %s"), socket_strerror (errsv));
2542 win32_unset_event_mask (socket, FD_READ);
2551 * g_socket_receive_from:
2552 * @socket: a #GSocket
2553 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2555 * @buffer: (array length=size) (element-type guint8): a buffer to
2556 * read data into (which should be at least @size bytes long).
2557 * @size: the number of bytes you want to read from the socket
2558 * @cancellable: (allow-none): a %GCancellable or %NULL
2559 * @error: #GError for error reporting, or %NULL to ignore.
2561 * Receive data (up to @size bytes) from a socket.
2563 * If @address is non-%NULL then @address will be set equal to the
2564 * source address of the received packet.
2565 * @address is owned by the caller.
2567 * See g_socket_receive() for additional information.
2569 * Returns: Number of bytes read, or 0 if the connection was closed by
2570 * the peer, or -1 on error
2575 g_socket_receive_from (GSocket *socket,
2576 GSocketAddress **address,
2579 GCancellable *cancellable,
2587 return g_socket_receive_message (socket,
2595 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2596 * one, which can be confusing and annoying. So if possible, we want
2597 * to suppress the signal entirely.
2600 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2602 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2607 * @socket: a #GSocket
2608 * @buffer: (array length=size) (element-type guint8): the buffer
2609 * containing the data to send.
2610 * @size: the number of bytes to send
2611 * @cancellable: (allow-none): a %GCancellable or %NULL
2612 * @error: #GError for error reporting, or %NULL to ignore.
2614 * Tries to send @size bytes from @buffer on the socket. This is
2615 * mainly used by connection-oriented sockets; it is identical to
2616 * g_socket_send_to() with @address set to %NULL.
2618 * If the socket is in blocking mode the call will block until there is
2619 * space for the data in the socket queue. If there is no space available
2620 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2621 * will be returned. To be notified when space is available, wait for the
2622 * %G_IO_OUT condition. Note though that you may still receive
2623 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2624 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2625 * very common due to the way the underlying APIs work.)
2627 * On error -1 is returned and @error is set accordingly.
2629 * Returns: Number of bytes written (which may be less than @size), or -1
2635 g_socket_send (GSocket *socket,
2636 const gchar *buffer,
2638 GCancellable *cancellable,
2641 return g_socket_send_with_blocking (socket, buffer, size,
2642 socket->priv->blocking,
2643 cancellable, error);
2647 * g_socket_send_with_blocking:
2648 * @socket: a #GSocket
2649 * @buffer: (array length=size) (element-type guint8): the buffer
2650 * containing the data to send.
2651 * @size: the number of bytes to send
2652 * @blocking: whether to do blocking or non-blocking I/O
2653 * @cancellable: (allow-none): a %GCancellable or %NULL
2654 * @error: #GError for error reporting, or %NULL to ignore.
2656 * This behaves exactly the same as g_socket_send(), except that
2657 * the choice of blocking or non-blocking behavior is determined by
2658 * the @blocking argument rather than by @socket's properties.
2660 * Returns: Number of bytes written (which may be less than @size), or -1
2666 g_socket_send_with_blocking (GSocket *socket,
2667 const gchar *buffer,
2670 GCancellable *cancellable,
2675 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2677 if (!check_socket (socket, error))
2680 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2686 !g_socket_condition_wait (socket,
2687 G_IO_OUT, cancellable, error))
2690 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2692 int errsv = get_socket_errno ();
2697 #ifdef WSAEWOULDBLOCK
2698 if (errsv == WSAEWOULDBLOCK)
2699 win32_unset_event_mask (socket, FD_WRITE);
2704 #ifdef WSAEWOULDBLOCK
2705 if (errsv == WSAEWOULDBLOCK)
2708 if (errsv == EWOULDBLOCK ||
2714 g_set_error (error, G_IO_ERROR,
2715 socket_io_error_from_errno (errsv),
2716 _("Error sending data: %s"), socket_strerror (errsv));
2727 * @socket: a #GSocket
2728 * @address: (allow-none): a #GSocketAddress, or %NULL
2729 * @buffer: (array length=size) (element-type guint8): the buffer
2730 * containing the data to send.
2731 * @size: the number of bytes to send
2732 * @cancellable: (allow-none): a %GCancellable or %NULL
2733 * @error: #GError for error reporting, or %NULL to ignore.
2735 * Tries to send @size bytes from @buffer to @address. If @address is
2736 * %NULL then the message is sent to the default receiver (set by
2737 * g_socket_connect()).
2739 * See g_socket_send() for additional information.
2741 * Returns: Number of bytes written (which may be less than @size), or -1
2747 g_socket_send_to (GSocket *socket,
2748 GSocketAddress *address,
2749 const gchar *buffer,
2751 GCancellable *cancellable,
2759 return g_socket_send_message (socket,
2769 * g_socket_shutdown:
2770 * @socket: a #GSocket
2771 * @shutdown_read: whether to shut down the read side
2772 * @shutdown_write: whether to shut down the write side
2773 * @error: #GError for error reporting, or %NULL to ignore.
2775 * Shut down part of a full-duplex connection.
2777 * If @shutdown_read is %TRUE then the receiving side of the connection
2778 * is shut down, and further reading is disallowed.
2780 * If @shutdown_write is %TRUE then the sending side of the connection
2781 * is shut down, and further writing is disallowed.
2783 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2785 * One example where this is used is graceful disconnect for TCP connections
2786 * where you close the sending side, then wait for the other side to close
2787 * the connection, thus ensuring that the other side saw all sent data.
2789 * Returns: %TRUE on success, %FALSE on error
2794 g_socket_shutdown (GSocket *socket,
2795 gboolean shutdown_read,
2796 gboolean shutdown_write,
2801 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2803 if (!check_socket (socket, error))
2807 if (!shutdown_read && !shutdown_write)
2811 if (shutdown_read && shutdown_write)
2813 else if (shutdown_read)
2818 if (shutdown_read && shutdown_write)
2820 else if (shutdown_read)
2826 if (shutdown (socket->priv->fd, how) != 0)
2828 int errsv = get_socket_errno ();
2829 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2830 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2834 if (shutdown_read && shutdown_write)
2835 socket->priv->connected = FALSE;
2842 * @socket: a #GSocket
2843 * @error: #GError for error reporting, or %NULL to ignore.
2845 * Closes the socket, shutting down any active connection.
2847 * Closing a socket does not wait for all outstanding I/O operations
2848 * to finish, so the caller should not rely on them to be guaranteed
2849 * to complete even if the close returns with no error.
2851 * Once the socket is closed, all other operations will return
2852 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2855 * Sockets will be automatically closed when the last reference
2856 * is dropped, but you might want to call this function to make sure
2857 * resources are released as early as possible.
2859 * Beware that due to the way that TCP works, it is possible for
2860 * recently-sent data to be lost if either you close a socket while the
2861 * %G_IO_IN condition is set, or else if the remote connection tries to
2862 * send something to you after you close the socket but before it has
2863 * finished reading all of the data you sent. There is no easy generic
2864 * way to avoid this problem; the easiest fix is to design the network
2865 * protocol such that the client will never send data "out of turn".
2866 * Another solution is for the server to half-close the connection by
2867 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2868 * and then wait for the client to notice this and close its side of the
2869 * connection, after which the server can safely call g_socket_close().
2870 * (This is what #GTcpConnection does if you call
2871 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2872 * only works if the client will close its connection after the server
2875 * Returns: %TRUE on success, %FALSE on error
2880 g_socket_close (GSocket *socket,
2885 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2887 if (socket->priv->closed)
2888 return TRUE; /* Multiple close not an error */
2890 if (!check_socket (socket, error))
2896 res = closesocket (socket->priv->fd);
2898 res = close (socket->priv->fd);
2902 int errsv = get_socket_errno ();
2907 g_set_error (error, G_IO_ERROR,
2908 socket_io_error_from_errno (errsv),
2909 _("Error closing socket: %s"),
2910 socket_strerror (errsv));
2916 socket->priv->connected = FALSE;
2917 socket->priv->closed = TRUE;
2918 if (socket->priv->remote_address)
2920 g_object_unref (socket->priv->remote_address);
2921 socket->priv->remote_address = NULL;
2928 * g_socket_is_closed:
2929 * @socket: a #GSocket
2931 * Checks whether a socket is closed.
2933 * Returns: %TRUE if socket is closed, %FALSE otherwise
2938 g_socket_is_closed (GSocket *socket)
2940 return socket->priv->closed;
2944 /* Broken source, used on errors */
2946 broken_dispatch (GSource *source,
2947 GSourceFunc callback,
2953 static GSourceFuncs broken_funcs =
2962 network_events_for_condition (GIOCondition condition)
2966 if (condition & G_IO_IN)
2967 event_mask |= (FD_READ | FD_ACCEPT);
2968 if (condition & G_IO_OUT)
2969 event_mask |= (FD_WRITE | FD_CONNECT);
2970 event_mask |= FD_CLOSE;
2976 ensure_event (GSocket *socket)
2978 if (socket->priv->event == WSA_INVALID_EVENT)
2979 socket->priv->event = WSACreateEvent();
2983 update_select_events (GSocket *socket)
2990 ensure_event (socket);
2993 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2996 event_mask |= network_events_for_condition (*ptr);
2999 if (event_mask != socket->priv->selected_events)
3001 /* If no events selected, disable event so we can unset
3004 if (event_mask == 0)
3007 event = socket->priv->event;
3009 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3010 socket->priv->selected_events = event_mask;
3015 add_condition_watch (GSocket *socket,
3016 GIOCondition *condition)
3018 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3020 socket->priv->requested_conditions =
3021 g_list_prepend (socket->priv->requested_conditions, condition);
3023 update_select_events (socket);
3027 remove_condition_watch (GSocket *socket,
3028 GIOCondition *condition)
3030 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3032 socket->priv->requested_conditions =
3033 g_list_remove (socket->priv->requested_conditions, condition);
3035 update_select_events (socket);
3039 update_condition (GSocket *socket)
3041 WSANETWORKEVENTS events;
3042 GIOCondition condition;
3044 if (WSAEnumNetworkEvents (socket->priv->fd,
3045 socket->priv->event,
3048 socket->priv->current_events |= events.lNetworkEvents;
3049 if (events.lNetworkEvents & FD_WRITE &&
3050 events.iErrorCode[FD_WRITE_BIT] != 0)
3051 socket->priv->current_errors |= FD_WRITE;
3052 if (events.lNetworkEvents & FD_CONNECT &&
3053 events.iErrorCode[FD_CONNECT_BIT] != 0)
3054 socket->priv->current_errors |= FD_CONNECT;
3058 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3059 condition |= G_IO_IN;
3061 if (socket->priv->current_events & FD_CLOSE)
3063 int r, errsv, buffer;
3065 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3067 errsv = get_socket_errno ();
3070 (r < 0 && errsv == WSAENOTCONN))
3071 condition |= G_IO_IN;
3073 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3074 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3075 condition |= G_IO_HUP;
3077 condition |= G_IO_ERR;
3080 if (socket->priv->closed)
3081 condition |= G_IO_HUP;
3083 /* Never report both G_IO_OUT and HUP, these are
3084 mutually exclusive (can't write to a closed socket) */
3085 if ((condition & G_IO_HUP) == 0 &&
3086 socket->priv->current_events & FD_WRITE)
3088 if (socket->priv->current_errors & FD_WRITE)
3089 condition |= G_IO_ERR;
3091 condition |= G_IO_OUT;
3095 if (socket->priv->current_events & FD_CONNECT)
3097 if (socket->priv->current_errors & FD_CONNECT)
3098 condition |= (G_IO_HUP | G_IO_ERR);
3100 condition |= G_IO_OUT;
3112 GIOCondition condition;
3113 GCancellable *cancellable;
3114 GPollFD cancel_pollfd;
3115 gint64 timeout_time;
3119 socket_source_prepare (GSource *source,
3122 GSocketSource *socket_source = (GSocketSource *)source;
3124 if (g_cancellable_is_cancelled (socket_source->cancellable))
3127 if (socket_source->timeout_time)
3131 now = g_source_get_time (source);
3132 /* Round up to ensure that we don't try again too early */
3133 *timeout = (socket_source->timeout_time - now + 999) / 1000;
3136 socket_source->socket->priv->timed_out = TRUE;
3145 socket_source->pollfd.revents = update_condition (socket_source->socket);
3148 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
3155 socket_source_check (GSource *source)
3159 return socket_source_prepare (source, &timeout);
3163 socket_source_dispatch (GSource *source,
3164 GSourceFunc callback,
3167 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3168 GSocketSource *socket_source = (GSocketSource *)source;
3169 GSocket *socket = socket_source->socket;
3173 socket_source->pollfd.revents = update_condition (socket_source->socket);
3175 if (socket_source->socket->priv->timed_out)
3176 socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
3178 ret = (*func) (socket,
3179 socket_source->pollfd.revents & socket_source->condition,
3182 if (socket->priv->timeout)
3183 socket_source->timeout_time = g_get_monotonic_time () +
3184 socket->priv->timeout * 1000000;
3187 socket_source->timeout_time = 0;
3193 socket_source_finalize (GSource *source)
3195 GSocketSource *socket_source = (GSocketSource *)source;
3198 socket = socket_source->socket;
3201 remove_condition_watch (socket, &socket_source->condition);
3204 g_object_unref (socket);
3206 if (socket_source->cancellable)
3208 g_cancellable_release_fd (socket_source->cancellable);
3209 g_object_unref (socket_source->cancellable);
3214 socket_source_closure_callback (GSocket *socket,
3215 GIOCondition condition,
3218 GClosure *closure = data;
3220 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3221 GValue result_value = G_VALUE_INIT;
3224 g_value_init (&result_value, G_TYPE_BOOLEAN);
3226 g_value_init (¶ms[0], G_TYPE_SOCKET);
3227 g_value_set_object (¶ms[0], socket);
3228 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
3229 g_value_set_flags (¶ms[1], condition);
3231 g_closure_invoke (closure, &result_value, 2, params, NULL);
3233 result = g_value_get_boolean (&result_value);
3234 g_value_unset (&result_value);
3235 g_value_unset (¶ms[0]);
3236 g_value_unset (¶ms[1]);
3241 static GSourceFuncs socket_source_funcs =
3243 socket_source_prepare,
3244 socket_source_check,
3245 socket_source_dispatch,
3246 socket_source_finalize,
3247 (GSourceFunc)socket_source_closure_callback,
3251 socket_source_new (GSocket *socket,
3252 GIOCondition condition,
3253 GCancellable *cancellable)
3256 GSocketSource *socket_source;
3259 ensure_event (socket);
3261 if (socket->priv->event == WSA_INVALID_EVENT)
3263 g_warning ("Failed to create WSAEvent");
3264 return g_source_new (&broken_funcs, sizeof (GSource));
3268 condition |= G_IO_HUP | G_IO_ERR;
3270 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3271 g_source_set_name (source, "GSocket");
3272 socket_source = (GSocketSource *)source;
3274 socket_source->socket = g_object_ref (socket);
3275 socket_source->condition = condition;
3277 if (g_cancellable_make_pollfd (cancellable,
3278 &socket_source->cancel_pollfd))
3280 socket_source->cancellable = g_object_ref (cancellable);
3281 g_source_add_poll (source, &socket_source->cancel_pollfd);
3285 add_condition_watch (socket, &socket_source->condition);
3286 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3288 socket_source->pollfd.fd = socket->priv->fd;
3291 socket_source->pollfd.events = condition;
3292 socket_source->pollfd.revents = 0;
3293 g_source_add_poll (source, &socket_source->pollfd);
3295 if (socket->priv->timeout)
3296 socket_source->timeout_time = g_get_monotonic_time () +
3297 socket->priv->timeout * 1000000;
3300 socket_source->timeout_time = 0;
3306 * g_socket_create_source: (skip)
3307 * @socket: a #GSocket
3308 * @condition: a #GIOCondition mask to monitor
3309 * @cancellable: (allow-none): a %GCancellable or %NULL
3311 * Creates a %GSource that can be attached to a %GMainContext to monitor
3312 * for the availibility of the specified @condition on the socket.
3314 * The callback on the source is of the #GSocketSourceFunc type.
3316 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3317 * these conditions will always be reported output if they are true.
3319 * @cancellable if not %NULL can be used to cancel the source, which will
3320 * cause the source to trigger, reporting the current condition (which
3321 * is likely 0 unless cancellation happened at the same time as a
3322 * condition change). You can check for this in the callback using
3323 * g_cancellable_is_cancelled().
3325 * If @socket has a timeout set, and it is reached before @condition
3326 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3327 * %G_IO_OUT depending on @condition. However, @socket will have been
3328 * marked as having had a timeout, and so the next #GSocket I/O method
3329 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3331 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3336 g_socket_create_source (GSocket *socket,
3337 GIOCondition condition,
3338 GCancellable *cancellable)
3340 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3342 return socket_source_new (socket, condition, cancellable);
3346 * g_socket_condition_check:
3347 * @socket: a #GSocket
3348 * @condition: a #GIOCondition mask to check
3350 * Checks on the readiness of @socket to perform operations.
3351 * The operations specified in @condition are checked for and masked
3352 * against the currently-satisfied conditions on @socket. The result
3355 * Note that on Windows, it is possible for an operation to return
3356 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3357 * g_socket_condition_check() has claimed that the socket is ready for
3358 * writing. Rather than calling g_socket_condition_check() and then
3359 * writing to the socket if it succeeds, it is generally better to
3360 * simply try writing to the socket right away, and try again later if
3361 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3363 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3364 * these conditions will always be set in the output if they are true.
3366 * This call never blocks.
3368 * Returns: the @GIOCondition mask of the current state
3373 g_socket_condition_check (GSocket *socket,
3374 GIOCondition condition)
3376 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3378 if (!check_socket (socket, NULL))
3383 GIOCondition current_condition;
3385 condition |= G_IO_ERR | G_IO_HUP;
3387 add_condition_watch (socket, &condition);
3388 current_condition = update_condition (socket);
3389 remove_condition_watch (socket, &condition);
3390 return condition & current_condition;
3396 poll_fd.fd = socket->priv->fd;
3397 poll_fd.events = condition;
3398 poll_fd.revents = 0;
3401 result = g_poll (&poll_fd, 1, 0);
3402 while (result == -1 && get_socket_errno () == EINTR);
3404 return poll_fd.revents;
3410 * g_socket_condition_wait:
3411 * @socket: a #GSocket
3412 * @condition: a #GIOCondition mask to wait for
3413 * @cancellable: (allow-none): a #GCancellable, or %NULL
3414 * @error: a #GError pointer, or %NULL
3416 * Waits for @condition to become true on @socket. When the condition
3417 * is met, %TRUE is returned.
3419 * If @cancellable is cancelled before the condition is met, or if the
3420 * socket has a timeout set and it is reached before the condition is
3421 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3422 * the appropriate value (%G_IO_ERROR_CANCELLED or
3423 * %G_IO_ERROR_TIMED_OUT).
3425 * See also g_socket_condition_timed_wait().
3427 * Returns: %TRUE if the condition was met, %FALSE otherwise
3432 g_socket_condition_wait (GSocket *socket,
3433 GIOCondition condition,
3434 GCancellable *cancellable,
3437 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3439 return g_socket_condition_timed_wait (socket, condition, -1,
3440 cancellable, error);
3444 * g_socket_condition_timed_wait:
3445 * @socket: a #GSocket
3446 * @condition: a #GIOCondition mask to wait for
3447 * @timeout: the maximum time (in microseconds) to wait, or -1
3448 * @cancellable: (allow-none): a #GCancellable, or %NULL
3449 * @error: a #GError pointer, or %NULL
3451 * Waits for up to @timeout microseconds for @condition to become true
3452 * on @socket. If the condition is met, %TRUE is returned.
3454 * If @cancellable is cancelled before the condition is met, or if
3455 * @timeout (or the socket's #GSocket:timeout) is reached before the
3456 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3457 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3458 * %G_IO_ERROR_TIMED_OUT).
3460 * If you don't want a timeout, use g_socket_condition_wait().
3461 * (Alternatively, you can pass -1 for @timeout.)
3463 * Note that although @timeout is in microseconds for consistency with
3464 * other GLib APIs, this function actually only has millisecond
3465 * resolution, and the behavior is undefined if @timeout is not an
3466 * exact number of milliseconds.
3468 * Returns: %TRUE if the condition was met, %FALSE otherwise
3473 g_socket_condition_timed_wait (GSocket *socket,
3474 GIOCondition condition,
3476 GCancellable *cancellable,
3481 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3483 if (!check_socket (socket, error))
3486 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3489 if (socket->priv->timeout &&
3490 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3491 timeout = socket->priv->timeout * 1000;
3492 else if (timeout != -1)
3493 timeout = timeout / 1000;
3495 start_time = g_get_monotonic_time ();
3499 GIOCondition current_condition;
3505 /* Always check these */
3506 condition |= G_IO_ERR | G_IO_HUP;
3508 add_condition_watch (socket, &condition);
3511 events[num_events++] = socket->priv->event;
3513 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3514 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3517 timeout = WSA_INFINITE;
3519 current_condition = update_condition (socket);
3520 while ((condition & current_condition) == 0)
3522 res = WSAWaitForMultipleEvents (num_events, events,
3523 FALSE, timeout, FALSE);
3524 if (res == WSA_WAIT_FAILED)
3526 int errsv = get_socket_errno ();
3528 g_set_error (error, G_IO_ERROR,
3529 socket_io_error_from_errno (errsv),
3530 _("Waiting for socket condition: %s"),
3531 socket_strerror (errsv));
3534 else if (res == WSA_WAIT_TIMEOUT)
3536 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3537 _("Socket I/O timed out"));
3541 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3544 current_condition = update_condition (socket);
3546 if (timeout != WSA_INFINITE)
3548 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3553 remove_condition_watch (socket, &condition);
3555 g_cancellable_release_fd (cancellable);
3557 return (condition & current_condition) != 0;
3565 poll_fd[0].fd = socket->priv->fd;
3566 poll_fd[0].events = condition;
3569 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3574 result = g_poll (poll_fd, num, timeout);
3575 if (result != -1 || errno != EINTR)
3580 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3587 g_cancellable_release_fd (cancellable);
3591 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3592 _("Socket I/O timed out"));
3596 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3602 * g_socket_send_message:
3603 * @socket: a #GSocket
3604 * @address: (allow-none): a #GSocketAddress, or %NULL
3605 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3606 * @num_vectors: the number of elements in @vectors, or -1
3607 * @messages: (array length=num_messages) (allow-none): a pointer to an
3608 * array of #GSocketControlMessages, or %NULL.
3609 * @num_messages: number of elements in @messages, or -1.
3610 * @flags: an int containing #GSocketMsgFlags flags
3611 * @cancellable: (allow-none): a %GCancellable or %NULL
3612 * @error: #GError for error reporting, or %NULL to ignore.
3614 * Send data to @address on @socket. This is the most complicated and
3615 * fully-featured version of this call. For easier use, see
3616 * g_socket_send() and g_socket_send_to().
3618 * If @address is %NULL then the message is sent to the default receiver
3619 * (set by g_socket_connect()).
3621 * @vectors must point to an array of #GOutputVector structs and
3622 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3623 * then @vectors is assumed to be terminated by a #GOutputVector with a
3624 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3625 * that the sent data will be gathered from. Using multiple
3626 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3627 * data from multiple sources into a single buffer, and more
3628 * network-efficient than making multiple calls to g_socket_send().
3630 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3631 * #GSocketControlMessage instances. These correspond to the control
3632 * messages to be sent on the socket.
3633 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3636 * @flags modify how the message is sent. The commonly available arguments
3637 * for this are available in the #GSocketMsgFlags enum, but the
3638 * values there are the same as the system values, and the flags
3639 * are passed in as-is, so you can pass in system-specific flags too.
3641 * If the socket is in blocking mode the call will block until there is
3642 * space for the data in the socket queue. If there is no space available
3643 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3644 * will be returned. To be notified when space is available, wait for the
3645 * %G_IO_OUT condition. Note though that you may still receive
3646 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3647 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3648 * very common due to the way the underlying APIs work.)
3650 * On error -1 is returned and @error is set accordingly.
3652 * Returns: Number of bytes written (which may be less than @size), or -1
3658 g_socket_send_message (GSocket *socket,
3659 GSocketAddress *address,
3660 GOutputVector *vectors,
3662 GSocketControlMessage **messages,
3665 GCancellable *cancellable,
3668 GOutputVector one_vector;
3671 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3673 if (!check_socket (socket, error))
3676 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3679 if (num_vectors == -1)
3681 for (num_vectors = 0;
3682 vectors[num_vectors].buffer != NULL;
3687 if (num_messages == -1)
3689 for (num_messages = 0;
3690 messages != NULL && messages[num_messages] != NULL;
3695 if (num_vectors == 0)
3699 one_vector.buffer = &zero;
3700 one_vector.size = 1;
3702 vectors = &one_vector;
3715 msg.msg_namelen = g_socket_address_get_native_size (address);
3716 msg.msg_name = g_alloca (msg.msg_namelen);
3717 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3722 msg.msg_name = NULL;
3723 msg.msg_namelen = 0;
3728 /* this entire expression will be evaluated at compile time */
3729 if (sizeof *msg.msg_iov == sizeof *vectors &&
3730 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3731 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3732 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3733 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3734 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3735 G_STRUCT_OFFSET (GOutputVector, size))
3736 /* ABI is compatible */
3738 msg.msg_iov = (struct iovec *) vectors;
3739 msg.msg_iovlen = num_vectors;
3742 /* ABI is incompatible */
3746 msg.msg_iov = g_newa (struct iovec, num_vectors);
3747 for (i = 0; i < num_vectors; i++)
3749 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3750 msg.msg_iov[i].iov_len = vectors[i].size;
3752 msg.msg_iovlen = num_vectors;
3758 struct cmsghdr *cmsg;
3761 msg.msg_controllen = 0;
3762 for (i = 0; i < num_messages; i++)
3763 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3765 if (msg.msg_controllen == 0)
3766 msg.msg_control = NULL;
3769 msg.msg_control = g_alloca (msg.msg_controllen);
3770 memset (msg.msg_control, '\0', msg.msg_controllen);
3773 cmsg = CMSG_FIRSTHDR (&msg);
3774 for (i = 0; i < num_messages; i++)
3776 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3777 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3778 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3779 g_socket_control_message_serialize (messages[i],
3781 cmsg = CMSG_NXTHDR (&msg, cmsg);
3783 g_assert (cmsg == NULL);
3788 if (socket->priv->blocking &&
3789 !g_socket_condition_wait (socket,
3790 G_IO_OUT, cancellable, error))
3793 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3796 int errsv = get_socket_errno ();
3801 if (socket->priv->blocking &&
3802 (errsv == EWOULDBLOCK ||
3806 g_set_error (error, G_IO_ERROR,
3807 socket_io_error_from_errno (errsv),
3808 _("Error sending message: %s"), socket_strerror (errsv));
3819 struct sockaddr_storage addr;
3826 /* Win32 doesn't support control messages.
3827 Actually this is possible for raw and datagram sockets
3828 via WSASendMessage on Vista or later, but that doesn't
3830 if (num_messages != 0)
3832 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3833 _("GSocketControlMessage not supported on Windows"));
3838 bufs = g_newa (WSABUF, num_vectors);
3839 for (i = 0; i < num_vectors; i++)
3841 bufs[i].buf = (char *)vectors[i].buffer;
3842 bufs[i].len = (gulong)vectors[i].size;
3846 addrlen = 0; /* Avoid warning */
3849 addrlen = g_socket_address_get_native_size (address);
3850 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3856 if (socket->priv->blocking &&
3857 !g_socket_condition_wait (socket,
3858 G_IO_OUT, cancellable, error))
3862 result = WSASendTo (socket->priv->fd,
3865 (const struct sockaddr *)&addr, addrlen,
3868 result = WSASend (socket->priv->fd,
3875 int errsv = get_socket_errno ();
3877 if (errsv == WSAEINTR)
3880 if (errsv == WSAEWOULDBLOCK)
3881 win32_unset_event_mask (socket, FD_WRITE);
3883 if (socket->priv->blocking &&
3884 errsv == WSAEWOULDBLOCK)
3887 g_set_error (error, G_IO_ERROR,
3888 socket_io_error_from_errno (errsv),
3889 _("Error sending message: %s"), socket_strerror (errsv));
3901 static GSocketAddress *
3902 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
3904 GSocketAddress *saddr;
3906 guint64 oldest_time = G_MAXUINT64;
3907 gint oldest_index = 0;
3909 if (native_len <= 0)
3913 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
3915 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
3916 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
3917 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
3922 if (tmp_native_len != native_len)
3925 if (memcmp (tmp_native, native, native_len) == 0)
3927 saddr = g_object_ref (tmp);
3928 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
3932 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
3934 oldest_time = socket->priv->recv_addr_cache[i].last_used;
3939 saddr = g_socket_address_new_from_native (native, native_len);
3941 if (socket->priv->recv_addr_cache[oldest_index].addr)
3943 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
3944 g_free (socket->priv->recv_addr_cache[oldest_index].native);
3947 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
3948 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
3949 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
3950 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
3956 * g_socket_receive_message:
3957 * @socket: a #GSocket
3958 * @address: (out) (allow-none): a pointer to a #GSocketAddress
3960 * @vectors: (array length=num_vectors): an array of #GInputVector structs
3961 * @num_vectors: the number of elements in @vectors, or -1
3962 * @messages: (array length=num_messages) (allow-none): a pointer which
3963 * may be filled with an array of #GSocketControlMessages, or %NULL
3964 * @num_messages: a pointer which will be filled with the number of
3965 * elements in @messages, or %NULL
3966 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3967 * @cancellable: (allow-none): a %GCancellable or %NULL
3968 * @error: a #GError pointer, or %NULL
3970 * Receive data from a socket. This is the most complicated and
3971 * fully-featured version of this call. For easier use, see
3972 * g_socket_receive() and g_socket_receive_from().
3974 * If @address is non-%NULL then @address will be set equal to the
3975 * source address of the received packet.
3976 * @address is owned by the caller.
3978 * @vector must point to an array of #GInputVector structs and
3979 * @num_vectors must be the length of this array. These structs
3980 * describe the buffers that received data will be scattered into.
3981 * If @num_vectors is -1, then @vectors is assumed to be terminated
3982 * by a #GInputVector with a %NULL buffer pointer.
3984 * As a special case, if @num_vectors is 0 (in which case, @vectors
3985 * may of course be %NULL), then a single byte is received and
3986 * discarded. This is to facilitate the common practice of sending a
3987 * single '\0' byte for the purposes of transferring ancillary data.
3989 * @messages, if non-%NULL, will be set to point to a newly-allocated
3990 * array of #GSocketControlMessage instances or %NULL if no such
3991 * messages was received. These correspond to the control messages
3992 * received from the kernel, one #GSocketControlMessage per message
3993 * from the kernel. This array is %NULL-terminated and must be freed
3994 * by the caller using g_free() after calling g_object_unref() on each
3995 * element. If @messages is %NULL, any control messages received will
3998 * @num_messages, if non-%NULL, will be set to the number of control
3999 * messages received.
4001 * If both @messages and @num_messages are non-%NULL, then
4002 * @num_messages gives the number of #GSocketControlMessage instances
4003 * in @messages (ie: not including the %NULL terminator).
4005 * @flags is an in/out parameter. The commonly available arguments
4006 * for this are available in the #GSocketMsgFlags enum, but the
4007 * values there are the same as the system values, and the flags
4008 * are passed in as-is, so you can pass in system-specific flags too
4009 * (and g_socket_receive_message() may pass system-specific flags out).
4011 * As with g_socket_receive(), data may be discarded if @socket is
4012 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
4013 * provide enough buffer space to read a complete message. You can pass
4014 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
4015 * removing it from the receive queue, but there is no portable way to find
4016 * out the length of the message other than by reading it into a
4017 * sufficiently-large buffer.
4019 * If the socket is in blocking mode the call will block until there
4020 * is some data to receive, the connection is closed, or there is an
4021 * error. If there is no data available and the socket is in
4022 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
4023 * returned. To be notified when data is available, wait for the
4024 * %G_IO_IN condition.
4026 * On error -1 is returned and @error is set accordingly.
4028 * Returns: Number of bytes read, or 0 if the connection was closed by
4029 * the peer, or -1 on error
4034 g_socket_receive_message (GSocket *socket,
4035 GSocketAddress **address,
4036 GInputVector *vectors,
4038 GSocketControlMessage ***messages,
4041 GCancellable *cancellable,
4044 GInputVector one_vector;
4047 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4049 if (!check_socket (socket, error))
4052 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4055 if (num_vectors == -1)
4057 for (num_vectors = 0;
4058 vectors[num_vectors].buffer != NULL;
4063 if (num_vectors == 0)
4065 one_vector.buffer = &one_byte;
4066 one_vector.size = 1;
4068 vectors = &one_vector;
4075 struct sockaddr_storage one_sockaddr;
4080 msg.msg_name = &one_sockaddr;
4081 msg.msg_namelen = sizeof (struct sockaddr_storage);
4085 msg.msg_name = NULL;
4086 msg.msg_namelen = 0;
4090 /* this entire expression will be evaluated at compile time */
4091 if (sizeof *msg.msg_iov == sizeof *vectors &&
4092 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4093 G_STRUCT_OFFSET (struct iovec, iov_base) ==
4094 G_STRUCT_OFFSET (GInputVector, buffer) &&
4095 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4096 G_STRUCT_OFFSET (struct iovec, iov_len) ==
4097 G_STRUCT_OFFSET (GInputVector, size))
4098 /* ABI is compatible */
4100 msg.msg_iov = (struct iovec *) vectors;
4101 msg.msg_iovlen = num_vectors;
4104 /* ABI is incompatible */
4108 msg.msg_iov = g_newa (struct iovec, num_vectors);
4109 for (i = 0; i < num_vectors; i++)
4111 msg.msg_iov[i].iov_base = vectors[i].buffer;
4112 msg.msg_iov[i].iov_len = vectors[i].size;
4114 msg.msg_iovlen = num_vectors;
4118 msg.msg_control = g_alloca (2048);
4119 msg.msg_controllen = 2048;
4123 msg.msg_flags = *flags;
4127 /* We always set the close-on-exec flag so we don't leak file
4128 * descriptors into child processes. Note that gunixfdmessage.c
4129 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4131 #ifdef MSG_CMSG_CLOEXEC
4132 msg.msg_flags |= MSG_CMSG_CLOEXEC;
4138 if (socket->priv->blocking &&
4139 !g_socket_condition_wait (socket,
4140 G_IO_IN, cancellable, error))
4143 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4144 #ifdef MSG_CMSG_CLOEXEC
4145 if (result < 0 && get_socket_errno () == EINVAL)
4147 /* We must be running on an old kernel. Call without the flag. */
4148 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4149 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4155 int errsv = get_socket_errno ();
4160 if (socket->priv->blocking &&
4161 (errsv == EWOULDBLOCK ||
4165 g_set_error (error, G_IO_ERROR,
4166 socket_io_error_from_errno (errsv),
4167 _("Error receiving message: %s"), socket_strerror (errsv));
4174 /* decode address */
4175 if (address != NULL)
4177 *address = cache_recv_address (socket, msg.msg_name, msg.msg_namelen);
4180 /* decode control messages */
4182 GPtrArray *my_messages = NULL;
4183 struct cmsghdr *cmsg;
4185 if (msg.msg_controllen >= sizeof (struct cmsghdr))
4187 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4189 GSocketControlMessage *message;
4191 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4193 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4195 if (message == NULL)
4196 /* We've already spewed about the problem in the
4197 deserialization code, so just continue */
4200 if (messages == NULL)
4202 /* we have to do it this way if the user ignores the
4203 * messages so that we will close any received fds.
4205 g_object_unref (message);
4209 if (my_messages == NULL)
4210 my_messages = g_ptr_array_new ();
4211 g_ptr_array_add (my_messages, message);
4217 *num_messages = my_messages != NULL ? my_messages->len : 0;
4221 if (my_messages == NULL)
4227 g_ptr_array_add (my_messages, NULL);
4228 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4233 g_assert (my_messages == NULL);
4237 /* capture the flags */
4239 *flags = msg.msg_flags;
4245 struct sockaddr_storage addr;
4247 DWORD bytes_received;
4254 bufs = g_newa (WSABUF, num_vectors);
4255 for (i = 0; i < num_vectors; i++)
4257 bufs[i].buf = (char *)vectors[i].buffer;
4258 bufs[i].len = (gulong)vectors[i].size;
4270 if (socket->priv->blocking &&
4271 !g_socket_condition_wait (socket,
4272 G_IO_IN, cancellable, error))
4275 addrlen = sizeof addr;
4277 result = WSARecvFrom (socket->priv->fd,
4279 &bytes_received, &win_flags,
4280 (struct sockaddr *)&addr, &addrlen,
4283 result = WSARecv (socket->priv->fd,
4285 &bytes_received, &win_flags,
4289 int errsv = get_socket_errno ();
4291 if (errsv == WSAEINTR)
4294 win32_unset_event_mask (socket, FD_READ);
4296 if (socket->priv->blocking &&
4297 errsv == WSAEWOULDBLOCK)
4300 g_set_error (error, G_IO_ERROR,
4301 socket_io_error_from_errno (errsv),
4302 _("Error receiving message: %s"), socket_strerror (errsv));
4306 win32_unset_event_mask (socket, FD_READ);
4310 /* decode address */
4311 if (address != NULL)
4313 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
4316 /* capture the flags */
4320 if (messages != NULL)
4322 if (num_messages != NULL)
4325 return bytes_received;
4331 * g_socket_get_credentials:
4332 * @socket: a #GSocket.
4333 * @error: #GError for error reporting, or %NULL to ignore.
4335 * Returns the credentials of the foreign process connected to this
4336 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4339 * If this operation isn't supported on the OS, the method fails with
4340 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4341 * by reading the %SO_PEERCRED option on the underlying socket.
4343 * Other ways to obtain credentials from a foreign peer includes the
4344 * #GUnixCredentialsMessage type and
4345 * g_unix_connection_send_credentials() /
4346 * g_unix_connection_receive_credentials() functions.
4348 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4349 * that must be freed with g_object_unref().
4354 g_socket_get_credentials (GSocket *socket,
4359 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4360 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4364 #if defined(__linux__) || defined(__OpenBSD__)
4367 #if defined(__linux__)
4368 struct ucred native_creds;
4369 optlen = sizeof (struct ucred);
4370 #elif defined(__OpenBSD__)
4371 struct sockpeercred native_creds;
4372 optlen = sizeof (struct sockpeercred);
4374 if (getsockopt (socket->priv->fd,
4377 (void *)&native_creds,
4380 int errsv = get_socket_errno ();
4383 socket_io_error_from_errno (errsv),
4384 _("Unable to read socket credentials: %s"),
4385 socket_strerror (errsv));
4389 ret = g_credentials_new ();
4390 g_credentials_set_native (ret,
4391 #if defined(__linux__)
4392 G_CREDENTIALS_TYPE_LINUX_UCRED,
4393 #elif defined(__OpenBSD__)
4394 G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
4400 g_set_error_literal (error,
4402 G_IO_ERROR_NOT_SUPPORTED,
4403 _("g_socket_get_credentials not implemented for this OS"));
4410 * g_socket_get_option:
4411 * @socket: a #GSocket
4412 * @level: the "API level" of the option (eg, <literal>SOL_SOCKET</literal>)
4413 * @optname: the "name" of the option (eg, <literal>SO_BROADCAST</literal>)
4414 * @value: (out): return location for the option value
4415 * @error: #GError for error reporting, or %NULL to ignore.
4417 * Gets the value of an integer-valued option on @socket, as with
4418 * <literal>getsockopt ()</literal>. (If you need to fetch a
4419 * non-integer-valued option, you will need to call
4420 * <literal>getsockopt ()</literal> directly.)
4422 * The <link linkend="gio-gnetworking.h"><literal><gio/gnetworking.h></literal></link>
4423 * header pulls in system headers that will define most of the
4424 * standard/portable socket options. For unusual socket protocols or
4425 * platform-dependent options, you may need to include additional
4428 * Note that even for socket options that are a single byte in size,
4429 * @value is still a pointer to a #gint variable, not a #guchar;
4430 * g_socket_get_option() will handle the conversion internally.
4432 * Returns: success or failure. On failure, @error will be set, and
4433 * the system error value (<literal>errno</literal> or
4434 * <literal>WSAGetLastError ()</literal>) will still be set to the
4435 * result of the <literal>getsockopt ()</literal> call.
4440 g_socket_get_option (GSocket *socket,
4448 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4451 size = sizeof (gint);
4452 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
4454 int errsv = get_socket_errno ();
4456 g_set_error_literal (error,
4458 socket_io_error_from_errno (errsv),
4459 socket_strerror (errsv));
4461 /* Reset errno in case the caller wants to look at it */
4467 #if G_BYTE_ORDER == G_BIG_ENDIAN
4468 /* If the returned value is smaller than an int then we need to
4469 * slide it over into the low-order bytes of *value.
4471 if (size != sizeof (gint))
4472 *value = *value >> (8 * (sizeof (gint) - size));
4479 * g_socket_set_option:
4480 * @socket: a #GSocket
4481 * @level: the "API level" of the option (eg, <literal>SOL_SOCKET</literal>)
4482 * @optname: the "name" of the option (eg, <literal>SO_BROADCAST</literal>)
4483 * @value: the value to set the option to
4484 * @error: #GError for error reporting, or %NULL to ignore.
4486 * Sets the value of an integer-valued option on @socket, as with
4487 * <literal>setsockopt ()</literal>. (If you need to set a
4488 * non-integer-valued option, you will need to call
4489 * <literal>setsockopt ()</literal> directly.)
4491 * The <link linkend="gio-gnetworking.h"><literal><gio/gnetworking.h></literal></link>
4492 * header pulls in system headers that will define most of the
4493 * standard/portable socket options. For unusual socket protocols or
4494 * platform-dependent options, you may need to include additional
4497 * Returns: success or failure. On failure, @error will be set, and
4498 * the system error value (<literal>errno</literal> or
4499 * <literal>WSAGetLastError ()</literal>) will still be set to the
4500 * result of the <literal>setsockopt ()</literal> call.
4505 g_socket_set_option (GSocket *socket,
4513 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4515 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
4518 #if !defined (__linux__) && !defined (G_OS_WIN32)
4519 /* Linux and Windows let you set a single-byte value from an int,
4520 * but most other platforms don't.
4522 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
4524 #if G_BYTE_ORDER == G_BIG_ENDIAN
4525 value = value << (8 * (sizeof (gint) - 1));
4527 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
4532 errsv = get_socket_errno ();
4534 g_set_error_literal (error,
4536 socket_io_error_from_errno (errsv),
4537 socket_strerror (errsv));