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
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,
129 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
130 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
131 g_socket_initable_iface_init));
148 PROP_MULTICAST_LOOPBACK,
152 /* Size of the receiver cache for g_socket_receive_from() */
153 #define RECV_ADDR_CACHE_SIZE 8
155 struct _GSocketPrivate
157 GSocketFamily family;
159 GSocketProtocol protocol;
163 GError *construct_error;
164 GSocketAddress *remote_address;
172 guint connect_pending : 1;
178 GList *requested_conditions; /* list of requested GIOCondition * */
182 GSocketAddress *addr;
183 struct sockaddr *native;
186 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
190 get_socket_errno (void)
195 return WSAGetLastError ();
200 socket_io_error_from_errno (int err)
203 return g_io_error_from_errno (err);
208 return G_IO_ERROR_ADDRESS_IN_USE;
210 return G_IO_ERROR_WOULD_BLOCK;
212 return G_IO_ERROR_PERMISSION_DENIED;
213 case WSA_INVALID_HANDLE:
214 case WSA_INVALID_PARAMETER:
217 return G_IO_ERROR_INVALID_ARGUMENT;
218 case WSAEPROTONOSUPPORT:
219 return G_IO_ERROR_NOT_SUPPORTED;
221 return G_IO_ERROR_CANCELLED;
222 case WSAESOCKTNOSUPPORT:
224 case WSAEPFNOSUPPORT:
225 case WSAEAFNOSUPPORT:
226 return G_IO_ERROR_NOT_SUPPORTED;
228 return G_IO_ERROR_FAILED;
234 socket_strerror (int err)
237 return g_strerror (err);
242 msg = g_win32_error_message (err);
244 msg_ret = g_intern_string (msg);
252 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
254 _win32_unset_event_mask (GSocket *socket, int mask)
256 socket->priv->current_events &= ~mask;
257 socket->priv->current_errors &= ~mask;
260 #define win32_unset_event_mask(_socket, _mask)
263 /* Windows has broken prototypes... */
265 #define getsockopt(sockfd, level, optname, optval, optlen) \
266 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
267 #define setsockopt(sockfd, level, optname, optval, optlen) \
268 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
269 #define getsockname(sockfd, addr, addrlen) \
270 getsockname (sockfd, addr, (int *)addrlen)
271 #define getpeername(sockfd, addr, addrlen) \
272 getpeername (sockfd, addr, (int *)addrlen)
273 #define recv(sockfd, buf, len, flags) \
274 recv (sockfd, (gpointer)buf, len, flags)
278 set_fd_nonblocking (int fd)
281 GError *error = NULL;
287 if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
289 g_warning ("Error setting socket nonblocking: %s", error->message);
290 g_clear_error (&error);
295 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
297 int errsv = get_socket_errno ();
298 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
304 check_socket (GSocket *socket,
307 if (!socket->priv->inited)
309 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
310 _("Invalid socket, not initialized"));
314 if (socket->priv->construct_error)
316 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
317 _("Invalid socket, initialization failed due to: %s"),
318 socket->priv->construct_error->message);
322 if (socket->priv->closed)
324 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
325 _("Socket is already closed"));
329 if (socket->priv->timed_out)
331 socket->priv->timed_out = FALSE;
332 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
333 _("Socket I/O timed out"));
341 g_socket_details_from_fd (GSocket *socket)
343 struct sockaddr_storage address;
350 /* See bug #611756 */
351 BOOL bool_val = FALSE;
356 fd = socket->priv->fd;
357 optlen = sizeof value;
358 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
360 errsv = get_socket_errno ();
372 /* programmer error */
373 g_error ("creating GSocket from fd %d: %s\n",
374 fd, socket_strerror (errsv));
382 g_assert (optlen == sizeof value);
386 socket->priv->type = G_SOCKET_TYPE_STREAM;
390 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
394 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
398 socket->priv->type = G_SOCKET_TYPE_INVALID;
402 addrlen = sizeof address;
403 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
405 errsv = get_socket_errno ();
411 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
412 sizeof address.ss_family <= addrlen);
413 family = address.ss_family;
417 /* On Solaris, this happens if the socket is not yet connected.
418 * But we can use SO_DOMAIN as a workaround there.
421 optlen = sizeof family;
422 if (getsockopt (fd, SOL_SOCKET, SO_DOMAIN, (void *)&family, &optlen) != 0)
424 errsv = get_socket_errno ();
428 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
436 case G_SOCKET_FAMILY_IPV4:
437 case G_SOCKET_FAMILY_IPV6:
438 socket->priv->family = address.ss_family;
439 switch (socket->priv->type)
441 case G_SOCKET_TYPE_STREAM:
442 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
445 case G_SOCKET_TYPE_DATAGRAM:
446 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
449 case G_SOCKET_TYPE_SEQPACKET:
450 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
458 case G_SOCKET_FAMILY_UNIX:
459 socket->priv->family = G_SOCKET_FAMILY_UNIX;
460 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
464 socket->priv->family = G_SOCKET_FAMILY_INVALID;
468 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
470 addrlen = sizeof address;
471 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
472 socket->priv->connected = TRUE;
475 optlen = sizeof bool_val;
476 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
477 (void *)&bool_val, &optlen) == 0)
480 /* Experimentation indicates that the SO_KEEPALIVE value is
481 * actually a char on Windows, even if documentation claims it
482 * to be a BOOL which is a typedef for int. So this g_assert()
483 * fails. See bug #611756.
485 g_assert (optlen == sizeof bool_val);
487 socket->priv->keepalive = !!bool_val;
491 /* Can't read, maybe not supported, assume FALSE */
492 socket->priv->keepalive = FALSE;
498 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
499 socket_io_error_from_errno (errsv),
500 _("creating GSocket from fd: %s"),
501 socket_strerror (errsv));
505 g_socket_create_socket (GSocketFamily family,
515 case G_SOCKET_TYPE_STREAM:
516 native_type = SOCK_STREAM;
519 case G_SOCKET_TYPE_DATAGRAM:
520 native_type = SOCK_DGRAM;
523 case G_SOCKET_TYPE_SEQPACKET:
524 native_type = SOCK_SEQPACKET;
528 g_assert_not_reached ();
533 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
534 _("Unable to create socket: %s"), _("Unknown family was specified"));
540 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
541 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
546 fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
547 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
548 if (fd < 0 && errno == EINVAL)
550 fd = socket (family, native_type, protocol);
554 int errsv = get_socket_errno ();
556 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
557 _("Unable to create socket: %s"), socket_strerror (errsv));
564 /* We always want to set close-on-exec to protect users. If you
565 need to so some weird inheritance to exec you can re-enable this
566 using lower level hacks with g_socket_get_fd(). */
567 flags = fcntl (fd, F_GETFD, 0);
569 (flags & FD_CLOEXEC) == 0)
572 fcntl (fd, F_SETFD, flags);
581 g_socket_constructed (GObject *object)
583 GSocket *socket = G_SOCKET (object);
585 if (socket->priv->fd >= 0)
586 /* create socket->priv info from the fd */
587 g_socket_details_from_fd (socket);
590 /* create the fd from socket->priv info */
591 socket->priv->fd = g_socket_create_socket (socket->priv->family,
593 socket->priv->protocol,
594 &socket->priv->construct_error);
596 /* Always use native nonblocking sockets, as
597 windows sets sockets to nonblocking automatically
598 in certain operations. This way we make things work
599 the same on all platforms */
600 if (socket->priv->fd != -1)
601 set_fd_nonblocking (socket->priv->fd);
605 g_socket_get_property (GObject *object,
610 GSocket *socket = G_SOCKET (object);
611 GSocketAddress *address;
616 g_value_set_enum (value, socket->priv->family);
620 g_value_set_enum (value, socket->priv->type);
624 g_value_set_enum (value, socket->priv->protocol);
628 g_value_set_int (value, socket->priv->fd);
632 g_value_set_boolean (value, socket->priv->blocking);
635 case PROP_LISTEN_BACKLOG:
636 g_value_set_int (value, socket->priv->listen_backlog);
640 g_value_set_boolean (value, socket->priv->keepalive);
643 case PROP_LOCAL_ADDRESS:
644 address = g_socket_get_local_address (socket, NULL);
645 g_value_take_object (value, address);
648 case PROP_REMOTE_ADDRESS:
649 address = g_socket_get_remote_address (socket, NULL);
650 g_value_take_object (value, address);
654 g_value_set_uint (value, socket->priv->timeout);
658 g_value_set_uint (value, g_socket_get_ttl (socket));
662 g_value_set_boolean (value, g_socket_get_broadcast (socket));
665 case PROP_MULTICAST_LOOPBACK:
666 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
669 case PROP_MULTICAST_TTL:
670 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
674 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
679 g_socket_set_property (GObject *object,
684 GSocket *socket = G_SOCKET (object);
689 socket->priv->family = g_value_get_enum (value);
693 socket->priv->type = g_value_get_enum (value);
697 socket->priv->protocol = g_value_get_enum (value);
701 socket->priv->fd = g_value_get_int (value);
705 g_socket_set_blocking (socket, g_value_get_boolean (value));
708 case PROP_LISTEN_BACKLOG:
709 g_socket_set_listen_backlog (socket, g_value_get_int (value));
713 g_socket_set_keepalive (socket, g_value_get_boolean (value));
717 g_socket_set_timeout (socket, g_value_get_uint (value));
721 g_socket_set_ttl (socket, g_value_get_uint (value));
725 g_socket_set_broadcast (socket, g_value_get_boolean (value));
728 case PROP_MULTICAST_LOOPBACK:
729 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
732 case PROP_MULTICAST_TTL:
733 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
737 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
742 g_socket_finalize (GObject *object)
744 GSocket *socket = G_SOCKET (object);
747 g_clear_error (&socket->priv->construct_error);
749 if (socket->priv->fd != -1 &&
750 !socket->priv->closed)
751 g_socket_close (socket, NULL);
753 if (socket->priv->remote_address)
754 g_object_unref (socket->priv->remote_address);
757 if (socket->priv->event != WSA_INVALID_EVENT)
759 WSACloseEvent (socket->priv->event);
760 socket->priv->event = WSA_INVALID_EVENT;
763 g_assert (socket->priv->requested_conditions == NULL);
766 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
768 if (socket->priv->recv_addr_cache[i].addr)
770 g_object_unref (socket->priv->recv_addr_cache[i].addr);
771 g_free (socket->priv->recv_addr_cache[i].native);
775 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
776 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
780 g_socket_class_init (GSocketClass *klass)
782 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
784 /* Make sure winsock has been initialized */
785 g_type_ensure (G_TYPE_INET_ADDRESS);
788 /* There is no portable, thread-safe way to avoid having the process
789 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
790 * forced to simply ignore the signal process-wide.
792 signal (SIGPIPE, SIG_IGN);
795 g_type_class_add_private (klass, sizeof (GSocketPrivate));
797 gobject_class->finalize = g_socket_finalize;
798 gobject_class->constructed = g_socket_constructed;
799 gobject_class->set_property = g_socket_set_property;
800 gobject_class->get_property = g_socket_get_property;
802 g_object_class_install_property (gobject_class, PROP_FAMILY,
803 g_param_spec_enum ("family",
805 P_("The sockets address family"),
806 G_TYPE_SOCKET_FAMILY,
807 G_SOCKET_FAMILY_INVALID,
808 G_PARAM_CONSTRUCT_ONLY |
810 G_PARAM_STATIC_STRINGS));
812 g_object_class_install_property (gobject_class, PROP_TYPE,
813 g_param_spec_enum ("type",
815 P_("The sockets type"),
817 G_SOCKET_TYPE_STREAM,
818 G_PARAM_CONSTRUCT_ONLY |
820 G_PARAM_STATIC_STRINGS));
822 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
823 g_param_spec_enum ("protocol",
824 P_("Socket protocol"),
825 P_("The id of the protocol to use, or -1 for unknown"),
826 G_TYPE_SOCKET_PROTOCOL,
827 G_SOCKET_PROTOCOL_UNKNOWN,
828 G_PARAM_CONSTRUCT_ONLY |
830 G_PARAM_STATIC_STRINGS));
832 g_object_class_install_property (gobject_class, PROP_FD,
833 g_param_spec_int ("fd",
834 P_("File descriptor"),
835 P_("The sockets file descriptor"),
839 G_PARAM_CONSTRUCT_ONLY |
841 G_PARAM_STATIC_STRINGS));
843 g_object_class_install_property (gobject_class, PROP_BLOCKING,
844 g_param_spec_boolean ("blocking",
846 P_("Whether or not I/O on this socket is blocking"),
849 G_PARAM_STATIC_STRINGS));
851 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
852 g_param_spec_int ("listen-backlog",
853 P_("Listen backlog"),
854 P_("Outstanding connections in the listen queue"),
859 G_PARAM_STATIC_STRINGS));
861 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
862 g_param_spec_boolean ("keepalive",
863 P_("Keep connection alive"),
864 P_("Keep connection alive by sending periodic pings"),
867 G_PARAM_STATIC_STRINGS));
869 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
870 g_param_spec_object ("local-address",
872 P_("The local address the socket is bound to"),
873 G_TYPE_SOCKET_ADDRESS,
875 G_PARAM_STATIC_STRINGS));
877 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
878 g_param_spec_object ("remote-address",
879 P_("Remote address"),
880 P_("The remote address the socket is connected to"),
881 G_TYPE_SOCKET_ADDRESS,
883 G_PARAM_STATIC_STRINGS));
888 * The timeout in seconds on socket I/O
892 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
893 g_param_spec_uint ("timeout",
895 P_("The timeout in seconds on socket I/O"),
900 G_PARAM_STATIC_STRINGS));
905 * Whether the socket should allow sending to and receiving from broadcast addresses.
909 g_object_class_install_property (gobject_class, PROP_BROADCAST,
910 g_param_spec_boolean ("broadcast",
912 P_("Whether to allow sending to and receiving from broadcast addresses"),
915 G_PARAM_STATIC_STRINGS));
920 * Time-to-live for outgoing unicast packets
924 g_object_class_install_property (gobject_class, PROP_TTL,
925 g_param_spec_uint ("ttl",
927 P_("Time-to-live of outgoing unicast packets"),
930 G_PARAM_STATIC_STRINGS));
933 * GSocket:multicast-loopback:
935 * Whether outgoing multicast packets loop back to the local host.
939 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
940 g_param_spec_boolean ("multicast-loopback",
941 P_("Multicast loopback"),
942 P_("Whether outgoing multicast packets loop back to the local host"),
945 G_PARAM_STATIC_STRINGS));
948 * GSocket:multicast-ttl:
950 * Time-to-live out outgoing multicast packets
954 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
955 g_param_spec_uint ("multicast-ttl",
957 P_("Time-to-live of outgoing multicast packets"),
960 G_PARAM_STATIC_STRINGS));
964 g_socket_initable_iface_init (GInitableIface *iface)
966 iface->init = g_socket_initable_init;
970 g_socket_init (GSocket *socket)
972 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
974 socket->priv->fd = -1;
975 socket->priv->blocking = TRUE;
976 socket->priv->listen_backlog = 10;
977 socket->priv->construct_error = NULL;
979 socket->priv->event = WSA_INVALID_EVENT;
984 g_socket_initable_init (GInitable *initable,
985 GCancellable *cancellable,
990 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
992 socket = G_SOCKET (initable);
994 if (cancellable != NULL)
996 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
997 _("Cancellable initialization not supported"));
1001 socket->priv->inited = TRUE;
1003 if (socket->priv->construct_error)
1006 *error = g_error_copy (socket->priv->construct_error);
1016 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1017 * @type: the socket type to use.
1018 * @protocol: the id of the protocol to use, or 0 for default.
1019 * @error: #GError for error reporting, or %NULL to ignore.
1021 * Creates a new #GSocket with the defined family, type and protocol.
1022 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1023 * for the family and type is used.
1025 * The @protocol is a family and type specific int that specifies what
1026 * kind of protocol to use. #GSocketProtocol lists several common ones.
1027 * Many families only support one protocol, and use 0 for this, others
1028 * support several and using 0 means to use the default protocol for
1029 * the family and type.
1031 * The protocol id is passed directly to the operating
1032 * system, so you can use protocols not listed in #GSocketProtocol if you
1033 * know the protocol number used for it.
1035 * Returns: a #GSocket or %NULL on error.
1036 * Free the returned object with g_object_unref().
1041 g_socket_new (GSocketFamily family,
1043 GSocketProtocol protocol,
1046 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1050 "protocol", protocol,
1055 * g_socket_new_from_fd:
1056 * @fd: a native socket file descriptor.
1057 * @error: #GError for error reporting, or %NULL to ignore.
1059 * Creates a new #GSocket from a native file descriptor
1060 * or winsock SOCKET handle.
1062 * This reads all the settings from the file descriptor so that
1063 * all properties should work. Note that the file descriptor
1064 * will be set to non-blocking mode, independent on the blocking
1065 * mode of the #GSocket.
1067 * Returns: a #GSocket or %NULL on error.
1068 * Free the returned object with g_object_unref().
1073 g_socket_new_from_fd (gint fd,
1076 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1083 * g_socket_set_blocking:
1084 * @socket: a #GSocket.
1085 * @blocking: Whether to use blocking I/O or not.
1087 * Sets the blocking mode of the socket. In blocking mode
1088 * all operations block until they succeed or there is an error. In
1089 * non-blocking mode all functions return results immediately or
1090 * with a %G_IO_ERROR_WOULD_BLOCK error.
1092 * All sockets are created in blocking mode. However, note that the
1093 * platform level socket is always non-blocking, and blocking mode
1094 * is a GSocket level feature.
1099 g_socket_set_blocking (GSocket *socket,
1102 g_return_if_fail (G_IS_SOCKET (socket));
1104 blocking = !!blocking;
1106 if (socket->priv->blocking == blocking)
1109 socket->priv->blocking = blocking;
1110 g_object_notify (G_OBJECT (socket), "blocking");
1114 * g_socket_get_blocking:
1115 * @socket: a #GSocket.
1117 * Gets the blocking mode of the socket. For details on blocking I/O,
1118 * see g_socket_set_blocking().
1120 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1125 g_socket_get_blocking (GSocket *socket)
1127 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1129 return socket->priv->blocking;
1133 * g_socket_set_keepalive:
1134 * @socket: a #GSocket.
1135 * @keepalive: Value for the keepalive flag
1137 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1138 * this flag is set on a socket, the system will attempt to verify that the
1139 * remote socket endpoint is still present if a sufficiently long period of
1140 * time passes with no data being exchanged. If the system is unable to
1141 * verify the presence of the remote endpoint, it will automatically close
1144 * This option is only functional on certain kinds of sockets. (Notably,
1145 * %G_SOCKET_PROTOCOL_TCP sockets.)
1147 * The exact time between pings is system- and protocol-dependent, but will
1148 * normally be at least two hours. Most commonly, you would set this flag
1149 * on a server socket if you want to allow clients to remain idle for long
1150 * periods of time, but also want to ensure that connections are eventually
1151 * garbage-collected if clients crash or become unreachable.
1156 g_socket_set_keepalive (GSocket *socket,
1161 g_return_if_fail (G_IS_SOCKET (socket));
1163 keepalive = !!keepalive;
1164 if (socket->priv->keepalive == keepalive)
1167 value = (gint) keepalive;
1168 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1169 (gpointer) &value, sizeof (value)) < 0)
1171 int errsv = get_socket_errno ();
1172 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1176 socket->priv->keepalive = keepalive;
1177 g_object_notify (G_OBJECT (socket), "keepalive");
1181 * g_socket_get_keepalive:
1182 * @socket: a #GSocket.
1184 * Gets the keepalive mode of the socket. For details on this,
1185 * see g_socket_set_keepalive().
1187 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1192 g_socket_get_keepalive (GSocket *socket)
1194 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1196 return socket->priv->keepalive;
1200 * g_socket_get_listen_backlog:
1201 * @socket: a #GSocket.
1203 * Gets the listen backlog setting of the socket. For details on this,
1204 * see g_socket_set_listen_backlog().
1206 * Returns: the maximum number of pending connections.
1211 g_socket_get_listen_backlog (GSocket *socket)
1213 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1215 return socket->priv->listen_backlog;
1219 * g_socket_set_listen_backlog:
1220 * @socket: a #GSocket.
1221 * @backlog: the maximum number of pending connections.
1223 * Sets the maximum number of outstanding connections allowed
1224 * when listening on this socket. If more clients than this are
1225 * connecting to the socket and the application is not handling them
1226 * on time then the new connections will be refused.
1228 * Note that this must be called before g_socket_listen() and has no
1229 * effect if called after that.
1234 g_socket_set_listen_backlog (GSocket *socket,
1237 g_return_if_fail (G_IS_SOCKET (socket));
1238 g_return_if_fail (!socket->priv->listening);
1240 if (backlog != socket->priv->listen_backlog)
1242 socket->priv->listen_backlog = backlog;
1243 g_object_notify (G_OBJECT (socket), "listen-backlog");
1248 * g_socket_get_timeout:
1249 * @socket: a #GSocket.
1251 * Gets the timeout setting of the socket. For details on this, see
1252 * g_socket_set_timeout().
1254 * Returns: the timeout in seconds
1259 g_socket_get_timeout (GSocket *socket)
1261 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1263 return socket->priv->timeout;
1267 * g_socket_set_timeout:
1268 * @socket: a #GSocket.
1269 * @timeout: the timeout for @socket, in seconds, or 0 for none
1271 * Sets the time in seconds after which I/O operations on @socket will
1272 * time out if they have not yet completed.
1274 * On a blocking socket, this means that any blocking #GSocket
1275 * operation will time out after @timeout seconds of inactivity,
1276 * returning %G_IO_ERROR_TIMED_OUT.
1278 * On a non-blocking socket, calls to g_socket_condition_wait() will
1279 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1280 * created with g_socket_create_source() will trigger after
1281 * @timeout seconds of inactivity, with the requested condition
1282 * set, at which point calling g_socket_receive(), g_socket_send(),
1283 * g_socket_check_connect_result(), etc, will fail with
1284 * %G_IO_ERROR_TIMED_OUT.
1286 * If @timeout is 0 (the default), operations will never time out
1289 * Note that if an I/O operation is interrupted by a signal, this may
1290 * cause the timeout to be reset.
1295 g_socket_set_timeout (GSocket *socket,
1298 g_return_if_fail (G_IS_SOCKET (socket));
1300 if (timeout != socket->priv->timeout)
1302 socket->priv->timeout = timeout;
1303 g_object_notify (G_OBJECT (socket), "timeout");
1309 * @socket: a #GSocket.
1311 * Gets the unicast time-to-live setting on @socket; see
1312 * g_socket_set_ttl() for more details.
1314 * Returns: the time-to-live setting on @socket
1319 g_socket_get_ttl (GSocket *socket)
1322 guint value, optlen;
1324 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1326 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1330 optlen = sizeof (optval);
1331 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_TTL,
1335 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1337 optlen = sizeof (value);
1338 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1342 g_return_val_if_reached (FALSE);
1346 int errsv = get_socket_errno ();
1347 g_warning ("error getting unicast ttl: %s", socket_strerror (errsv));
1356 * @socket: a #GSocket.
1357 * @ttl: the time-to-live value for all unicast packets on @socket
1359 * Sets the time-to-live for outgoing unicast packets on @socket.
1360 * By default the platform-specific default value is used.
1365 g_socket_set_ttl (GSocket *socket,
1370 g_return_if_fail (G_IS_SOCKET (socket));
1372 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1374 guchar optval = (guchar)ttl;
1376 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_TTL,
1377 &optval, sizeof (optval));
1379 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1381 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1382 &ttl, sizeof (ttl));
1385 g_return_if_reached ();
1389 int errsv = get_socket_errno ();
1390 g_warning ("error setting unicast ttl: %s", socket_strerror (errsv));
1394 g_object_notify (G_OBJECT (socket), "ttl");
1398 * g_socket_get_broadcast:
1399 * @socket: a #GSocket.
1401 * Gets the broadcast setting on @socket; if %TRUE,
1402 * it is possible to send packets to broadcast
1403 * addresses or receive from broadcast addresses.
1405 * Returns: the broadcast setting on @socket
1410 g_socket_get_broadcast (GSocket *socket)
1413 guint value = 0, optlen;
1415 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1417 optlen = sizeof (guchar);
1418 result = getsockopt (socket->priv->fd, SOL_SOCKET, SO_BROADCAST,
1423 int errsv = get_socket_errno ();
1424 g_warning ("error getting broadcast: %s", socket_strerror (errsv));
1432 * g_socket_set_broadcast:
1433 * @socket: a #GSocket.
1434 * @broadcast: whether @socket should allow sending to and receiving
1435 * from broadcast addresses
1437 * Sets whether @socket should allow sending to and receiving from
1438 * broadcast addresses. This is %FALSE by default.
1443 g_socket_set_broadcast (GSocket *socket,
1449 g_return_if_fail (G_IS_SOCKET (socket));
1451 broadcast = !!broadcast;
1452 value = (guchar)broadcast;
1454 result = setsockopt (socket->priv->fd, SOL_SOCKET, SO_BROADCAST,
1455 &value, sizeof (value));
1459 int errsv = get_socket_errno ();
1460 g_warning ("error setting broadcast: %s", socket_strerror (errsv));
1464 g_object_notify (G_OBJECT (socket), "broadcast");
1468 * g_socket_get_multicast_loopback:
1469 * @socket: a #GSocket.
1471 * Gets the multicast loopback setting on @socket; if %TRUE (the
1472 * default), outgoing multicast packets will be looped back to
1473 * multicast listeners on the same host.
1475 * Returns: the multicast loopback setting on @socket
1480 g_socket_get_multicast_loopback (GSocket *socket)
1483 guint value = 0, optlen;
1485 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1487 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1489 optlen = sizeof (guchar);
1490 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1493 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1495 optlen = sizeof (guint);
1496 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1500 g_return_val_if_reached (FALSE);
1504 int errsv = get_socket_errno ();
1505 g_warning ("error getting multicast loopback: %s", socket_strerror (errsv));
1513 * g_socket_set_multicast_loopback:
1514 * @socket: a #GSocket.
1515 * @loopback: whether @socket should receive messages sent to its
1516 * multicast groups from the local host
1518 * Sets whether outgoing multicast packets will be received by sockets
1519 * listening on that multicast address on the same host. This is %TRUE
1525 g_socket_set_multicast_loopback (GSocket *socket,
1530 g_return_if_fail (G_IS_SOCKET (socket));
1532 loopback = !!loopback;
1534 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1536 guchar value = (guchar)loopback;
1538 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1539 &value, sizeof (value));
1541 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1543 guint value = (guint)loopback;
1545 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1546 &value, sizeof (value));
1549 g_return_if_reached ();
1553 int errsv = get_socket_errno ();
1554 g_warning ("error setting multicast loopback: %s", socket_strerror (errsv));
1558 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1562 * g_socket_get_multicast_ttl:
1563 * @socket: a #GSocket.
1565 * Gets the multicast time-to-live setting on @socket; see
1566 * g_socket_set_multicast_ttl() for more details.
1568 * Returns: the multicast time-to-live setting on @socket
1573 g_socket_get_multicast_ttl (GSocket *socket)
1576 guint value, optlen;
1578 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1580 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1584 optlen = sizeof (optval);
1585 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1589 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1591 optlen = sizeof (value);
1592 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1596 g_return_val_if_reached (FALSE);
1600 int errsv = get_socket_errno ();
1601 g_warning ("error getting multicast ttl: %s", socket_strerror (errsv));
1609 * g_socket_set_multicast_ttl:
1610 * @socket: a #GSocket.
1611 * @ttl: the time-to-live value for all multicast datagrams on @socket
1613 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1614 * By default, this is 1, meaning that multicast packets will not leave
1615 * the local network.
1620 g_socket_set_multicast_ttl (GSocket *socket,
1625 g_return_if_fail (G_IS_SOCKET (socket));
1627 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1629 guchar optval = (guchar)ttl;
1631 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1632 &optval, sizeof (optval));
1634 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1636 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1637 &ttl, sizeof (ttl));
1640 g_return_if_reached ();
1644 int errsv = get_socket_errno ();
1645 g_warning ("error setting multicast ttl: %s", socket_strerror (errsv));
1649 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1653 * g_socket_get_family:
1654 * @socket: a #GSocket.
1656 * Gets the socket family of the socket.
1658 * Returns: a #GSocketFamily
1663 g_socket_get_family (GSocket *socket)
1665 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1667 return socket->priv->family;
1671 * g_socket_get_socket_type:
1672 * @socket: a #GSocket.
1674 * Gets the socket type of the socket.
1676 * Returns: a #GSocketType
1681 g_socket_get_socket_type (GSocket *socket)
1683 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1685 return socket->priv->type;
1689 * g_socket_get_protocol:
1690 * @socket: a #GSocket.
1692 * Gets the socket protocol id the socket was created with.
1693 * In case the protocol is unknown, -1 is returned.
1695 * Returns: a protocol id, or -1 if unknown
1700 g_socket_get_protocol (GSocket *socket)
1702 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1704 return socket->priv->protocol;
1709 * @socket: a #GSocket.
1711 * Returns the underlying OS socket object. On unix this
1712 * is a socket file descriptor, and on Windows this is
1713 * a Winsock2 SOCKET handle. This may be useful for
1714 * doing platform specific or otherwise unusual operations
1717 * Returns: the file descriptor of the socket.
1722 g_socket_get_fd (GSocket *socket)
1724 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1726 return socket->priv->fd;
1730 * g_socket_get_local_address:
1731 * @socket: a #GSocket.
1732 * @error: #GError for error reporting, or %NULL to ignore.
1734 * Try to get the local address of a bound socket. This is only
1735 * useful if the socket has been bound to a local address,
1736 * either explicitly or implicitly when connecting.
1738 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1739 * Free the returned object with g_object_unref().
1744 g_socket_get_local_address (GSocket *socket,
1747 struct sockaddr_storage buffer;
1748 guint len = sizeof (buffer);
1750 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1752 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1754 int errsv = get_socket_errno ();
1755 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1756 _("could not get local address: %s"), socket_strerror (errsv));
1760 return g_socket_address_new_from_native (&buffer, len);
1764 * g_socket_get_remote_address:
1765 * @socket: a #GSocket.
1766 * @error: #GError for error reporting, or %NULL to ignore.
1768 * Try to get the remove address of a connected socket. This is only
1769 * useful for connection oriented sockets that have been connected.
1771 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1772 * Free the returned object with g_object_unref().
1777 g_socket_get_remote_address (GSocket *socket,
1780 struct sockaddr_storage buffer;
1781 guint len = sizeof (buffer);
1783 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1785 if (socket->priv->connect_pending)
1787 if (!g_socket_check_connect_result (socket, error))
1790 socket->priv->connect_pending = FALSE;
1793 if (!socket->priv->remote_address)
1795 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1797 int errsv = get_socket_errno ();
1798 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1799 _("could not get remote address: %s"), socket_strerror (errsv));
1803 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1806 return g_object_ref (socket->priv->remote_address);
1810 * g_socket_is_connected:
1811 * @socket: a #GSocket.
1813 * Check whether the socket is connected. This is only useful for
1814 * connection-oriented sockets.
1816 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1821 g_socket_is_connected (GSocket *socket)
1823 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1825 return socket->priv->connected;
1830 * @socket: a #GSocket.
1831 * @error: #GError for error reporting, or %NULL to ignore.
1833 * Marks the socket as a server socket, i.e. a socket that is used
1834 * to accept incoming requests using g_socket_accept().
1836 * Before calling this the socket must be bound to a local address using
1839 * To set the maximum amount of outstanding clients, use
1840 * g_socket_set_listen_backlog().
1842 * Returns: %TRUE on success, %FALSE on error.
1847 g_socket_listen (GSocket *socket,
1850 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1852 if (!check_socket (socket, error))
1855 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1857 int errsv = get_socket_errno ();
1859 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1860 _("could not listen: %s"), socket_strerror (errsv));
1864 socket->priv->listening = TRUE;
1871 * @socket: a #GSocket.
1872 * @address: a #GSocketAddress specifying the local address.
1873 * @allow_reuse: whether to allow reusing this address
1874 * @error: #GError for error reporting, or %NULL to ignore.
1876 * When a socket is created it is attached to an address family, but it
1877 * doesn't have an address in this family. g_socket_bind() assigns the
1878 * address (sometimes called name) of the socket.
1880 * It is generally required to bind to a local address before you can
1881 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1882 * In certain situations, you may also want to bind a socket that will be
1883 * used to initiate connections, though this is not normally required.
1885 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1886 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1887 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1888 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1889 * that address was previously used by another socket that has not yet been
1890 * fully cleaned-up by the kernel. Failing to set this flag on a server
1891 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1892 * the server program is stopped and then immediately restarted.)
1894 * Returns: %TRUE on success, %FALSE on error.
1899 g_socket_bind (GSocket *socket,
1900 GSocketAddress *address,
1901 gboolean reuse_address,
1904 struct sockaddr_storage addr;
1906 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1908 if (!check_socket (socket, error))
1911 /* SO_REUSEADDR on Windows means something else and is not what we want.
1912 It always allows the unix variant of SO_REUSEADDR anyway */
1917 value = (int) !!reuse_address;
1918 /* Ignore errors here, the only likely error is "not supported", and
1919 this is a "best effort" thing mainly */
1920 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1921 (gpointer) &value, sizeof (value));
1925 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1928 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1929 g_socket_address_get_native_size (address)) < 0)
1931 int errsv = get_socket_errno ();
1933 G_IO_ERROR, socket_io_error_from_errno (errsv),
1934 _("Error binding to address: %s"), socket_strerror (errsv));
1942 g_socket_multicast_group_operation (GSocket *socket,
1943 GInetAddress *group,
1944 gboolean source_specific,
1946 gboolean join_group,
1949 const guint8 *native_addr;
1950 gint optname, result;
1952 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1953 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
1954 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
1955 g_return_val_if_fail (g_inet_address_get_family (group) == socket->priv->family, FALSE);
1957 if (!check_socket (socket, error))
1960 native_addr = g_inet_address_to_bytes (group);
1961 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1963 #ifdef HAVE_IP_MREQN
1964 struct ip_mreqn mc_req;
1966 struct ip_mreq mc_req;
1969 memset (&mc_req, 0, sizeof (mc_req));
1970 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
1972 #ifdef HAVE_IP_MREQN
1974 mc_req.imr_ifindex = if_nametoindex (iface);
1976 mc_req.imr_ifindex = 0; /* Pick any. */
1978 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
1981 if (source_specific)
1983 #ifdef IP_ADD_SOURCE_MEMBERSHIP
1984 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
1986 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1988 _("Error joining multicast group: %s") :
1989 _("Error leaving multicast group: %s"),
1990 _("No support for source-specific multicast"));
1995 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
1996 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
1997 &mc_req, sizeof (mc_req));
1999 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
2001 struct ipv6_mreq mc_req_ipv6;
2003 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2004 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2005 #ifdef HAVE_IF_NAMETOINDEX
2007 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2010 mc_req_ipv6.ipv6mr_interface = 0;
2012 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2013 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2014 &mc_req_ipv6, sizeof (mc_req_ipv6));
2017 g_return_val_if_reached (FALSE);
2021 int errsv = get_socket_errno ();
2023 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2025 _("Error joining multicast group: %s") :
2026 _("Error leaving multicast group: %s"),
2027 socket_strerror (errsv));
2035 * g_socket_join_multicast_group:
2036 * @socket: a #GSocket.
2037 * @group: a #GInetAddress specifying the group address to join.
2038 * @iface: (allow-none): Name of the interface to use, or %NULL
2039 * @source_specific: %TRUE if source-specific multicast should be used
2040 * @error: #GError for error reporting, or %NULL to ignore.
2042 * Registers @socket to receive multicast messages sent to @group.
2043 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2044 * been bound to an appropriate interface and port with
2047 * If @iface is %NULL, the system will automatically pick an interface
2048 * to bind to based on @group.
2050 * If @source_specific is %TRUE, source-specific multicast as defined
2051 * in RFC 4604 is used. Note that on older platforms this may fail
2052 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2054 * Returns: %TRUE on success, %FALSE on error.
2059 g_socket_join_multicast_group (GSocket *socket,
2060 GInetAddress *group,
2061 gboolean source_specific,
2065 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2069 * g_socket_leave_multicast_group:
2070 * @socket: a #GSocket.
2071 * @group: a #GInetAddress specifying the group address to leave.
2072 * @iface: (allow-none): Interface used
2073 * @source_specific: %TRUE if source-specific multicast was used
2074 * @error: #GError for error reporting, or %NULL to ignore.
2076 * Removes @socket from the multicast group defined by @group, @iface,
2077 * and @source_specific (which must all have the same values they had
2078 * when you joined the group).
2080 * @socket remains bound to its address and port, and can still receive
2081 * unicast messages after calling this.
2083 * Returns: %TRUE on success, %FALSE on error.
2088 g_socket_leave_multicast_group (GSocket *socket,
2089 GInetAddress *group,
2090 gboolean source_specific,
2094 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2098 * g_socket_speaks_ipv4:
2099 * @socket: a #GSocket
2101 * Checks if a socket is capable of speaking IPv4.
2103 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2104 * and under some combinations of circumstances IPv6 sockets are also
2105 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2108 * No other types of sockets are currently considered as being capable
2111 * Returns: %TRUE if this socket can be used with IPv4.
2116 g_socket_speaks_ipv4 (GSocket *socket)
2118 switch (socket->priv->family)
2120 case G_SOCKET_FAMILY_IPV4:
2123 case G_SOCKET_FAMILY_IPV6:
2124 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2126 guint sizeof_int = sizeof (int);
2129 if (getsockopt (socket->priv->fd,
2130 IPPROTO_IPV6, IPV6_V6ONLY,
2131 &v6_only, &sizeof_int) != 0)
2147 * @socket: a #GSocket.
2148 * @cancellable: (allow-none): a %GCancellable or %NULL
2149 * @error: #GError for error reporting, or %NULL to ignore.
2151 * Accept incoming connections on a connection-based socket. This removes
2152 * the first outstanding connection request from the listening socket and
2153 * creates a #GSocket object for it.
2155 * The @socket must be bound to a local address with g_socket_bind() and
2156 * must be listening for incoming connections (g_socket_listen()).
2158 * If there are no outstanding connections then the operation will block
2159 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2160 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2162 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2163 * Free the returned object with g_object_unref().
2168 g_socket_accept (GSocket *socket,
2169 GCancellable *cancellable,
2172 GSocket *new_socket;
2175 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2177 if (!check_socket (socket, error))
2182 if (socket->priv->blocking &&
2183 !g_socket_condition_wait (socket,
2184 G_IO_IN, cancellable, error))
2187 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2189 int errsv = get_socket_errno ();
2191 win32_unset_event_mask (socket, FD_ACCEPT);
2196 if (socket->priv->blocking)
2198 #ifdef WSAEWOULDBLOCK
2199 if (errsv == WSAEWOULDBLOCK)
2202 if (errsv == EWOULDBLOCK ||
2208 g_set_error (error, G_IO_ERROR,
2209 socket_io_error_from_errno (errsv),
2210 _("Error accepting connection: %s"), socket_strerror (errsv));
2216 win32_unset_event_mask (socket, FD_ACCEPT);
2220 /* The socket inherits the accepting sockets event mask and even object,
2221 we need to remove that */
2222 WSAEventSelect (ret, NULL, 0);
2228 /* We always want to set close-on-exec to protect users. If you
2229 need to so some weird inheritance to exec you can re-enable this
2230 using lower level hacks with g_socket_get_fd(). */
2231 flags = fcntl (ret, F_GETFD, 0);
2233 (flags & FD_CLOEXEC) == 0)
2235 flags |= FD_CLOEXEC;
2236 fcntl (ret, F_SETFD, flags);
2241 new_socket = g_socket_new_from_fd (ret, error);
2242 if (new_socket == NULL)
2251 new_socket->priv->protocol = socket->priv->protocol;
2258 * @socket: a #GSocket.
2259 * @address: a #GSocketAddress specifying the remote address.
2260 * @cancellable: (allow-none): a %GCancellable or %NULL
2261 * @error: #GError for error reporting, or %NULL to ignore.
2263 * Connect the socket to the specified remote address.
2265 * For connection oriented socket this generally means we attempt to make
2266 * a connection to the @address. For a connection-less socket it sets
2267 * the default address for g_socket_send() and discards all incoming datagrams
2268 * from other sources.
2270 * Generally connection oriented sockets can only connect once, but
2271 * connection-less sockets can connect multiple times to change the
2274 * If the connect call needs to do network I/O it will block, unless
2275 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2276 * and the user can be notified of the connection finishing by waiting
2277 * for the G_IO_OUT condition. The result of the connection must then be
2278 * checked with g_socket_check_connect_result().
2280 * Returns: %TRUE if connected, %FALSE on error.
2285 g_socket_connect (GSocket *socket,
2286 GSocketAddress *address,
2287 GCancellable *cancellable,
2290 struct sockaddr_storage buffer;
2292 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2294 if (!check_socket (socket, error))
2297 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2300 if (socket->priv->remote_address)
2301 g_object_unref (socket->priv->remote_address);
2302 socket->priv->remote_address = g_object_ref (address);
2306 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2307 g_socket_address_get_native_size (address)) < 0)
2309 int errsv = get_socket_errno ();
2315 if (errsv == EINPROGRESS)
2317 if (errsv == WSAEWOULDBLOCK)
2320 if (socket->priv->blocking)
2322 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2324 if (g_socket_check_connect_result (socket, error))
2330 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2331 _("Connection in progress"));
2332 socket->priv->connect_pending = TRUE;
2336 g_set_error_literal (error, G_IO_ERROR,
2337 socket_io_error_from_errno (errsv),
2338 socket_strerror (errsv));
2345 win32_unset_event_mask (socket, FD_CONNECT);
2347 socket->priv->connected = TRUE;
2353 * g_socket_check_connect_result:
2354 * @socket: a #GSocket
2355 * @error: #GError for error reporting, or %NULL to ignore.
2357 * Checks and resets the pending connect error for the socket.
2358 * This is used to check for errors when g_socket_connect() is
2359 * used in non-blocking mode.
2361 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2366 g_socket_check_connect_result (GSocket *socket,
2372 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2374 if (!check_socket (socket, error))
2377 optlen = sizeof (value);
2378 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
2380 int errsv = get_socket_errno ();
2382 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2383 _("Unable to get pending error: %s"), socket_strerror (errsv));
2389 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2390 socket_strerror (value));
2391 if (socket->priv->remote_address)
2393 g_object_unref (socket->priv->remote_address);
2394 socket->priv->remote_address = NULL;
2399 socket->priv->connected = TRUE;
2404 * g_socket_get_available_bytes:
2405 * @socket: a #GSocket
2407 * Get the amount of data pending in the OS input buffer.
2409 * Returns: the number of bytes that can be read from the socket
2410 * without blocking or -1 on error.
2415 g_socket_get_available_bytes (GSocket *socket)
2419 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2422 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2425 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) == SOCKET_ERROR)
2434 * @socket: a #GSocket
2435 * @buffer: a buffer to read data into (which should be at least @size
2437 * @size: the number of bytes you want to read from the socket
2438 * @cancellable: (allow-none): a %GCancellable or %NULL
2439 * @error: #GError for error reporting, or %NULL to ignore.
2441 * Receive data (up to @size bytes) from a socket. This is mainly used by
2442 * connection-oriented sockets; it is identical to g_socket_receive_from()
2443 * with @address set to %NULL.
2445 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2446 * g_socket_receive() will always read either 0 or 1 complete messages from
2447 * the socket. If the received message is too large to fit in @buffer, then
2448 * the data beyond @size bytes will be discarded, without any explicit
2449 * indication that this has occurred.
2451 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2452 * number of bytes, up to @size. If more than @size bytes have been
2453 * received, the additional data will be returned in future calls to
2454 * g_socket_receive().
2456 * If the socket is in blocking mode the call will block until there
2457 * is some data to receive, the connection is closed, or there is an
2458 * error. If there is no data available and the socket is in
2459 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2460 * returned. To be notified when data is available, wait for the
2461 * %G_IO_IN condition.
2463 * On error -1 is returned and @error is set accordingly.
2465 * Returns: Number of bytes read, or 0 if the connection was closed by
2466 * the peer, or -1 on error
2471 g_socket_receive (GSocket *socket,
2474 GCancellable *cancellable,
2477 return g_socket_receive_with_blocking (socket, buffer, size,
2478 socket->priv->blocking,
2479 cancellable, error);
2483 * g_socket_receive_with_blocking:
2484 * @socket: a #GSocket
2485 * @buffer: a buffer to read data into (which should be at least @size
2487 * @size: the number of bytes you want to read from the socket
2488 * @blocking: whether to do blocking or non-blocking I/O
2489 * @cancellable: (allow-none): a %GCancellable or %NULL
2490 * @error: #GError for error reporting, or %NULL to ignore.
2492 * This behaves exactly the same as g_socket_receive(), except that
2493 * the choice of blocking or non-blocking behavior is determined by
2494 * the @blocking argument rather than by @socket's properties.
2496 * Returns: Number of bytes read, or 0 if the connection was closed by
2497 * the peer, or -1 on error
2502 g_socket_receive_with_blocking (GSocket *socket,
2506 GCancellable *cancellable,
2511 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2513 if (!check_socket (socket, error))
2516 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2522 !g_socket_condition_wait (socket,
2523 G_IO_IN, cancellable, error))
2526 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2528 int errsv = get_socket_errno ();
2535 #ifdef WSAEWOULDBLOCK
2536 if (errsv == WSAEWOULDBLOCK)
2539 if (errsv == EWOULDBLOCK ||
2545 win32_unset_event_mask (socket, FD_READ);
2547 g_set_error (error, G_IO_ERROR,
2548 socket_io_error_from_errno (errsv),
2549 _("Error receiving data: %s"), socket_strerror (errsv));
2553 win32_unset_event_mask (socket, FD_READ);
2562 * g_socket_receive_from:
2563 * @socket: a #GSocket
2564 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2566 * @buffer: (array length=size) (element-type guint8): a buffer to
2567 * read data into (which should be at least @size bytes long).
2568 * @size: the number of bytes you want to read from the socket
2569 * @cancellable: (allow-none): a %GCancellable or %NULL
2570 * @error: #GError for error reporting, or %NULL to ignore.
2572 * Receive data (up to @size bytes) from a socket.
2574 * If @address is non-%NULL then @address will be set equal to the
2575 * source address of the received packet.
2576 * @address is owned by the caller.
2578 * See g_socket_receive() for additional information.
2580 * Returns: Number of bytes read, or 0 if the connection was closed by
2581 * the peer, or -1 on error
2586 g_socket_receive_from (GSocket *socket,
2587 GSocketAddress **address,
2590 GCancellable *cancellable,
2598 return g_socket_receive_message (socket,
2606 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2607 * one, which can be confusing and annoying. So if possible, we want
2608 * to suppress the signal entirely.
2611 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2613 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2618 * @socket: a #GSocket
2619 * @buffer: (array length=size) (element-type guint8): the buffer
2620 * containing the data to send.
2621 * @size: the number of bytes to send
2622 * @cancellable: (allow-none): a %GCancellable or %NULL
2623 * @error: #GError for error reporting, or %NULL to ignore.
2625 * Tries to send @size bytes from @buffer on the socket. This is
2626 * mainly used by connection-oriented sockets; it is identical to
2627 * g_socket_send_to() with @address set to %NULL.
2629 * If the socket is in blocking mode the call will block until there is
2630 * space for the data in the socket queue. If there is no space available
2631 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2632 * will be returned. To be notified when space is available, wait for the
2633 * %G_IO_OUT condition. Note though that you may still receive
2634 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2635 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2636 * very common due to the way the underlying APIs work.)
2638 * On error -1 is returned and @error is set accordingly.
2640 * Returns: Number of bytes written (which may be less than @size), or -1
2646 g_socket_send (GSocket *socket,
2647 const gchar *buffer,
2649 GCancellable *cancellable,
2652 return g_socket_send_with_blocking (socket, buffer, size,
2653 socket->priv->blocking,
2654 cancellable, error);
2658 * g_socket_send_with_blocking:
2659 * @socket: a #GSocket
2660 * @buffer: (array length=size) (element-type guint8): the buffer
2661 * containing the data to send.
2662 * @size: the number of bytes to send
2663 * @blocking: whether to do blocking or non-blocking I/O
2664 * @cancellable: (allow-none): a %GCancellable or %NULL
2665 * @error: #GError for error reporting, or %NULL to ignore.
2667 * This behaves exactly the same as g_socket_send(), except that
2668 * the choice of blocking or non-blocking behavior is determined by
2669 * the @blocking argument rather than by @socket's properties.
2671 * Returns: Number of bytes written (which may be less than @size), or -1
2677 g_socket_send_with_blocking (GSocket *socket,
2678 const gchar *buffer,
2681 GCancellable *cancellable,
2686 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2688 if (!check_socket (socket, error))
2691 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2697 !g_socket_condition_wait (socket,
2698 G_IO_OUT, cancellable, error))
2701 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2703 int errsv = get_socket_errno ();
2708 #ifdef WSAEWOULDBLOCK
2709 if (errsv == WSAEWOULDBLOCK)
2710 win32_unset_event_mask (socket, FD_WRITE);
2715 #ifdef WSAEWOULDBLOCK
2716 if (errsv == WSAEWOULDBLOCK)
2719 if (errsv == EWOULDBLOCK ||
2725 g_set_error (error, G_IO_ERROR,
2726 socket_io_error_from_errno (errsv),
2727 _("Error sending data: %s"), socket_strerror (errsv));
2738 * @socket: a #GSocket
2739 * @address: (allow-none): a #GSocketAddress, or %NULL
2740 * @buffer: (array length=size) (element-type guint8): the buffer
2741 * containing the data to send.
2742 * @size: the number of bytes to send
2743 * @cancellable: (allow-none): a %GCancellable or %NULL
2744 * @error: #GError for error reporting, or %NULL to ignore.
2746 * Tries to send @size bytes from @buffer to @address. If @address is
2747 * %NULL then the message is sent to the default receiver (set by
2748 * g_socket_connect()).
2750 * See g_socket_send() for additional information.
2752 * Returns: Number of bytes written (which may be less than @size), or -1
2758 g_socket_send_to (GSocket *socket,
2759 GSocketAddress *address,
2760 const gchar *buffer,
2762 GCancellable *cancellable,
2770 return g_socket_send_message (socket,
2780 * g_socket_shutdown:
2781 * @socket: a #GSocket
2782 * @shutdown_read: whether to shut down the read side
2783 * @shutdown_write: whether to shut down the write side
2784 * @error: #GError for error reporting, or %NULL to ignore.
2786 * Shut down part of a full-duplex connection.
2788 * If @shutdown_read is %TRUE then the receiving side of the connection
2789 * is shut down, and further reading is disallowed.
2791 * If @shutdown_write is %TRUE then the sending side of the connection
2792 * is shut down, and further writing is disallowed.
2794 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2796 * One example where this is used is graceful disconnect for TCP connections
2797 * where you close the sending side, then wait for the other side to close
2798 * the connection, thus ensuring that the other side saw all sent data.
2800 * Returns: %TRUE on success, %FALSE on error
2805 g_socket_shutdown (GSocket *socket,
2806 gboolean shutdown_read,
2807 gboolean shutdown_write,
2812 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2814 if (!check_socket (socket, error))
2818 if (!shutdown_read && !shutdown_write)
2822 if (shutdown_read && shutdown_write)
2824 else if (shutdown_read)
2829 if (shutdown_read && shutdown_write)
2831 else if (shutdown_read)
2837 if (shutdown (socket->priv->fd, how) != 0)
2839 int errsv = get_socket_errno ();
2840 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2841 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2845 if (shutdown_read && shutdown_write)
2846 socket->priv->connected = FALSE;
2853 * @socket: a #GSocket
2854 * @error: #GError for error reporting, or %NULL to ignore.
2856 * Closes the socket, shutting down any active connection.
2858 * Closing a socket does not wait for all outstanding I/O operations
2859 * to finish, so the caller should not rely on them to be guaranteed
2860 * to complete even if the close returns with no error.
2862 * Once the socket is closed, all other operations will return
2863 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2866 * Sockets will be automatically closed when the last reference
2867 * is dropped, but you might want to call this function to make sure
2868 * resources are released as early as possible.
2870 * Beware that due to the way that TCP works, it is possible for
2871 * recently-sent data to be lost if either you close a socket while the
2872 * %G_IO_IN condition is set, or else if the remote connection tries to
2873 * send something to you after you close the socket but before it has
2874 * finished reading all of the data you sent. There is no easy generic
2875 * way to avoid this problem; the easiest fix is to design the network
2876 * protocol such that the client will never send data "out of turn".
2877 * Another solution is for the server to half-close the connection by
2878 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2879 * and then wait for the client to notice this and close its side of the
2880 * connection, after which the server can safely call g_socket_close().
2881 * (This is what #GTcpConnection does if you call
2882 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2883 * only works if the client will close its connection after the server
2886 * Returns: %TRUE on success, %FALSE on error
2891 g_socket_close (GSocket *socket,
2896 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2898 if (socket->priv->closed)
2899 return TRUE; /* Multiple close not an error */
2901 if (!check_socket (socket, error))
2907 res = closesocket (socket->priv->fd);
2909 res = close (socket->priv->fd);
2913 int errsv = get_socket_errno ();
2918 g_set_error (error, G_IO_ERROR,
2919 socket_io_error_from_errno (errsv),
2920 _("Error closing socket: %s"),
2921 socket_strerror (errsv));
2927 socket->priv->connected = FALSE;
2928 socket->priv->closed = TRUE;
2929 if (socket->priv->remote_address)
2931 g_object_unref (socket->priv->remote_address);
2932 socket->priv->remote_address = NULL;
2939 * g_socket_is_closed:
2940 * @socket: a #GSocket
2942 * Checks whether a socket is closed.
2944 * Returns: %TRUE if socket is closed, %FALSE otherwise
2949 g_socket_is_closed (GSocket *socket)
2951 return socket->priv->closed;
2955 /* Broken source, used on errors */
2957 broken_prepare (GSource *source,
2964 broken_check (GSource *source)
2970 broken_dispatch (GSource *source,
2971 GSourceFunc callback,
2977 static GSourceFuncs broken_funcs =
2986 network_events_for_condition (GIOCondition condition)
2990 if (condition & G_IO_IN)
2991 event_mask |= (FD_READ | FD_ACCEPT);
2992 if (condition & G_IO_OUT)
2993 event_mask |= (FD_WRITE | FD_CONNECT);
2994 event_mask |= FD_CLOSE;
3000 ensure_event (GSocket *socket)
3002 if (socket->priv->event == WSA_INVALID_EVENT)
3003 socket->priv->event = WSACreateEvent();
3007 update_select_events (GSocket *socket)
3014 ensure_event (socket);
3017 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3020 event_mask |= network_events_for_condition (*ptr);
3023 if (event_mask != socket->priv->selected_events)
3025 /* If no events selected, disable event so we can unset
3028 if (event_mask == 0)
3031 event = socket->priv->event;
3033 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3034 socket->priv->selected_events = event_mask;
3039 add_condition_watch (GSocket *socket,
3040 GIOCondition *condition)
3042 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3044 socket->priv->requested_conditions =
3045 g_list_prepend (socket->priv->requested_conditions, condition);
3047 update_select_events (socket);
3051 remove_condition_watch (GSocket *socket,
3052 GIOCondition *condition)
3054 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3056 socket->priv->requested_conditions =
3057 g_list_remove (socket->priv->requested_conditions, condition);
3059 update_select_events (socket);
3063 update_condition (GSocket *socket)
3065 WSANETWORKEVENTS events;
3066 GIOCondition condition;
3068 if (WSAEnumNetworkEvents (socket->priv->fd,
3069 socket->priv->event,
3072 socket->priv->current_events |= events.lNetworkEvents;
3073 if (events.lNetworkEvents & FD_WRITE &&
3074 events.iErrorCode[FD_WRITE_BIT] != 0)
3075 socket->priv->current_errors |= FD_WRITE;
3076 if (events.lNetworkEvents & FD_CONNECT &&
3077 events.iErrorCode[FD_CONNECT_BIT] != 0)
3078 socket->priv->current_errors |= FD_CONNECT;
3082 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3083 condition |= G_IO_IN;
3085 if (socket->priv->current_events & FD_CLOSE)
3087 int r, errsv, buffer;
3089 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3091 errsv = get_socket_errno ();
3094 (r < 0 && errsv == WSAENOTCONN))
3095 condition |= G_IO_IN;
3097 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3098 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3099 condition |= G_IO_HUP;
3101 condition |= G_IO_ERR;
3104 if (socket->priv->closed)
3105 condition |= G_IO_HUP;
3107 /* Never report both G_IO_OUT and HUP, these are
3108 mutually exclusive (can't write to a closed socket) */
3109 if ((condition & G_IO_HUP) == 0 &&
3110 socket->priv->current_events & FD_WRITE)
3112 if (socket->priv->current_errors & FD_WRITE)
3113 condition |= G_IO_ERR;
3115 condition |= G_IO_OUT;
3119 if (socket->priv->current_events & FD_CONNECT)
3121 if (socket->priv->current_errors & FD_CONNECT)
3122 condition |= (G_IO_HUP | G_IO_ERR);
3124 condition |= G_IO_OUT;
3136 GIOCondition condition;
3137 GCancellable *cancellable;
3138 GPollFD cancel_pollfd;
3139 gint64 timeout_time;
3143 socket_source_prepare (GSource *source,
3146 GSocketSource *socket_source = (GSocketSource *)source;
3148 if (g_cancellable_is_cancelled (socket_source->cancellable))
3151 if (socket_source->timeout_time)
3155 now = g_source_get_time (source);
3156 /* Round up to ensure that we don't try again too early */
3157 *timeout = (socket_source->timeout_time - now + 999) / 1000;
3160 socket_source->socket->priv->timed_out = TRUE;
3169 socket_source->pollfd.revents = update_condition (socket_source->socket);
3172 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
3179 socket_source_check (GSource *source)
3183 return socket_source_prepare (source, &timeout);
3187 socket_source_dispatch (GSource *source,
3188 GSourceFunc callback,
3191 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3192 GSocketSource *socket_source = (GSocketSource *)source;
3193 GSocket *socket = socket_source->socket;
3197 socket_source->pollfd.revents = update_condition (socket_source->socket);
3199 if (socket_source->socket->priv->timed_out)
3200 socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
3202 ret = (*func) (socket,
3203 socket_source->pollfd.revents & socket_source->condition,
3206 if (socket->priv->timeout)
3207 socket_source->timeout_time = g_get_monotonic_time () +
3208 socket->priv->timeout * 1000000;
3211 socket_source->timeout_time = 0;
3217 socket_source_finalize (GSource *source)
3219 GSocketSource *socket_source = (GSocketSource *)source;
3222 socket = socket_source->socket;
3225 remove_condition_watch (socket, &socket_source->condition);
3228 g_object_unref (socket);
3230 if (socket_source->cancellable)
3232 g_cancellable_release_fd (socket_source->cancellable);
3233 g_object_unref (socket_source->cancellable);
3238 socket_source_closure_callback (GSocket *socket,
3239 GIOCondition condition,
3242 GClosure *closure = data;
3244 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3245 GValue result_value = G_VALUE_INIT;
3248 g_value_init (&result_value, G_TYPE_BOOLEAN);
3250 g_value_init (¶ms[0], G_TYPE_SOCKET);
3251 g_value_set_object (¶ms[0], socket);
3252 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
3253 g_value_set_flags (¶ms[1], condition);
3255 g_closure_invoke (closure, &result_value, 2, params, NULL);
3257 result = g_value_get_boolean (&result_value);
3258 g_value_unset (&result_value);
3259 g_value_unset (¶ms[0]);
3260 g_value_unset (¶ms[1]);
3265 static GSourceFuncs socket_source_funcs =
3267 socket_source_prepare,
3268 socket_source_check,
3269 socket_source_dispatch,
3270 socket_source_finalize,
3271 (GSourceFunc)socket_source_closure_callback,
3272 (GSourceDummyMarshal)g_cclosure_marshal_generic,
3276 socket_source_new (GSocket *socket,
3277 GIOCondition condition,
3278 GCancellable *cancellable)
3281 GSocketSource *socket_source;
3284 ensure_event (socket);
3286 if (socket->priv->event == WSA_INVALID_EVENT)
3288 g_warning ("Failed to create WSAEvent");
3289 return g_source_new (&broken_funcs, sizeof (GSource));
3293 condition |= G_IO_HUP | G_IO_ERR;
3295 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3296 g_source_set_name (source, "GSocket");
3297 socket_source = (GSocketSource *)source;
3299 socket_source->socket = g_object_ref (socket);
3300 socket_source->condition = condition;
3302 if (g_cancellable_make_pollfd (cancellable,
3303 &socket_source->cancel_pollfd))
3305 socket_source->cancellable = g_object_ref (cancellable);
3306 g_source_add_poll (source, &socket_source->cancel_pollfd);
3310 add_condition_watch (socket, &socket_source->condition);
3311 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3313 socket_source->pollfd.fd = socket->priv->fd;
3316 socket_source->pollfd.events = condition;
3317 socket_source->pollfd.revents = 0;
3318 g_source_add_poll (source, &socket_source->pollfd);
3320 if (socket->priv->timeout)
3321 socket_source->timeout_time = g_get_monotonic_time () +
3322 socket->priv->timeout * 1000000;
3325 socket_source->timeout_time = 0;
3331 * g_socket_create_source: (skip)
3332 * @socket: a #GSocket
3333 * @condition: a #GIOCondition mask to monitor
3334 * @cancellable: (allow-none): a %GCancellable or %NULL
3336 * Creates a %GSource that can be attached to a %GMainContext to monitor
3337 * for the availibility of the specified @condition on the socket.
3339 * The callback on the source is of the #GSocketSourceFunc type.
3341 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3342 * these conditions will always be reported output if they are true.
3344 * @cancellable if not %NULL can be used to cancel the source, which will
3345 * cause the source to trigger, reporting the current condition (which
3346 * is likely 0 unless cancellation happened at the same time as a
3347 * condition change). You can check for this in the callback using
3348 * g_cancellable_is_cancelled().
3350 * If @socket has a timeout set, and it is reached before @condition
3351 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3352 * %G_IO_OUT depending on @condition. However, @socket will have been
3353 * marked as having had a timeout, and so the next #GSocket I/O method
3354 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3356 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3361 g_socket_create_source (GSocket *socket,
3362 GIOCondition condition,
3363 GCancellable *cancellable)
3365 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3367 return socket_source_new (socket, condition, cancellable);
3371 * g_socket_condition_check:
3372 * @socket: a #GSocket
3373 * @condition: a #GIOCondition mask to check
3375 * Checks on the readiness of @socket to perform operations.
3376 * The operations specified in @condition are checked for and masked
3377 * against the currently-satisfied conditions on @socket. The result
3380 * Note that on Windows, it is possible for an operation to return
3381 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3382 * g_socket_condition_check() has claimed that the socket is ready for
3383 * writing. Rather than calling g_socket_condition_check() and then
3384 * writing to the socket if it succeeds, it is generally better to
3385 * simply try writing to the socket right away, and try again later if
3386 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3388 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3389 * these conditions will always be set in the output if they are true.
3391 * This call never blocks.
3393 * Returns: the @GIOCondition mask of the current state
3398 g_socket_condition_check (GSocket *socket,
3399 GIOCondition condition)
3401 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3403 if (!check_socket (socket, NULL))
3408 GIOCondition current_condition;
3410 condition |= G_IO_ERR | G_IO_HUP;
3412 add_condition_watch (socket, &condition);
3413 current_condition = update_condition (socket);
3414 remove_condition_watch (socket, &condition);
3415 return condition & current_condition;
3421 poll_fd.fd = socket->priv->fd;
3422 poll_fd.events = condition;
3423 poll_fd.revents = 0;
3426 result = g_poll (&poll_fd, 1, 0);
3427 while (result == -1 && get_socket_errno () == EINTR);
3429 return poll_fd.revents;
3435 * g_socket_condition_wait:
3436 * @socket: a #GSocket
3437 * @condition: a #GIOCondition mask to wait for
3438 * @cancellable: (allow-none): a #GCancellable, or %NULL
3439 * @error: a #GError pointer, or %NULL
3441 * Waits for @condition to become true on @socket. When the condition
3442 * is met, %TRUE is returned.
3444 * If @cancellable is cancelled before the condition is met, or if the
3445 * socket has a timeout set and it is reached before the condition is
3446 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3447 * the appropriate value (%G_IO_ERROR_CANCELLED or
3448 * %G_IO_ERROR_TIMED_OUT).
3450 * See also g_socket_condition_timed_wait().
3452 * Returns: %TRUE if the condition was met, %FALSE otherwise
3457 g_socket_condition_wait (GSocket *socket,
3458 GIOCondition condition,
3459 GCancellable *cancellable,
3462 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3464 return g_socket_condition_timed_wait (socket, condition, -1,
3465 cancellable, error);
3469 * g_socket_condition_timed_wait:
3470 * @socket: a #GSocket
3471 * @condition: a #GIOCondition mask to wait for
3472 * @timeout: the maximum time (in microseconds) to wait, or -1
3473 * @cancellable: (allow-none): a #GCancellable, or %NULL
3474 * @error: a #GError pointer, or %NULL
3476 * Waits for up to @timeout microseconds for @condition to become true
3477 * on @socket. If the condition is met, %TRUE is returned.
3479 * If @cancellable is cancelled before the condition is met, or if
3480 * @timeout (or the socket's #GSocket:timeout) is reached before the
3481 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3482 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3483 * %G_IO_ERROR_TIMED_OUT).
3485 * If you don't want a timeout, use g_socket_condition_wait().
3486 * (Alternatively, you can pass -1 for @timeout.)
3488 * Note that although @timeout is in microseconds for consistency with
3489 * other GLib APIs, this function actually only has millisecond
3490 * resolution, and the behavior is undefined if @timeout is not an
3491 * exact number of milliseconds.
3493 * Returns: %TRUE if the condition was met, %FALSE otherwise
3498 g_socket_condition_timed_wait (GSocket *socket,
3499 GIOCondition condition,
3501 GCancellable *cancellable,
3506 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3508 if (!check_socket (socket, error))
3511 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3514 if (socket->priv->timeout &&
3515 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3516 timeout = socket->priv->timeout * 1000;
3517 else if (timeout != -1)
3518 timeout = timeout / 1000;
3520 start_time = g_get_monotonic_time ();
3524 GIOCondition current_condition;
3530 /* Always check these */
3531 condition |= G_IO_ERR | G_IO_HUP;
3533 add_condition_watch (socket, &condition);
3536 events[num_events++] = socket->priv->event;
3538 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3539 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3542 timeout = WSA_INFINITE;
3544 current_condition = update_condition (socket);
3545 while ((condition & current_condition) == 0)
3547 res = WSAWaitForMultipleEvents (num_events, events,
3548 FALSE, timeout, FALSE);
3549 if (res == WSA_WAIT_FAILED)
3551 int errsv = get_socket_errno ();
3553 g_set_error (error, G_IO_ERROR,
3554 socket_io_error_from_errno (errsv),
3555 _("Waiting for socket condition: %s"),
3556 socket_strerror (errsv));
3559 else if (res == WSA_WAIT_TIMEOUT)
3561 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3562 _("Socket I/O timed out"));
3566 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3569 current_condition = update_condition (socket);
3571 if (timeout != WSA_INFINITE)
3573 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3578 remove_condition_watch (socket, &condition);
3580 g_cancellable_release_fd (cancellable);
3582 return (condition & current_condition) != 0;
3590 poll_fd[0].fd = socket->priv->fd;
3591 poll_fd[0].events = condition;
3594 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3599 result = g_poll (poll_fd, num, timeout);
3600 if (result != -1 || errno != EINTR)
3605 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3612 g_cancellable_release_fd (cancellable);
3616 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3617 _("Socket I/O timed out"));
3621 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3627 * g_socket_send_message:
3628 * @socket: a #GSocket
3629 * @address: (allow-none): a #GSocketAddress, or %NULL
3630 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3631 * @num_vectors: the number of elements in @vectors, or -1
3632 * @messages: (array length=num_messages) (allow-none): a pointer to an
3633 * array of #GSocketControlMessages, or %NULL.
3634 * @num_messages: number of elements in @messages, or -1.
3635 * @flags: an int containing #GSocketMsgFlags flags
3636 * @cancellable: (allow-none): a %GCancellable or %NULL
3637 * @error: #GError for error reporting, or %NULL to ignore.
3639 * Send data to @address on @socket. This is the most complicated and
3640 * fully-featured version of this call. For easier use, see
3641 * g_socket_send() and g_socket_send_to().
3643 * If @address is %NULL then the message is sent to the default receiver
3644 * (set by g_socket_connect()).
3646 * @vectors must point to an array of #GOutputVector structs and
3647 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3648 * then @vectors is assumed to be terminated by a #GOutputVector with a
3649 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3650 * that the sent data will be gathered from. Using multiple
3651 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3652 * data from multiple sources into a single buffer, and more
3653 * network-efficient than making multiple calls to g_socket_send().
3655 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3656 * #GSocketControlMessage instances. These correspond to the control
3657 * messages to be sent on the socket.
3658 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3661 * @flags modify how the message is sent. The commonly available arguments
3662 * for this are available in the #GSocketMsgFlags enum, but the
3663 * values there are the same as the system values, and the flags
3664 * are passed in as-is, so you can pass in system-specific flags too.
3666 * If the socket is in blocking mode the call will block until there is
3667 * space for the data in the socket queue. If there is no space available
3668 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3669 * will be returned. To be notified when space is available, wait for the
3670 * %G_IO_OUT condition. Note though that you may still receive
3671 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3672 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3673 * very common due to the way the underlying APIs work.)
3675 * On error -1 is returned and @error is set accordingly.
3677 * Returns: Number of bytes written (which may be less than @size), or -1
3683 g_socket_send_message (GSocket *socket,
3684 GSocketAddress *address,
3685 GOutputVector *vectors,
3687 GSocketControlMessage **messages,
3690 GCancellable *cancellable,
3693 GOutputVector one_vector;
3696 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3698 if (!check_socket (socket, error))
3701 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3704 if (num_vectors == -1)
3706 for (num_vectors = 0;
3707 vectors[num_vectors].buffer != NULL;
3712 if (num_messages == -1)
3714 for (num_messages = 0;
3715 messages != NULL && messages[num_messages] != NULL;
3720 if (num_vectors == 0)
3724 one_vector.buffer = &zero;
3725 one_vector.size = 1;
3727 vectors = &one_vector;
3740 msg.msg_namelen = g_socket_address_get_native_size (address);
3741 msg.msg_name = g_alloca (msg.msg_namelen);
3742 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3747 msg.msg_name = NULL;
3748 msg.msg_namelen = 0;
3753 /* this entire expression will be evaluated at compile time */
3754 if (sizeof *msg.msg_iov == sizeof *vectors &&
3755 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3756 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3757 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3758 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3759 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3760 G_STRUCT_OFFSET (GOutputVector, size))
3761 /* ABI is compatible */
3763 msg.msg_iov = (struct iovec *) vectors;
3764 msg.msg_iovlen = num_vectors;
3767 /* ABI is incompatible */
3771 msg.msg_iov = g_newa (struct iovec, num_vectors);
3772 for (i = 0; i < num_vectors; i++)
3774 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3775 msg.msg_iov[i].iov_len = vectors[i].size;
3777 msg.msg_iovlen = num_vectors;
3783 struct cmsghdr *cmsg;
3786 msg.msg_controllen = 0;
3787 for (i = 0; i < num_messages; i++)
3788 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3790 if (msg.msg_controllen == 0)
3791 msg.msg_control = NULL;
3794 msg.msg_control = g_alloca (msg.msg_controllen);
3795 memset (msg.msg_control, '\0', msg.msg_controllen);
3798 cmsg = CMSG_FIRSTHDR (&msg);
3799 for (i = 0; i < num_messages; i++)
3801 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3802 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3803 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3804 g_socket_control_message_serialize (messages[i],
3806 cmsg = CMSG_NXTHDR (&msg, cmsg);
3808 g_assert (cmsg == NULL);
3813 if (socket->priv->blocking &&
3814 !g_socket_condition_wait (socket,
3815 G_IO_OUT, cancellable, error))
3818 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3821 int errsv = get_socket_errno ();
3826 if (socket->priv->blocking &&
3827 (errsv == EWOULDBLOCK ||
3831 g_set_error (error, G_IO_ERROR,
3832 socket_io_error_from_errno (errsv),
3833 _("Error sending message: %s"), socket_strerror (errsv));
3844 struct sockaddr_storage addr;
3851 /* Win32 doesn't support control messages.
3852 Actually this is possible for raw and datagram sockets
3853 via WSASendMessage on Vista or later, but that doesn't
3855 if (num_messages != 0)
3857 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3858 _("GSocketControlMessage not supported on Windows"));
3863 bufs = g_newa (WSABUF, num_vectors);
3864 for (i = 0; i < num_vectors; i++)
3866 bufs[i].buf = (char *)vectors[i].buffer;
3867 bufs[i].len = (gulong)vectors[i].size;
3871 addrlen = 0; /* Avoid warning */
3874 addrlen = g_socket_address_get_native_size (address);
3875 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3881 if (socket->priv->blocking &&
3882 !g_socket_condition_wait (socket,
3883 G_IO_OUT, cancellable, error))
3887 result = WSASendTo (socket->priv->fd,
3890 (const struct sockaddr *)&addr, addrlen,
3893 result = WSASend (socket->priv->fd,
3900 int errsv = get_socket_errno ();
3902 if (errsv == WSAEINTR)
3905 if (errsv == WSAEWOULDBLOCK)
3906 win32_unset_event_mask (socket, FD_WRITE);
3908 if (socket->priv->blocking &&
3909 errsv == WSAEWOULDBLOCK)
3912 g_set_error (error, G_IO_ERROR,
3913 socket_io_error_from_errno (errsv),
3914 _("Error sending message: %s"), socket_strerror (errsv));
3926 static GSocketAddress *
3927 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
3929 GSocketAddress *saddr;
3931 guint64 oldest_time = G_MAXUINT64;
3932 gint oldest_index = 0;
3934 if (native_len <= 0)
3938 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
3940 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
3941 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
3942 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
3947 if (tmp_native_len != native_len)
3950 if (memcmp (tmp_native, native, native_len) == 0)
3952 saddr = g_object_ref (tmp);
3953 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
3957 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
3959 oldest_time = socket->priv->recv_addr_cache[i].last_used;
3964 saddr = g_socket_address_new_from_native (native, native_len);
3966 if (socket->priv->recv_addr_cache[oldest_index].addr)
3968 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
3969 g_free (socket->priv->recv_addr_cache[oldest_index].native);
3972 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
3973 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
3974 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
3975 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
3981 * g_socket_receive_message:
3982 * @socket: a #GSocket
3983 * @address: (out) (allow-none): a pointer to a #GSocketAddress
3985 * @vectors: (array length=num_vectors): an array of #GInputVector structs
3986 * @num_vectors: the number of elements in @vectors, or -1
3987 * @messages: (array length=num_messages) (allow-none): a pointer which
3988 * may be filled with an array of #GSocketControlMessages, or %NULL
3989 * @num_messages: a pointer which will be filled with the number of
3990 * elements in @messages, or %NULL
3991 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3992 * @cancellable: (allow-none): a %GCancellable or %NULL
3993 * @error: a #GError pointer, or %NULL
3995 * Receive data from a socket. This is the most complicated and
3996 * fully-featured version of this call. For easier use, see
3997 * g_socket_receive() and g_socket_receive_from().
3999 * If @address is non-%NULL then @address will be set equal to the
4000 * source address of the received packet.
4001 * @address is owned by the caller.
4003 * @vector must point to an array of #GInputVector structs and
4004 * @num_vectors must be the length of this array. These structs
4005 * describe the buffers that received data will be scattered into.
4006 * If @num_vectors is -1, then @vectors is assumed to be terminated
4007 * by a #GInputVector with a %NULL buffer pointer.
4009 * As a special case, if @num_vectors is 0 (in which case, @vectors
4010 * may of course be %NULL), then a single byte is received and
4011 * discarded. This is to facilitate the common practice of sending a
4012 * single '\0' byte for the purposes of transferring ancillary data.
4014 * @messages, if non-%NULL, will be set to point to a newly-allocated
4015 * array of #GSocketControlMessage instances or %NULL if no such
4016 * messages was received. These correspond to the control messages
4017 * received from the kernel, one #GSocketControlMessage per message
4018 * from the kernel. This array is %NULL-terminated and must be freed
4019 * by the caller using g_free() after calling g_object_unref() on each
4020 * element. If @messages is %NULL, any control messages received will
4023 * @num_messages, if non-%NULL, will be set to the number of control
4024 * messages received.
4026 * If both @messages and @num_messages are non-%NULL, then
4027 * @num_messages gives the number of #GSocketControlMessage instances
4028 * in @messages (ie: not including the %NULL terminator).
4030 * @flags is an in/out parameter. The commonly available arguments
4031 * for this are available in the #GSocketMsgFlags enum, but the
4032 * values there are the same as the system values, and the flags
4033 * are passed in as-is, so you can pass in system-specific flags too
4034 * (and g_socket_receive_message() may pass system-specific flags out).
4036 * As with g_socket_receive(), data may be discarded if @socket is
4037 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
4038 * provide enough buffer space to read a complete message. You can pass
4039 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
4040 * removing it from the receive queue, but there is no portable way to find
4041 * out the length of the message other than by reading it into a
4042 * sufficiently-large buffer.
4044 * If the socket is in blocking mode the call will block until there
4045 * is some data to receive, the connection is closed, or there is an
4046 * error. If there is no data available and the socket is in
4047 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
4048 * returned. To be notified when data is available, wait for the
4049 * %G_IO_IN condition.
4051 * On error -1 is returned and @error is set accordingly.
4053 * Returns: Number of bytes read, or 0 if the connection was closed by
4054 * the peer, or -1 on error
4059 g_socket_receive_message (GSocket *socket,
4060 GSocketAddress **address,
4061 GInputVector *vectors,
4063 GSocketControlMessage ***messages,
4066 GCancellable *cancellable,
4069 GInputVector one_vector;
4072 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4074 if (!check_socket (socket, error))
4077 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4080 if (num_vectors == -1)
4082 for (num_vectors = 0;
4083 vectors[num_vectors].buffer != NULL;
4088 if (num_vectors == 0)
4090 one_vector.buffer = &one_byte;
4091 one_vector.size = 1;
4093 vectors = &one_vector;
4100 struct sockaddr_storage one_sockaddr;
4105 msg.msg_name = &one_sockaddr;
4106 msg.msg_namelen = sizeof (struct sockaddr_storage);
4110 msg.msg_name = NULL;
4111 msg.msg_namelen = 0;
4115 /* this entire expression will be evaluated at compile time */
4116 if (sizeof *msg.msg_iov == sizeof *vectors &&
4117 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4118 G_STRUCT_OFFSET (struct iovec, iov_base) ==
4119 G_STRUCT_OFFSET (GInputVector, buffer) &&
4120 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4121 G_STRUCT_OFFSET (struct iovec, iov_len) ==
4122 G_STRUCT_OFFSET (GInputVector, size))
4123 /* ABI is compatible */
4125 msg.msg_iov = (struct iovec *) vectors;
4126 msg.msg_iovlen = num_vectors;
4129 /* ABI is incompatible */
4133 msg.msg_iov = g_newa (struct iovec, num_vectors);
4134 for (i = 0; i < num_vectors; i++)
4136 msg.msg_iov[i].iov_base = vectors[i].buffer;
4137 msg.msg_iov[i].iov_len = vectors[i].size;
4139 msg.msg_iovlen = num_vectors;
4143 msg.msg_control = g_alloca (2048);
4144 msg.msg_controllen = 2048;
4148 msg.msg_flags = *flags;
4152 /* We always set the close-on-exec flag so we don't leak file
4153 * descriptors into child processes. Note that gunixfdmessage.c
4154 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4156 #ifdef MSG_CMSG_CLOEXEC
4157 msg.msg_flags |= MSG_CMSG_CLOEXEC;
4163 if (socket->priv->blocking &&
4164 !g_socket_condition_wait (socket,
4165 G_IO_IN, cancellable, error))
4168 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4169 #ifdef MSG_CMSG_CLOEXEC
4170 if (result < 0 && get_socket_errno () == EINVAL)
4172 /* We must be running on an old kernel. Call without the flag. */
4173 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4174 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4180 int errsv = get_socket_errno ();
4185 if (socket->priv->blocking &&
4186 (errsv == EWOULDBLOCK ||
4190 g_set_error (error, G_IO_ERROR,
4191 socket_io_error_from_errno (errsv),
4192 _("Error receiving message: %s"), socket_strerror (errsv));
4199 /* decode address */
4200 if (address != NULL)
4202 *address = cache_recv_address (socket, msg.msg_name, msg.msg_namelen);
4205 /* decode control messages */
4207 GPtrArray *my_messages = NULL;
4208 struct cmsghdr *cmsg;
4210 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4212 GSocketControlMessage *message;
4214 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4216 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4218 if (message == NULL)
4219 /* We've already spewed about the problem in the
4220 deserialization code, so just continue */
4223 if (messages == NULL)
4225 /* we have to do it this way if the user ignores the
4226 * messages so that we will close any received fds.
4228 g_object_unref (message);
4232 if (my_messages == NULL)
4233 my_messages = g_ptr_array_new ();
4234 g_ptr_array_add (my_messages, message);
4239 *num_messages = my_messages != NULL ? my_messages->len : 0;
4243 if (my_messages == NULL)
4249 g_ptr_array_add (my_messages, NULL);
4250 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4255 g_assert (my_messages == NULL);
4259 /* capture the flags */
4261 *flags = msg.msg_flags;
4267 struct sockaddr_storage addr;
4269 DWORD bytes_received;
4276 bufs = g_newa (WSABUF, num_vectors);
4277 for (i = 0; i < num_vectors; i++)
4279 bufs[i].buf = (char *)vectors[i].buffer;
4280 bufs[i].len = (gulong)vectors[i].size;
4292 if (socket->priv->blocking &&
4293 !g_socket_condition_wait (socket,
4294 G_IO_IN, cancellable, error))
4297 addrlen = sizeof addr;
4299 result = WSARecvFrom (socket->priv->fd,
4301 &bytes_received, &win_flags,
4302 (struct sockaddr *)&addr, &addrlen,
4305 result = WSARecv (socket->priv->fd,
4307 &bytes_received, &win_flags,
4311 int errsv = get_socket_errno ();
4313 if (errsv == WSAEINTR)
4316 win32_unset_event_mask (socket, FD_READ);
4318 if (socket->priv->blocking &&
4319 errsv == WSAEWOULDBLOCK)
4322 g_set_error (error, G_IO_ERROR,
4323 socket_io_error_from_errno (errsv),
4324 _("Error receiving message: %s"), socket_strerror (errsv));
4328 win32_unset_event_mask (socket, FD_READ);
4332 /* decode address */
4333 if (address != NULL)
4335 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
4338 /* capture the flags */
4342 if (messages != NULL)
4344 if (num_messages != NULL)
4347 return bytes_received;
4353 * g_socket_get_credentials:
4354 * @socket: a #GSocket.
4355 * @error: #GError for error reporting, or %NULL to ignore.
4357 * Returns the credentials of the foreign process connected to this
4358 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4361 * If this operation isn't supported on the OS, the method fails with
4362 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4363 * by reading the %SO_PEERCRED option on the underlying socket.
4365 * Other ways to obtain credentials from a foreign peer includes the
4366 * #GUnixCredentialsMessage type and
4367 * g_unix_connection_send_credentials() /
4368 * g_unix_connection_receive_credentials() functions.
4370 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4371 * that must be freed with g_object_unref().
4376 g_socket_get_credentials (GSocket *socket,
4381 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4382 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4386 #if defined(__linux__) || defined(__OpenBSD__)
4389 #if defined(__linux__)
4390 struct ucred native_creds;
4391 optlen = sizeof (struct ucred);
4392 #elif defined(__OpenBSD__)
4393 struct sockpeercred native_creds;
4394 optlen = sizeof (struct sockpeercred);
4396 if (getsockopt (socket->priv->fd,
4399 (void *)&native_creds,
4402 int errsv = get_socket_errno ();
4405 socket_io_error_from_errno (errsv),
4406 _("Unable to get pending error: %s"),
4407 socket_strerror (errsv));
4411 ret = g_credentials_new ();
4412 g_credentials_set_native (ret,
4413 #if defined(__linux__)
4414 G_CREDENTIALS_TYPE_LINUX_UCRED,
4415 #elif defined(__OpenBSD__)
4416 G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
4422 g_set_error_literal (error,
4424 G_IO_ERROR_NOT_SUPPORTED,
4425 _("g_socket_get_credentials not implemented for this OS"));