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 "gnetworking.h"
63 #include "gsocketaddress.h"
64 #include "gsocketcontrolmessage.h"
65 #include "gcredentials.h"
70 * @short_description: Low-level socket object
72 * @see_also: #GInitable, <link linkend="gio-gnetworking.h">gnetworking.h</link>
74 * A #GSocket is a low-level networking primitive. It is a more or less
75 * direct mapping of the BSD socket API in a portable GObject based API.
76 * It supports both the UNIX socket implementations and winsock2 on Windows.
78 * #GSocket is the platform independent base upon which the higher level
79 * network primitives are based. Applications are not typically meant to
80 * use it directly, but rather through classes like #GSocketClient,
81 * #GSocketService and #GSocketConnection. However there may be cases where
82 * direct use of #GSocket is useful.
84 * #GSocket implements the #GInitable interface, so if it is manually constructed
85 * by e.g. g_object_new() you must call g_initable_init() and check the
86 * results before using the object. This is done automatically in
87 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
90 * Sockets operate in two general modes, blocking or non-blocking. When
91 * in blocking mode all operations block until the requested operation
92 * is finished or there is an error. In non-blocking mode all calls that
93 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
94 * To know when a call would successfully run you can call g_socket_condition_check(),
95 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
96 * attach it to a #GMainContext to get callbacks when I/O is possible.
97 * Note that all sockets are always set to non blocking mode in the system, and
98 * blocking mode is emulated in GSocket.
100 * When working in non-blocking mode applications should always be able to
101 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
102 * function said that I/O was possible. This can easily happen in case
103 * of a race condition in the application, but it can also happen for other
104 * reasons. For instance, on Windows a socket is always seen as writable
105 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
107 * #GSocket<!-- -->s can be either connection oriented or datagram based.
108 * For connection oriented types you must first establish a connection by
109 * either connecting to an address or accepting a connection from another
110 * address. For connectionless socket types the target/source address is
111 * specified or received in each I/O operation.
113 * All socket file descriptors are set to be close-on-exec.
115 * Note that creating a #GSocket causes the signal %SIGPIPE to be
116 * ignored for the remainder of the program. If you are writing a
117 * command-line utility that uses #GSocket, you may need to take into
118 * account the fact that your program will not automatically be killed
119 * if it tries to write to %stdout after it has been closed.
124 static void g_socket_initable_iface_init (GInitableIface *iface);
125 static gboolean g_socket_initable_init (GInitable *initable,
126 GCancellable *cancellable,
129 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
130 g_networking_init ();
131 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
132 g_socket_initable_iface_init));
149 PROP_MULTICAST_LOOPBACK,
153 /* Size of the receiver cache for g_socket_receive_from() */
154 #define RECV_ADDR_CACHE_SIZE 8
156 struct _GSocketPrivate
158 GSocketFamily family;
160 GSocketProtocol protocol;
164 GError *construct_error;
165 GSocketAddress *remote_address;
173 guint connect_pending : 1;
179 GList *requested_conditions; /* list of requested GIOCondition * */
183 GSocketAddress *addr;
184 struct sockaddr *native;
187 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
191 get_socket_errno (void)
196 return WSAGetLastError ();
201 socket_io_error_from_errno (int err)
204 return g_io_error_from_errno (err);
209 return G_IO_ERROR_ADDRESS_IN_USE;
211 return G_IO_ERROR_WOULD_BLOCK;
213 return G_IO_ERROR_PERMISSION_DENIED;
214 case WSA_INVALID_HANDLE:
215 case WSA_INVALID_PARAMETER:
218 return G_IO_ERROR_INVALID_ARGUMENT;
219 case WSAEPROTONOSUPPORT:
220 return G_IO_ERROR_NOT_SUPPORTED;
222 return G_IO_ERROR_CANCELLED;
223 case WSAESOCKTNOSUPPORT:
225 case WSAEPFNOSUPPORT:
226 case WSAEAFNOSUPPORT:
227 return G_IO_ERROR_NOT_SUPPORTED;
229 return G_IO_ERROR_FAILED;
235 socket_strerror (int err)
238 return g_strerror (err);
243 msg = g_win32_error_message (err);
245 msg_ret = g_intern_string (msg);
253 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
255 _win32_unset_event_mask (GSocket *socket, int mask)
257 socket->priv->current_events &= ~mask;
258 socket->priv->current_errors &= ~mask;
261 #define win32_unset_event_mask(_socket, _mask)
264 /* Windows has broken prototypes... */
266 #define getsockopt(sockfd, level, optname, optval, optlen) \
267 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
268 #define setsockopt(sockfd, level, optname, optval, optlen) \
269 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
270 #define getsockname(sockfd, addr, addrlen) \
271 getsockname (sockfd, addr, (int *)addrlen)
272 #define getpeername(sockfd, addr, addrlen) \
273 getpeername (sockfd, addr, (int *)addrlen)
274 #define recv(sockfd, buf, len, flags) \
275 recv (sockfd, (gpointer)buf, len, flags)
279 set_fd_nonblocking (int fd)
282 GError *error = NULL;
288 if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
290 g_warning ("Error setting socket nonblocking: %s", error->message);
291 g_clear_error (&error);
296 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
298 int errsv = get_socket_errno ();
299 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
305 check_socket (GSocket *socket,
308 if (!socket->priv->inited)
310 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
311 _("Invalid socket, not initialized"));
315 if (socket->priv->construct_error)
317 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
318 _("Invalid socket, initialization failed due to: %s"),
319 socket->priv->construct_error->message);
323 if (socket->priv->closed)
325 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
326 _("Socket is already closed"));
330 if (socket->priv->timed_out)
332 socket->priv->timed_out = FALSE;
333 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
334 _("Socket I/O timed out"));
342 g_socket_details_from_fd (GSocket *socket)
344 struct sockaddr_storage address;
351 /* See bug #611756 */
352 BOOL bool_val = FALSE;
357 fd = socket->priv->fd;
358 optlen = sizeof value;
359 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
361 errsv = get_socket_errno ();
373 /* programmer error */
374 g_error ("creating GSocket from fd %d: %s\n",
375 fd, socket_strerror (errsv));
383 g_assert (optlen == sizeof value);
387 socket->priv->type = G_SOCKET_TYPE_STREAM;
391 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
395 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
399 socket->priv->type = G_SOCKET_TYPE_INVALID;
403 addrlen = sizeof address;
404 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
406 errsv = get_socket_errno ();
412 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
413 sizeof address.ss_family <= addrlen);
414 family = address.ss_family;
418 /* On Solaris, this happens if the socket is not yet connected.
419 * But we can use SO_DOMAIN as a workaround there.
422 optlen = sizeof family;
423 if (getsockopt (fd, SOL_SOCKET, SO_DOMAIN, (void *)&family, &optlen) != 0)
425 errsv = get_socket_errno ();
429 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
437 case G_SOCKET_FAMILY_IPV4:
438 case G_SOCKET_FAMILY_IPV6:
439 socket->priv->family = address.ss_family;
440 switch (socket->priv->type)
442 case G_SOCKET_TYPE_STREAM:
443 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
446 case G_SOCKET_TYPE_DATAGRAM:
447 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
450 case G_SOCKET_TYPE_SEQPACKET:
451 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
459 case G_SOCKET_FAMILY_UNIX:
460 socket->priv->family = G_SOCKET_FAMILY_UNIX;
461 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
465 socket->priv->family = G_SOCKET_FAMILY_INVALID;
469 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
471 addrlen = sizeof address;
472 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
473 socket->priv->connected = TRUE;
476 optlen = sizeof bool_val;
477 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
478 (void *)&bool_val, &optlen) == 0)
481 /* Experimentation indicates that the SO_KEEPALIVE value is
482 * actually a char on Windows, even if documentation claims it
483 * to be a BOOL which is a typedef for int. So this g_assert()
484 * fails. See bug #611756.
486 g_assert (optlen == sizeof bool_val);
488 socket->priv->keepalive = !!bool_val;
492 /* Can't read, maybe not supported, assume FALSE */
493 socket->priv->keepalive = FALSE;
499 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
500 socket_io_error_from_errno (errsv),
501 _("creating GSocket from fd: %s"),
502 socket_strerror (errsv));
506 g_socket_create_socket (GSocketFamily family,
516 case G_SOCKET_TYPE_STREAM:
517 native_type = SOCK_STREAM;
520 case G_SOCKET_TYPE_DATAGRAM:
521 native_type = SOCK_DGRAM;
524 case G_SOCKET_TYPE_SEQPACKET:
525 native_type = SOCK_SEQPACKET;
529 g_assert_not_reached ();
534 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
535 _("Unable to create socket: %s"), _("Unknown family was specified"));
541 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
542 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
547 fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
548 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
549 if (fd < 0 && errno == EINVAL)
551 fd = socket (family, native_type, protocol);
555 int errsv = get_socket_errno ();
557 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
558 _("Unable to create socket: %s"), socket_strerror (errsv));
565 /* We always want to set close-on-exec to protect users. If you
566 need to so some weird inheritance to exec you can re-enable this
567 using lower level hacks with g_socket_get_fd(). */
568 flags = fcntl (fd, F_GETFD, 0);
570 (flags & FD_CLOEXEC) == 0)
573 fcntl (fd, F_SETFD, flags);
582 g_socket_constructed (GObject *object)
584 GSocket *socket = G_SOCKET (object);
586 if (socket->priv->fd >= 0)
587 /* create socket->priv info from the fd */
588 g_socket_details_from_fd (socket);
591 /* create the fd from socket->priv info */
592 socket->priv->fd = g_socket_create_socket (socket->priv->family,
594 socket->priv->protocol,
595 &socket->priv->construct_error);
597 /* Always use native nonblocking sockets, as
598 windows sets sockets to nonblocking automatically
599 in certain operations. This way we make things work
600 the same on all platforms */
601 if (socket->priv->fd != -1)
602 set_fd_nonblocking (socket->priv->fd);
606 g_socket_get_property (GObject *object,
611 GSocket *socket = G_SOCKET (object);
612 GSocketAddress *address;
617 g_value_set_enum (value, socket->priv->family);
621 g_value_set_enum (value, socket->priv->type);
625 g_value_set_enum (value, socket->priv->protocol);
629 g_value_set_int (value, socket->priv->fd);
633 g_value_set_boolean (value, socket->priv->blocking);
636 case PROP_LISTEN_BACKLOG:
637 g_value_set_int (value, socket->priv->listen_backlog);
641 g_value_set_boolean (value, socket->priv->keepalive);
644 case PROP_LOCAL_ADDRESS:
645 address = g_socket_get_local_address (socket, NULL);
646 g_value_take_object (value, address);
649 case PROP_REMOTE_ADDRESS:
650 address = g_socket_get_remote_address (socket, NULL);
651 g_value_take_object (value, address);
655 g_value_set_uint (value, socket->priv->timeout);
659 g_value_set_uint (value, g_socket_get_ttl (socket));
663 g_value_set_boolean (value, g_socket_get_broadcast (socket));
666 case PROP_MULTICAST_LOOPBACK:
667 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
670 case PROP_MULTICAST_TTL:
671 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
675 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
680 g_socket_set_property (GObject *object,
685 GSocket *socket = G_SOCKET (object);
690 socket->priv->family = g_value_get_enum (value);
694 socket->priv->type = g_value_get_enum (value);
698 socket->priv->protocol = g_value_get_enum (value);
702 socket->priv->fd = g_value_get_int (value);
706 g_socket_set_blocking (socket, g_value_get_boolean (value));
709 case PROP_LISTEN_BACKLOG:
710 g_socket_set_listen_backlog (socket, g_value_get_int (value));
714 g_socket_set_keepalive (socket, g_value_get_boolean (value));
718 g_socket_set_timeout (socket, g_value_get_uint (value));
722 g_socket_set_ttl (socket, g_value_get_uint (value));
726 g_socket_set_broadcast (socket, g_value_get_boolean (value));
729 case PROP_MULTICAST_LOOPBACK:
730 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
733 case PROP_MULTICAST_TTL:
734 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
738 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
743 g_socket_finalize (GObject *object)
745 GSocket *socket = G_SOCKET (object);
748 g_clear_error (&socket->priv->construct_error);
750 if (socket->priv->fd != -1 &&
751 !socket->priv->closed)
752 g_socket_close (socket, NULL);
754 if (socket->priv->remote_address)
755 g_object_unref (socket->priv->remote_address);
758 if (socket->priv->event != WSA_INVALID_EVENT)
760 WSACloseEvent (socket->priv->event);
761 socket->priv->event = WSA_INVALID_EVENT;
764 g_assert (socket->priv->requested_conditions == NULL);
767 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
769 if (socket->priv->recv_addr_cache[i].addr)
771 g_object_unref (socket->priv->recv_addr_cache[i].addr);
772 g_free (socket->priv->recv_addr_cache[i].native);
776 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
777 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
781 g_socket_class_init (GSocketClass *klass)
783 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
786 /* There is no portable, thread-safe way to avoid having the process
787 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
788 * forced to simply ignore the signal process-wide.
790 signal (SIGPIPE, SIG_IGN);
793 g_type_class_add_private (klass, sizeof (GSocketPrivate));
795 gobject_class->finalize = g_socket_finalize;
796 gobject_class->constructed = g_socket_constructed;
797 gobject_class->set_property = g_socket_set_property;
798 gobject_class->get_property = g_socket_get_property;
800 g_object_class_install_property (gobject_class, PROP_FAMILY,
801 g_param_spec_enum ("family",
803 P_("The sockets address family"),
804 G_TYPE_SOCKET_FAMILY,
805 G_SOCKET_FAMILY_INVALID,
806 G_PARAM_CONSTRUCT_ONLY |
808 G_PARAM_STATIC_STRINGS));
810 g_object_class_install_property (gobject_class, PROP_TYPE,
811 g_param_spec_enum ("type",
813 P_("The sockets type"),
815 G_SOCKET_TYPE_STREAM,
816 G_PARAM_CONSTRUCT_ONLY |
818 G_PARAM_STATIC_STRINGS));
820 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
821 g_param_spec_enum ("protocol",
822 P_("Socket protocol"),
823 P_("The id of the protocol to use, or -1 for unknown"),
824 G_TYPE_SOCKET_PROTOCOL,
825 G_SOCKET_PROTOCOL_UNKNOWN,
826 G_PARAM_CONSTRUCT_ONLY |
828 G_PARAM_STATIC_STRINGS));
830 g_object_class_install_property (gobject_class, PROP_FD,
831 g_param_spec_int ("fd",
832 P_("File descriptor"),
833 P_("The sockets file descriptor"),
837 G_PARAM_CONSTRUCT_ONLY |
839 G_PARAM_STATIC_STRINGS));
841 g_object_class_install_property (gobject_class, PROP_BLOCKING,
842 g_param_spec_boolean ("blocking",
844 P_("Whether or not I/O on this socket is blocking"),
847 G_PARAM_STATIC_STRINGS));
849 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
850 g_param_spec_int ("listen-backlog",
851 P_("Listen backlog"),
852 P_("Outstanding connections in the listen queue"),
857 G_PARAM_STATIC_STRINGS));
859 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
860 g_param_spec_boolean ("keepalive",
861 P_("Keep connection alive"),
862 P_("Keep connection alive by sending periodic pings"),
865 G_PARAM_STATIC_STRINGS));
867 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
868 g_param_spec_object ("local-address",
870 P_("The local address the socket is bound to"),
871 G_TYPE_SOCKET_ADDRESS,
873 G_PARAM_STATIC_STRINGS));
875 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
876 g_param_spec_object ("remote-address",
877 P_("Remote address"),
878 P_("The remote address the socket is connected to"),
879 G_TYPE_SOCKET_ADDRESS,
881 G_PARAM_STATIC_STRINGS));
886 * The timeout in seconds on socket I/O
890 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
891 g_param_spec_uint ("timeout",
893 P_("The timeout in seconds on socket I/O"),
898 G_PARAM_STATIC_STRINGS));
903 * Whether the socket should allow sending to and receiving from broadcast addresses.
907 g_object_class_install_property (gobject_class, PROP_BROADCAST,
908 g_param_spec_boolean ("broadcast",
910 P_("Whether to allow sending to and receiving from broadcast addresses"),
913 G_PARAM_STATIC_STRINGS));
918 * Time-to-live for outgoing unicast packets
922 g_object_class_install_property (gobject_class, PROP_TTL,
923 g_param_spec_uint ("ttl",
925 P_("Time-to-live of outgoing unicast packets"),
928 G_PARAM_STATIC_STRINGS));
931 * GSocket:multicast-loopback:
933 * Whether outgoing multicast packets loop back to the local host.
937 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
938 g_param_spec_boolean ("multicast-loopback",
939 P_("Multicast loopback"),
940 P_("Whether outgoing multicast packets loop back to the local host"),
943 G_PARAM_STATIC_STRINGS));
946 * GSocket:multicast-ttl:
948 * Time-to-live out outgoing multicast packets
952 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
953 g_param_spec_uint ("multicast-ttl",
955 P_("Time-to-live of outgoing multicast packets"),
958 G_PARAM_STATIC_STRINGS));
962 g_socket_initable_iface_init (GInitableIface *iface)
964 iface->init = g_socket_initable_init;
968 g_socket_init (GSocket *socket)
970 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
972 socket->priv->fd = -1;
973 socket->priv->blocking = TRUE;
974 socket->priv->listen_backlog = 10;
975 socket->priv->construct_error = NULL;
977 socket->priv->event = WSA_INVALID_EVENT;
982 g_socket_initable_init (GInitable *initable,
983 GCancellable *cancellable,
988 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
990 socket = G_SOCKET (initable);
992 if (cancellable != NULL)
994 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
995 _("Cancellable initialization not supported"));
999 socket->priv->inited = TRUE;
1001 if (socket->priv->construct_error)
1004 *error = g_error_copy (socket->priv->construct_error);
1014 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1015 * @type: the socket type to use.
1016 * @protocol: the id of the protocol to use, or 0 for default.
1017 * @error: #GError for error reporting, or %NULL to ignore.
1019 * Creates a new #GSocket with the defined family, type and protocol.
1020 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1021 * for the family and type is used.
1023 * The @protocol is a family and type specific int that specifies what
1024 * kind of protocol to use. #GSocketProtocol lists several common ones.
1025 * Many families only support one protocol, and use 0 for this, others
1026 * support several and using 0 means to use the default protocol for
1027 * the family and type.
1029 * The protocol id is passed directly to the operating
1030 * system, so you can use protocols not listed in #GSocketProtocol if you
1031 * know the protocol number used for it.
1033 * Returns: a #GSocket or %NULL on error.
1034 * Free the returned object with g_object_unref().
1039 g_socket_new (GSocketFamily family,
1041 GSocketProtocol protocol,
1044 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1048 "protocol", protocol,
1053 * g_socket_new_from_fd:
1054 * @fd: a native socket file descriptor.
1055 * @error: #GError for error reporting, or %NULL to ignore.
1057 * Creates a new #GSocket from a native file descriptor
1058 * or winsock SOCKET handle.
1060 * This reads all the settings from the file descriptor so that
1061 * all properties should work. Note that the file descriptor
1062 * will be set to non-blocking mode, independent on the blocking
1063 * mode of the #GSocket.
1065 * Returns: a #GSocket or %NULL on error.
1066 * Free the returned object with g_object_unref().
1071 g_socket_new_from_fd (gint fd,
1074 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1081 * g_socket_set_blocking:
1082 * @socket: a #GSocket.
1083 * @blocking: Whether to use blocking I/O or not.
1085 * Sets the blocking mode of the socket. In blocking mode
1086 * all operations block until they succeed or there is an error. In
1087 * non-blocking mode all functions return results immediately or
1088 * with a %G_IO_ERROR_WOULD_BLOCK error.
1090 * All sockets are created in blocking mode. However, note that the
1091 * platform level socket is always non-blocking, and blocking mode
1092 * is a GSocket level feature.
1097 g_socket_set_blocking (GSocket *socket,
1100 g_return_if_fail (G_IS_SOCKET (socket));
1102 blocking = !!blocking;
1104 if (socket->priv->blocking == blocking)
1107 socket->priv->blocking = blocking;
1108 g_object_notify (G_OBJECT (socket), "blocking");
1112 * g_socket_get_blocking:
1113 * @socket: a #GSocket.
1115 * Gets the blocking mode of the socket. For details on blocking I/O,
1116 * see g_socket_set_blocking().
1118 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1123 g_socket_get_blocking (GSocket *socket)
1125 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1127 return socket->priv->blocking;
1131 * g_socket_set_keepalive:
1132 * @socket: a #GSocket.
1133 * @keepalive: Value for the keepalive flag
1135 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1136 * this flag is set on a socket, the system will attempt to verify that the
1137 * remote socket endpoint is still present if a sufficiently long period of
1138 * time passes with no data being exchanged. If the system is unable to
1139 * verify the presence of the remote endpoint, it will automatically close
1142 * This option is only functional on certain kinds of sockets. (Notably,
1143 * %G_SOCKET_PROTOCOL_TCP sockets.)
1145 * The exact time between pings is system- and protocol-dependent, but will
1146 * normally be at least two hours. Most commonly, you would set this flag
1147 * on a server socket if you want to allow clients to remain idle for long
1148 * periods of time, but also want to ensure that connections are eventually
1149 * garbage-collected if clients crash or become unreachable.
1154 g_socket_set_keepalive (GSocket *socket,
1159 g_return_if_fail (G_IS_SOCKET (socket));
1161 keepalive = !!keepalive;
1162 if (socket->priv->keepalive == keepalive)
1165 value = (gint) keepalive;
1166 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1167 (gpointer) &value, sizeof (value)) < 0)
1169 int errsv = get_socket_errno ();
1170 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1174 socket->priv->keepalive = keepalive;
1175 g_object_notify (G_OBJECT (socket), "keepalive");
1179 * g_socket_get_keepalive:
1180 * @socket: a #GSocket.
1182 * Gets the keepalive mode of the socket. For details on this,
1183 * see g_socket_set_keepalive().
1185 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1190 g_socket_get_keepalive (GSocket *socket)
1192 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1194 return socket->priv->keepalive;
1198 * g_socket_get_listen_backlog:
1199 * @socket: a #GSocket.
1201 * Gets the listen backlog setting of the socket. For details on this,
1202 * see g_socket_set_listen_backlog().
1204 * Returns: the maximum number of pending connections.
1209 g_socket_get_listen_backlog (GSocket *socket)
1211 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1213 return socket->priv->listen_backlog;
1217 * g_socket_set_listen_backlog:
1218 * @socket: a #GSocket.
1219 * @backlog: the maximum number of pending connections.
1221 * Sets the maximum number of outstanding connections allowed
1222 * when listening on this socket. If more clients than this are
1223 * connecting to the socket and the application is not handling them
1224 * on time then the new connections will be refused.
1226 * Note that this must be called before g_socket_listen() and has no
1227 * effect if called after that.
1232 g_socket_set_listen_backlog (GSocket *socket,
1235 g_return_if_fail (G_IS_SOCKET (socket));
1236 g_return_if_fail (!socket->priv->listening);
1238 if (backlog != socket->priv->listen_backlog)
1240 socket->priv->listen_backlog = backlog;
1241 g_object_notify (G_OBJECT (socket), "listen-backlog");
1246 * g_socket_get_timeout:
1247 * @socket: a #GSocket.
1249 * Gets the timeout setting of the socket. For details on this, see
1250 * g_socket_set_timeout().
1252 * Returns: the timeout in seconds
1257 g_socket_get_timeout (GSocket *socket)
1259 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1261 return socket->priv->timeout;
1265 * g_socket_set_timeout:
1266 * @socket: a #GSocket.
1267 * @timeout: the timeout for @socket, in seconds, or 0 for none
1269 * Sets the time in seconds after which I/O operations on @socket will
1270 * time out if they have not yet completed.
1272 * On a blocking socket, this means that any blocking #GSocket
1273 * operation will time out after @timeout seconds of inactivity,
1274 * returning %G_IO_ERROR_TIMED_OUT.
1276 * On a non-blocking socket, calls to g_socket_condition_wait() will
1277 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1278 * created with g_socket_create_source() will trigger after
1279 * @timeout seconds of inactivity, with the requested condition
1280 * set, at which point calling g_socket_receive(), g_socket_send(),
1281 * g_socket_check_connect_result(), etc, will fail with
1282 * %G_IO_ERROR_TIMED_OUT.
1284 * If @timeout is 0 (the default), operations will never time out
1287 * Note that if an I/O operation is interrupted by a signal, this may
1288 * cause the timeout to be reset.
1293 g_socket_set_timeout (GSocket *socket,
1296 g_return_if_fail (G_IS_SOCKET (socket));
1298 if (timeout != socket->priv->timeout)
1300 socket->priv->timeout = timeout;
1301 g_object_notify (G_OBJECT (socket), "timeout");
1307 * @socket: a #GSocket.
1309 * Gets the unicast time-to-live setting on @socket; see
1310 * g_socket_set_ttl() for more details.
1312 * Returns: the time-to-live setting on @socket
1317 g_socket_get_ttl (GSocket *socket)
1320 guint value, optlen;
1322 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1324 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1328 optlen = sizeof (optval);
1329 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_TTL,
1333 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1335 optlen = sizeof (value);
1336 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1340 g_return_val_if_reached (FALSE);
1344 int errsv = get_socket_errno ();
1345 g_warning ("error getting unicast ttl: %s", socket_strerror (errsv));
1354 * @socket: a #GSocket.
1355 * @ttl: the time-to-live value for all unicast packets on @socket
1357 * Sets the time-to-live for outgoing unicast packets on @socket.
1358 * By default the platform-specific default value is used.
1363 g_socket_set_ttl (GSocket *socket,
1368 g_return_if_fail (G_IS_SOCKET (socket));
1370 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1372 guchar optval = (guchar)ttl;
1374 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_TTL,
1375 &optval, sizeof (optval));
1377 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1379 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1380 &ttl, sizeof (ttl));
1383 g_return_if_reached ();
1387 int errsv = get_socket_errno ();
1388 g_warning ("error setting unicast ttl: %s", socket_strerror (errsv));
1392 g_object_notify (G_OBJECT (socket), "ttl");
1396 * g_socket_get_broadcast:
1397 * @socket: a #GSocket.
1399 * Gets the broadcast setting on @socket; if %TRUE,
1400 * it is possible to send packets to broadcast
1401 * addresses or receive from broadcast addresses.
1403 * Returns: the broadcast setting on @socket
1408 g_socket_get_broadcast (GSocket *socket)
1411 guint value = 0, optlen;
1413 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1415 optlen = sizeof (guchar);
1416 result = getsockopt (socket->priv->fd, SOL_SOCKET, SO_BROADCAST,
1421 int errsv = get_socket_errno ();
1422 g_warning ("error getting broadcast: %s", socket_strerror (errsv));
1430 * g_socket_set_broadcast:
1431 * @socket: a #GSocket.
1432 * @broadcast: whether @socket should allow sending to and receiving
1433 * from broadcast addresses
1435 * Sets whether @socket should allow sending to and receiving from
1436 * broadcast addresses. This is %FALSE by default.
1441 g_socket_set_broadcast (GSocket *socket,
1447 g_return_if_fail (G_IS_SOCKET (socket));
1449 broadcast = !!broadcast;
1450 value = (guchar)broadcast;
1452 result = setsockopt (socket->priv->fd, SOL_SOCKET, SO_BROADCAST,
1453 &value, sizeof (value));
1457 int errsv = get_socket_errno ();
1458 g_warning ("error setting broadcast: %s", socket_strerror (errsv));
1462 g_object_notify (G_OBJECT (socket), "broadcast");
1466 * g_socket_get_multicast_loopback:
1467 * @socket: a #GSocket.
1469 * Gets the multicast loopback setting on @socket; if %TRUE (the
1470 * default), outgoing multicast packets will be looped back to
1471 * multicast listeners on the same host.
1473 * Returns: the multicast loopback setting on @socket
1478 g_socket_get_multicast_loopback (GSocket *socket)
1481 guint value = 0, optlen;
1483 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1485 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1487 optlen = sizeof (guchar);
1488 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1491 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1493 optlen = sizeof (guint);
1494 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1498 g_return_val_if_reached (FALSE);
1502 int errsv = get_socket_errno ();
1503 g_warning ("error getting multicast loopback: %s", socket_strerror (errsv));
1511 * g_socket_set_multicast_loopback:
1512 * @socket: a #GSocket.
1513 * @loopback: whether @socket should receive messages sent to its
1514 * multicast groups from the local host
1516 * Sets whether outgoing multicast packets will be received by sockets
1517 * listening on that multicast address on the same host. This is %TRUE
1523 g_socket_set_multicast_loopback (GSocket *socket,
1528 g_return_if_fail (G_IS_SOCKET (socket));
1530 loopback = !!loopback;
1532 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1534 guchar value = (guchar)loopback;
1536 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1537 &value, sizeof (value));
1539 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1541 guint value = (guint)loopback;
1543 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1544 &value, sizeof (value));
1547 g_return_if_reached ();
1551 int errsv = get_socket_errno ();
1552 g_warning ("error setting multicast loopback: %s", socket_strerror (errsv));
1556 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1560 * g_socket_get_multicast_ttl:
1561 * @socket: a #GSocket.
1563 * Gets the multicast time-to-live setting on @socket; see
1564 * g_socket_set_multicast_ttl() for more details.
1566 * Returns: the multicast time-to-live setting on @socket
1571 g_socket_get_multicast_ttl (GSocket *socket)
1574 guint value, optlen;
1576 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1578 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1582 optlen = sizeof (optval);
1583 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1587 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1589 optlen = sizeof (value);
1590 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1594 g_return_val_if_reached (FALSE);
1598 int errsv = get_socket_errno ();
1599 g_warning ("error getting multicast ttl: %s", socket_strerror (errsv));
1607 * g_socket_set_multicast_ttl:
1608 * @socket: a #GSocket.
1609 * @ttl: the time-to-live value for all multicast datagrams on @socket
1611 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1612 * By default, this is 1, meaning that multicast packets will not leave
1613 * the local network.
1618 g_socket_set_multicast_ttl (GSocket *socket,
1623 g_return_if_fail (G_IS_SOCKET (socket));
1625 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1627 guchar optval = (guchar)ttl;
1629 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1630 &optval, sizeof (optval));
1632 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1634 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1635 &ttl, sizeof (ttl));
1638 g_return_if_reached ();
1642 int errsv = get_socket_errno ();
1643 g_warning ("error setting multicast ttl: %s", socket_strerror (errsv));
1647 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1651 * g_socket_get_family:
1652 * @socket: a #GSocket.
1654 * Gets the socket family of the socket.
1656 * Returns: a #GSocketFamily
1661 g_socket_get_family (GSocket *socket)
1663 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1665 return socket->priv->family;
1669 * g_socket_get_socket_type:
1670 * @socket: a #GSocket.
1672 * Gets the socket type of the socket.
1674 * Returns: a #GSocketType
1679 g_socket_get_socket_type (GSocket *socket)
1681 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1683 return socket->priv->type;
1687 * g_socket_get_protocol:
1688 * @socket: a #GSocket.
1690 * Gets the socket protocol id the socket was created with.
1691 * In case the protocol is unknown, -1 is returned.
1693 * Returns: a protocol id, or -1 if unknown
1698 g_socket_get_protocol (GSocket *socket)
1700 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1702 return socket->priv->protocol;
1707 * @socket: a #GSocket.
1709 * Returns the underlying OS socket object. On unix this
1710 * is a socket file descriptor, and on Windows this is
1711 * a Winsock2 SOCKET handle. This may be useful for
1712 * doing platform specific or otherwise unusual operations
1715 * Returns: the file descriptor of the socket.
1720 g_socket_get_fd (GSocket *socket)
1722 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1724 return socket->priv->fd;
1728 * g_socket_get_local_address:
1729 * @socket: a #GSocket.
1730 * @error: #GError for error reporting, or %NULL to ignore.
1732 * Try to get the local address of a bound socket. This is only
1733 * useful if the socket has been bound to a local address,
1734 * either explicitly or implicitly when connecting.
1736 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1737 * Free the returned object with g_object_unref().
1742 g_socket_get_local_address (GSocket *socket,
1745 struct sockaddr_storage buffer;
1746 guint len = sizeof (buffer);
1748 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1750 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1752 int errsv = get_socket_errno ();
1753 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1754 _("could not get local address: %s"), socket_strerror (errsv));
1758 return g_socket_address_new_from_native (&buffer, len);
1762 * g_socket_get_remote_address:
1763 * @socket: a #GSocket.
1764 * @error: #GError for error reporting, or %NULL to ignore.
1766 * Try to get the remove address of a connected socket. This is only
1767 * useful for connection oriented sockets that have been connected.
1769 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1770 * Free the returned object with g_object_unref().
1775 g_socket_get_remote_address (GSocket *socket,
1778 struct sockaddr_storage buffer;
1779 guint len = sizeof (buffer);
1781 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1783 if (socket->priv->connect_pending)
1785 if (!g_socket_check_connect_result (socket, error))
1788 socket->priv->connect_pending = FALSE;
1791 if (!socket->priv->remote_address)
1793 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1795 int errsv = get_socket_errno ();
1796 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1797 _("could not get remote address: %s"), socket_strerror (errsv));
1801 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1804 return g_object_ref (socket->priv->remote_address);
1808 * g_socket_is_connected:
1809 * @socket: a #GSocket.
1811 * Check whether the socket is connected. This is only useful for
1812 * connection-oriented sockets.
1814 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1819 g_socket_is_connected (GSocket *socket)
1821 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1823 return socket->priv->connected;
1828 * @socket: a #GSocket.
1829 * @error: #GError for error reporting, or %NULL to ignore.
1831 * Marks the socket as a server socket, i.e. a socket that is used
1832 * to accept incoming requests using g_socket_accept().
1834 * Before calling this the socket must be bound to a local address using
1837 * To set the maximum amount of outstanding clients, use
1838 * g_socket_set_listen_backlog().
1840 * Returns: %TRUE on success, %FALSE on error.
1845 g_socket_listen (GSocket *socket,
1848 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1850 if (!check_socket (socket, error))
1853 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1855 int errsv = get_socket_errno ();
1857 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1858 _("could not listen: %s"), socket_strerror (errsv));
1862 socket->priv->listening = TRUE;
1869 * @socket: a #GSocket.
1870 * @address: a #GSocketAddress specifying the local address.
1871 * @allow_reuse: whether to allow reusing this address
1872 * @error: #GError for error reporting, or %NULL to ignore.
1874 * When a socket is created it is attached to an address family, but it
1875 * doesn't have an address in this family. g_socket_bind() assigns the
1876 * address (sometimes called name) of the socket.
1878 * It is generally required to bind to a local address before you can
1879 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1880 * In certain situations, you may also want to bind a socket that will be
1881 * used to initiate connections, though this is not normally required.
1883 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1884 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1885 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1886 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1887 * that address was previously used by another socket that has not yet been
1888 * fully cleaned-up by the kernel. Failing to set this flag on a server
1889 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1890 * the server program is stopped and then immediately restarted.)
1892 * Returns: %TRUE on success, %FALSE on error.
1897 g_socket_bind (GSocket *socket,
1898 GSocketAddress *address,
1899 gboolean reuse_address,
1902 struct sockaddr_storage addr;
1904 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1906 if (!check_socket (socket, error))
1909 /* SO_REUSEADDR on Windows means something else and is not what we want.
1910 It always allows the unix variant of SO_REUSEADDR anyway */
1915 value = (int) !!reuse_address;
1916 /* Ignore errors here, the only likely error is "not supported", and
1917 this is a "best effort" thing mainly */
1918 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1919 (gpointer) &value, sizeof (value));
1923 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1926 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1927 g_socket_address_get_native_size (address)) < 0)
1929 int errsv = get_socket_errno ();
1931 G_IO_ERROR, socket_io_error_from_errno (errsv),
1932 _("Error binding to address: %s"), socket_strerror (errsv));
1940 g_socket_multicast_group_operation (GSocket *socket,
1941 GInetAddress *group,
1942 gboolean source_specific,
1944 gboolean join_group,
1947 const guint8 *native_addr;
1948 gint optname, result;
1950 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1951 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
1952 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
1953 g_return_val_if_fail (g_inet_address_get_family (group) == socket->priv->family, FALSE);
1955 if (!check_socket (socket, error))
1958 native_addr = g_inet_address_to_bytes (group);
1959 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1961 #ifdef HAVE_IP_MREQN
1962 struct ip_mreqn mc_req;
1964 struct ip_mreq mc_req;
1967 memset (&mc_req, 0, sizeof (mc_req));
1968 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
1970 #ifdef HAVE_IP_MREQN
1972 mc_req.imr_ifindex = if_nametoindex (iface);
1974 mc_req.imr_ifindex = 0; /* Pick any. */
1976 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
1979 if (source_specific)
1981 #ifdef IP_ADD_SOURCE_MEMBERSHIP
1982 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
1984 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1986 _("Error joining multicast group: %s") :
1987 _("Error leaving multicast group: %s"),
1988 _("No support for source-specific multicast"));
1993 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
1994 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
1995 &mc_req, sizeof (mc_req));
1997 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1999 struct ipv6_mreq mc_req_ipv6;
2001 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2002 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2003 #ifdef HAVE_IF_NAMETOINDEX
2005 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2008 mc_req_ipv6.ipv6mr_interface = 0;
2010 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2011 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2012 &mc_req_ipv6, sizeof (mc_req_ipv6));
2015 g_return_val_if_reached (FALSE);
2019 int errsv = get_socket_errno ();
2021 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2023 _("Error joining multicast group: %s") :
2024 _("Error leaving multicast group: %s"),
2025 socket_strerror (errsv));
2033 * g_socket_join_multicast_group:
2034 * @socket: a #GSocket.
2035 * @group: a #GInetAddress specifying the group address to join.
2036 * @iface: (allow-none): Name of the interface to use, or %NULL
2037 * @source_specific: %TRUE if source-specific multicast should be used
2038 * @error: #GError for error reporting, or %NULL to ignore.
2040 * Registers @socket to receive multicast messages sent to @group.
2041 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2042 * been bound to an appropriate interface and port with
2045 * If @iface is %NULL, the system will automatically pick an interface
2046 * to bind to based on @group.
2048 * If @source_specific is %TRUE, source-specific multicast as defined
2049 * in RFC 4604 is used. Note that on older platforms this may fail
2050 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2052 * Returns: %TRUE on success, %FALSE on error.
2057 g_socket_join_multicast_group (GSocket *socket,
2058 GInetAddress *group,
2059 gboolean source_specific,
2063 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2067 * g_socket_leave_multicast_group:
2068 * @socket: a #GSocket.
2069 * @group: a #GInetAddress specifying the group address to leave.
2070 * @iface: (allow-none): Interface used
2071 * @source_specific: %TRUE if source-specific multicast was used
2072 * @error: #GError for error reporting, or %NULL to ignore.
2074 * Removes @socket from the multicast group defined by @group, @iface,
2075 * and @source_specific (which must all have the same values they had
2076 * when you joined the group).
2078 * @socket remains bound to its address and port, and can still receive
2079 * unicast messages after calling this.
2081 * Returns: %TRUE on success, %FALSE on error.
2086 g_socket_leave_multicast_group (GSocket *socket,
2087 GInetAddress *group,
2088 gboolean source_specific,
2092 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2096 * g_socket_speaks_ipv4:
2097 * @socket: a #GSocket
2099 * Checks if a socket is capable of speaking IPv4.
2101 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2102 * and under some combinations of circumstances IPv6 sockets are also
2103 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2106 * No other types of sockets are currently considered as being capable
2109 * Returns: %TRUE if this socket can be used with IPv4.
2114 g_socket_speaks_ipv4 (GSocket *socket)
2116 switch (socket->priv->family)
2118 case G_SOCKET_FAMILY_IPV4:
2121 case G_SOCKET_FAMILY_IPV6:
2122 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2124 guint sizeof_int = sizeof (int);
2127 if (getsockopt (socket->priv->fd,
2128 IPPROTO_IPV6, IPV6_V6ONLY,
2129 &v6_only, &sizeof_int) != 0)
2145 * @socket: a #GSocket.
2146 * @cancellable: (allow-none): a %GCancellable or %NULL
2147 * @error: #GError for error reporting, or %NULL to ignore.
2149 * Accept incoming connections on a connection-based socket. This removes
2150 * the first outstanding connection request from the listening socket and
2151 * creates a #GSocket object for it.
2153 * The @socket must be bound to a local address with g_socket_bind() and
2154 * must be listening for incoming connections (g_socket_listen()).
2156 * If there are no outstanding connections then the operation will block
2157 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2158 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2160 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2161 * Free the returned object with g_object_unref().
2166 g_socket_accept (GSocket *socket,
2167 GCancellable *cancellable,
2170 GSocket *new_socket;
2173 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2175 if (!check_socket (socket, error))
2180 if (socket->priv->blocking &&
2181 !g_socket_condition_wait (socket,
2182 G_IO_IN, cancellable, error))
2185 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2187 int errsv = get_socket_errno ();
2189 win32_unset_event_mask (socket, FD_ACCEPT);
2194 if (socket->priv->blocking)
2196 #ifdef WSAEWOULDBLOCK
2197 if (errsv == WSAEWOULDBLOCK)
2200 if (errsv == EWOULDBLOCK ||
2206 g_set_error (error, G_IO_ERROR,
2207 socket_io_error_from_errno (errsv),
2208 _("Error accepting connection: %s"), socket_strerror (errsv));
2214 win32_unset_event_mask (socket, FD_ACCEPT);
2218 /* The socket inherits the accepting sockets event mask and even object,
2219 we need to remove that */
2220 WSAEventSelect (ret, NULL, 0);
2226 /* We always want to set close-on-exec to protect users. If you
2227 need to so some weird inheritance to exec you can re-enable this
2228 using lower level hacks with g_socket_get_fd(). */
2229 flags = fcntl (ret, F_GETFD, 0);
2231 (flags & FD_CLOEXEC) == 0)
2233 flags |= FD_CLOEXEC;
2234 fcntl (ret, F_SETFD, flags);
2239 new_socket = g_socket_new_from_fd (ret, error);
2240 if (new_socket == NULL)
2249 new_socket->priv->protocol = socket->priv->protocol;
2256 * @socket: a #GSocket.
2257 * @address: a #GSocketAddress specifying the remote address.
2258 * @cancellable: (allow-none): a %GCancellable or %NULL
2259 * @error: #GError for error reporting, or %NULL to ignore.
2261 * Connect the socket to the specified remote address.
2263 * For connection oriented socket this generally means we attempt to make
2264 * a connection to the @address. For a connection-less socket it sets
2265 * the default address for g_socket_send() and discards all incoming datagrams
2266 * from other sources.
2268 * Generally connection oriented sockets can only connect once, but
2269 * connection-less sockets can connect multiple times to change the
2272 * If the connect call needs to do network I/O it will block, unless
2273 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2274 * and the user can be notified of the connection finishing by waiting
2275 * for the G_IO_OUT condition. The result of the connection must then be
2276 * checked with g_socket_check_connect_result().
2278 * Returns: %TRUE if connected, %FALSE on error.
2283 g_socket_connect (GSocket *socket,
2284 GSocketAddress *address,
2285 GCancellable *cancellable,
2288 struct sockaddr_storage buffer;
2290 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2292 if (!check_socket (socket, error))
2295 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2298 if (socket->priv->remote_address)
2299 g_object_unref (socket->priv->remote_address);
2300 socket->priv->remote_address = g_object_ref (address);
2304 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2305 g_socket_address_get_native_size (address)) < 0)
2307 int errsv = get_socket_errno ();
2313 if (errsv == EINPROGRESS)
2315 if (errsv == WSAEWOULDBLOCK)
2318 if (socket->priv->blocking)
2320 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2322 if (g_socket_check_connect_result (socket, error))
2328 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2329 _("Connection in progress"));
2330 socket->priv->connect_pending = TRUE;
2334 g_set_error_literal (error, G_IO_ERROR,
2335 socket_io_error_from_errno (errsv),
2336 socket_strerror (errsv));
2343 win32_unset_event_mask (socket, FD_CONNECT);
2345 socket->priv->connected = TRUE;
2351 * g_socket_check_connect_result:
2352 * @socket: a #GSocket
2353 * @error: #GError for error reporting, or %NULL to ignore.
2355 * Checks and resets the pending connect error for the socket.
2356 * This is used to check for errors when g_socket_connect() is
2357 * used in non-blocking mode.
2359 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2364 g_socket_check_connect_result (GSocket *socket,
2370 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2372 if (!check_socket (socket, error))
2375 optlen = sizeof (value);
2376 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
2378 int errsv = get_socket_errno ();
2380 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2381 _("Unable to get pending error: %s"), socket_strerror (errsv));
2387 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2388 socket_strerror (value));
2389 if (socket->priv->remote_address)
2391 g_object_unref (socket->priv->remote_address);
2392 socket->priv->remote_address = NULL;
2397 socket->priv->connected = TRUE;
2402 * g_socket_get_available_bytes:
2403 * @socket: a #GSocket
2405 * Get the amount of data pending in the OS input buffer.
2407 * Returns: the number of bytes that can be read from the socket
2408 * without blocking or -1 on error.
2413 g_socket_get_available_bytes (GSocket *socket)
2417 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2420 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2423 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) == SOCKET_ERROR)
2432 * @socket: a #GSocket
2433 * @buffer: a buffer to read data into (which should be at least @size
2435 * @size: the number of bytes you want to read from the socket
2436 * @cancellable: (allow-none): a %GCancellable or %NULL
2437 * @error: #GError for error reporting, or %NULL to ignore.
2439 * Receive data (up to @size bytes) from a socket. This is mainly used by
2440 * connection-oriented sockets; it is identical to g_socket_receive_from()
2441 * with @address set to %NULL.
2443 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2444 * g_socket_receive() will always read either 0 or 1 complete messages from
2445 * the socket. If the received message is too large to fit in @buffer, then
2446 * the data beyond @size bytes will be discarded, without any explicit
2447 * indication that this has occurred.
2449 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2450 * number of bytes, up to @size. If more than @size bytes have been
2451 * received, the additional data will be returned in future calls to
2452 * g_socket_receive().
2454 * If the socket is in blocking mode the call will block until there
2455 * is some data to receive, the connection is closed, or there is an
2456 * error. If there is no data available and the socket is in
2457 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2458 * returned. To be notified when data is available, wait for the
2459 * %G_IO_IN condition.
2461 * On error -1 is returned and @error is set accordingly.
2463 * Returns: Number of bytes read, or 0 if the connection was closed by
2464 * the peer, or -1 on error
2469 g_socket_receive (GSocket *socket,
2472 GCancellable *cancellable,
2475 return g_socket_receive_with_blocking (socket, buffer, size,
2476 socket->priv->blocking,
2477 cancellable, error);
2481 * g_socket_receive_with_blocking:
2482 * @socket: a #GSocket
2483 * @buffer: a buffer to read data into (which should be at least @size
2485 * @size: the number of bytes you want to read from the socket
2486 * @blocking: whether to do blocking or non-blocking I/O
2487 * @cancellable: (allow-none): a %GCancellable or %NULL
2488 * @error: #GError for error reporting, or %NULL to ignore.
2490 * This behaves exactly the same as g_socket_receive(), except that
2491 * the choice of blocking or non-blocking behavior is determined by
2492 * the @blocking argument rather than by @socket's properties.
2494 * Returns: Number of bytes read, or 0 if the connection was closed by
2495 * the peer, or -1 on error
2500 g_socket_receive_with_blocking (GSocket *socket,
2504 GCancellable *cancellable,
2509 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2511 if (!check_socket (socket, error))
2514 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2520 !g_socket_condition_wait (socket,
2521 G_IO_IN, cancellable, error))
2524 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2526 int errsv = get_socket_errno ();
2533 #ifdef WSAEWOULDBLOCK
2534 if (errsv == WSAEWOULDBLOCK)
2537 if (errsv == EWOULDBLOCK ||
2543 win32_unset_event_mask (socket, FD_READ);
2545 g_set_error (error, G_IO_ERROR,
2546 socket_io_error_from_errno (errsv),
2547 _("Error receiving data: %s"), socket_strerror (errsv));
2551 win32_unset_event_mask (socket, FD_READ);
2560 * g_socket_receive_from:
2561 * @socket: a #GSocket
2562 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2564 * @buffer: (array length=size) (element-type guint8): a buffer to
2565 * read data into (which should be at least @size bytes long).
2566 * @size: the number of bytes you want to read from the socket
2567 * @cancellable: (allow-none): a %GCancellable or %NULL
2568 * @error: #GError for error reporting, or %NULL to ignore.
2570 * Receive data (up to @size bytes) from a socket.
2572 * If @address is non-%NULL then @address will be set equal to the
2573 * source address of the received packet.
2574 * @address is owned by the caller.
2576 * See g_socket_receive() for additional information.
2578 * Returns: Number of bytes read, or 0 if the connection was closed by
2579 * the peer, or -1 on error
2584 g_socket_receive_from (GSocket *socket,
2585 GSocketAddress **address,
2588 GCancellable *cancellable,
2596 return g_socket_receive_message (socket,
2604 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2605 * one, which can be confusing and annoying. So if possible, we want
2606 * to suppress the signal entirely.
2609 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2611 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2616 * @socket: a #GSocket
2617 * @buffer: (array length=size) (element-type guint8): the buffer
2618 * containing the data to send.
2619 * @size: the number of bytes to send
2620 * @cancellable: (allow-none): a %GCancellable or %NULL
2621 * @error: #GError for error reporting, or %NULL to ignore.
2623 * Tries to send @size bytes from @buffer on the socket. This is
2624 * mainly used by connection-oriented sockets; it is identical to
2625 * g_socket_send_to() with @address set to %NULL.
2627 * If the socket is in blocking mode the call will block until there is
2628 * space for the data in the socket queue. If there is no space available
2629 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2630 * will be returned. To be notified when space is available, wait for the
2631 * %G_IO_OUT condition. Note though that you may still receive
2632 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2633 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2634 * very common due to the way the underlying APIs work.)
2636 * On error -1 is returned and @error is set accordingly.
2638 * Returns: Number of bytes written (which may be less than @size), or -1
2644 g_socket_send (GSocket *socket,
2645 const gchar *buffer,
2647 GCancellable *cancellable,
2650 return g_socket_send_with_blocking (socket, buffer, size,
2651 socket->priv->blocking,
2652 cancellable, error);
2656 * g_socket_send_with_blocking:
2657 * @socket: a #GSocket
2658 * @buffer: (array length=size) (element-type guint8): the buffer
2659 * containing the data to send.
2660 * @size: the number of bytes to send
2661 * @blocking: whether to do blocking or non-blocking I/O
2662 * @cancellable: (allow-none): a %GCancellable or %NULL
2663 * @error: #GError for error reporting, or %NULL to ignore.
2665 * This behaves exactly the same as g_socket_send(), except that
2666 * the choice of blocking or non-blocking behavior is determined by
2667 * the @blocking argument rather than by @socket's properties.
2669 * Returns: Number of bytes written (which may be less than @size), or -1
2675 g_socket_send_with_blocking (GSocket *socket,
2676 const gchar *buffer,
2679 GCancellable *cancellable,
2684 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2686 if (!check_socket (socket, error))
2689 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2695 !g_socket_condition_wait (socket,
2696 G_IO_OUT, cancellable, error))
2699 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2701 int errsv = get_socket_errno ();
2706 #ifdef WSAEWOULDBLOCK
2707 if (errsv == WSAEWOULDBLOCK)
2708 win32_unset_event_mask (socket, FD_WRITE);
2713 #ifdef WSAEWOULDBLOCK
2714 if (errsv == WSAEWOULDBLOCK)
2717 if (errsv == EWOULDBLOCK ||
2723 g_set_error (error, G_IO_ERROR,
2724 socket_io_error_from_errno (errsv),
2725 _("Error sending data: %s"), socket_strerror (errsv));
2736 * @socket: a #GSocket
2737 * @address: (allow-none): a #GSocketAddress, or %NULL
2738 * @buffer: (array length=size) (element-type guint8): the buffer
2739 * containing the data to send.
2740 * @size: the number of bytes to send
2741 * @cancellable: (allow-none): a %GCancellable or %NULL
2742 * @error: #GError for error reporting, or %NULL to ignore.
2744 * Tries to send @size bytes from @buffer to @address. If @address is
2745 * %NULL then the message is sent to the default receiver (set by
2746 * g_socket_connect()).
2748 * See g_socket_send() for additional information.
2750 * Returns: Number of bytes written (which may be less than @size), or -1
2756 g_socket_send_to (GSocket *socket,
2757 GSocketAddress *address,
2758 const gchar *buffer,
2760 GCancellable *cancellable,
2768 return g_socket_send_message (socket,
2778 * g_socket_shutdown:
2779 * @socket: a #GSocket
2780 * @shutdown_read: whether to shut down the read side
2781 * @shutdown_write: whether to shut down the write side
2782 * @error: #GError for error reporting, or %NULL to ignore.
2784 * Shut down part of a full-duplex connection.
2786 * If @shutdown_read is %TRUE then the receiving side of the connection
2787 * is shut down, and further reading is disallowed.
2789 * If @shutdown_write is %TRUE then the sending side of the connection
2790 * is shut down, and further writing is disallowed.
2792 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2794 * One example where this is used is graceful disconnect for TCP connections
2795 * where you close the sending side, then wait for the other side to close
2796 * the connection, thus ensuring that the other side saw all sent data.
2798 * Returns: %TRUE on success, %FALSE on error
2803 g_socket_shutdown (GSocket *socket,
2804 gboolean shutdown_read,
2805 gboolean shutdown_write,
2810 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2812 if (!check_socket (socket, error))
2816 if (!shutdown_read && !shutdown_write)
2820 if (shutdown_read && shutdown_write)
2822 else if (shutdown_read)
2827 if (shutdown_read && shutdown_write)
2829 else if (shutdown_read)
2835 if (shutdown (socket->priv->fd, how) != 0)
2837 int errsv = get_socket_errno ();
2838 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2839 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2843 if (shutdown_read && shutdown_write)
2844 socket->priv->connected = FALSE;
2851 * @socket: a #GSocket
2852 * @error: #GError for error reporting, or %NULL to ignore.
2854 * Closes the socket, shutting down any active connection.
2856 * Closing a socket does not wait for all outstanding I/O operations
2857 * to finish, so the caller should not rely on them to be guaranteed
2858 * to complete even if the close returns with no error.
2860 * Once the socket is closed, all other operations will return
2861 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2864 * Sockets will be automatically closed when the last reference
2865 * is dropped, but you might want to call this function to make sure
2866 * resources are released as early as possible.
2868 * Beware that due to the way that TCP works, it is possible for
2869 * recently-sent data to be lost if either you close a socket while the
2870 * %G_IO_IN condition is set, or else if the remote connection tries to
2871 * send something to you after you close the socket but before it has
2872 * finished reading all of the data you sent. There is no easy generic
2873 * way to avoid this problem; the easiest fix is to design the network
2874 * protocol such that the client will never send data "out of turn".
2875 * Another solution is for the server to half-close the connection by
2876 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2877 * and then wait for the client to notice this and close its side of the
2878 * connection, after which the server can safely call g_socket_close().
2879 * (This is what #GTcpConnection does if you call
2880 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2881 * only works if the client will close its connection after the server
2884 * Returns: %TRUE on success, %FALSE on error
2889 g_socket_close (GSocket *socket,
2894 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2896 if (socket->priv->closed)
2897 return TRUE; /* Multiple close not an error */
2899 if (!check_socket (socket, error))
2905 res = closesocket (socket->priv->fd);
2907 res = close (socket->priv->fd);
2911 int errsv = get_socket_errno ();
2916 g_set_error (error, G_IO_ERROR,
2917 socket_io_error_from_errno (errsv),
2918 _("Error closing socket: %s"),
2919 socket_strerror (errsv));
2925 socket->priv->connected = FALSE;
2926 socket->priv->closed = TRUE;
2927 if (socket->priv->remote_address)
2929 g_object_unref (socket->priv->remote_address);
2930 socket->priv->remote_address = NULL;
2937 * g_socket_is_closed:
2938 * @socket: a #GSocket
2940 * Checks whether a socket is closed.
2942 * Returns: %TRUE if socket is closed, %FALSE otherwise
2947 g_socket_is_closed (GSocket *socket)
2949 return socket->priv->closed;
2953 /* Broken source, used on errors */
2955 broken_prepare (GSource *source,
2962 broken_check (GSource *source)
2968 broken_dispatch (GSource *source,
2969 GSourceFunc callback,
2975 static GSourceFuncs broken_funcs =
2984 network_events_for_condition (GIOCondition condition)
2988 if (condition & G_IO_IN)
2989 event_mask |= (FD_READ | FD_ACCEPT);
2990 if (condition & G_IO_OUT)
2991 event_mask |= (FD_WRITE | FD_CONNECT);
2992 event_mask |= FD_CLOSE;
2998 ensure_event (GSocket *socket)
3000 if (socket->priv->event == WSA_INVALID_EVENT)
3001 socket->priv->event = WSACreateEvent();
3005 update_select_events (GSocket *socket)
3012 ensure_event (socket);
3015 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3018 event_mask |= network_events_for_condition (*ptr);
3021 if (event_mask != socket->priv->selected_events)
3023 /* If no events selected, disable event so we can unset
3026 if (event_mask == 0)
3029 event = socket->priv->event;
3031 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3032 socket->priv->selected_events = event_mask;
3037 add_condition_watch (GSocket *socket,
3038 GIOCondition *condition)
3040 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3042 socket->priv->requested_conditions =
3043 g_list_prepend (socket->priv->requested_conditions, condition);
3045 update_select_events (socket);
3049 remove_condition_watch (GSocket *socket,
3050 GIOCondition *condition)
3052 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3054 socket->priv->requested_conditions =
3055 g_list_remove (socket->priv->requested_conditions, condition);
3057 update_select_events (socket);
3061 update_condition (GSocket *socket)
3063 WSANETWORKEVENTS events;
3064 GIOCondition condition;
3066 if (WSAEnumNetworkEvents (socket->priv->fd,
3067 socket->priv->event,
3070 socket->priv->current_events |= events.lNetworkEvents;
3071 if (events.lNetworkEvents & FD_WRITE &&
3072 events.iErrorCode[FD_WRITE_BIT] != 0)
3073 socket->priv->current_errors |= FD_WRITE;
3074 if (events.lNetworkEvents & FD_CONNECT &&
3075 events.iErrorCode[FD_CONNECT_BIT] != 0)
3076 socket->priv->current_errors |= FD_CONNECT;
3080 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3081 condition |= G_IO_IN;
3083 if (socket->priv->current_events & FD_CLOSE)
3085 int r, errsv, buffer;
3087 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3089 errsv = get_socket_errno ();
3092 (r < 0 && errsv == WSAENOTCONN))
3093 condition |= G_IO_IN;
3095 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3096 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3097 condition |= G_IO_HUP;
3099 condition |= G_IO_ERR;
3102 if (socket->priv->closed)
3103 condition |= G_IO_HUP;
3105 /* Never report both G_IO_OUT and HUP, these are
3106 mutually exclusive (can't write to a closed socket) */
3107 if ((condition & G_IO_HUP) == 0 &&
3108 socket->priv->current_events & FD_WRITE)
3110 if (socket->priv->current_errors & FD_WRITE)
3111 condition |= G_IO_ERR;
3113 condition |= G_IO_OUT;
3117 if (socket->priv->current_events & FD_CONNECT)
3119 if (socket->priv->current_errors & FD_CONNECT)
3120 condition |= (G_IO_HUP | G_IO_ERR);
3122 condition |= G_IO_OUT;
3134 GIOCondition condition;
3135 GCancellable *cancellable;
3136 GPollFD cancel_pollfd;
3137 gint64 timeout_time;
3141 socket_source_prepare (GSource *source,
3144 GSocketSource *socket_source = (GSocketSource *)source;
3146 if (g_cancellable_is_cancelled (socket_source->cancellable))
3149 if (socket_source->timeout_time)
3153 now = g_source_get_time (source);
3154 /* Round up to ensure that we don't try again too early */
3155 *timeout = (socket_source->timeout_time - now + 999) / 1000;
3158 socket_source->socket->priv->timed_out = TRUE;
3167 socket_source->pollfd.revents = update_condition (socket_source->socket);
3170 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
3177 socket_source_check (GSource *source)
3181 return socket_source_prepare (source, &timeout);
3185 socket_source_dispatch (GSource *source,
3186 GSourceFunc callback,
3189 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3190 GSocketSource *socket_source = (GSocketSource *)source;
3191 GSocket *socket = socket_source->socket;
3195 socket_source->pollfd.revents = update_condition (socket_source->socket);
3197 if (socket_source->socket->priv->timed_out)
3198 socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
3200 ret = (*func) (socket,
3201 socket_source->pollfd.revents & socket_source->condition,
3204 if (socket->priv->timeout)
3205 socket_source->timeout_time = g_get_monotonic_time () +
3206 socket->priv->timeout * 1000000;
3209 socket_source->timeout_time = 0;
3215 socket_source_finalize (GSource *source)
3217 GSocketSource *socket_source = (GSocketSource *)source;
3220 socket = socket_source->socket;
3223 remove_condition_watch (socket, &socket_source->condition);
3226 g_object_unref (socket);
3228 if (socket_source->cancellable)
3230 g_cancellable_release_fd (socket_source->cancellable);
3231 g_object_unref (socket_source->cancellable);
3236 socket_source_closure_callback (GSocket *socket,
3237 GIOCondition condition,
3240 GClosure *closure = data;
3242 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3243 GValue result_value = G_VALUE_INIT;
3246 g_value_init (&result_value, G_TYPE_BOOLEAN);
3248 g_value_init (¶ms[0], G_TYPE_SOCKET);
3249 g_value_set_object (¶ms[0], socket);
3250 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
3251 g_value_set_flags (¶ms[1], condition);
3253 g_closure_invoke (closure, &result_value, 2, params, NULL);
3255 result = g_value_get_boolean (&result_value);
3256 g_value_unset (&result_value);
3257 g_value_unset (¶ms[0]);
3258 g_value_unset (¶ms[1]);
3263 static GSourceFuncs socket_source_funcs =
3265 socket_source_prepare,
3266 socket_source_check,
3267 socket_source_dispatch,
3268 socket_source_finalize,
3269 (GSourceFunc)socket_source_closure_callback,
3270 (GSourceDummyMarshal)g_cclosure_marshal_generic,
3274 socket_source_new (GSocket *socket,
3275 GIOCondition condition,
3276 GCancellable *cancellable)
3279 GSocketSource *socket_source;
3282 ensure_event (socket);
3284 if (socket->priv->event == WSA_INVALID_EVENT)
3286 g_warning ("Failed to create WSAEvent");
3287 return g_source_new (&broken_funcs, sizeof (GSource));
3291 condition |= G_IO_HUP | G_IO_ERR;
3293 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3294 g_source_set_name (source, "GSocket");
3295 socket_source = (GSocketSource *)source;
3297 socket_source->socket = g_object_ref (socket);
3298 socket_source->condition = condition;
3300 if (g_cancellable_make_pollfd (cancellable,
3301 &socket_source->cancel_pollfd))
3303 socket_source->cancellable = g_object_ref (cancellable);
3304 g_source_add_poll (source, &socket_source->cancel_pollfd);
3308 add_condition_watch (socket, &socket_source->condition);
3309 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3311 socket_source->pollfd.fd = socket->priv->fd;
3314 socket_source->pollfd.events = condition;
3315 socket_source->pollfd.revents = 0;
3316 g_source_add_poll (source, &socket_source->pollfd);
3318 if (socket->priv->timeout)
3319 socket_source->timeout_time = g_get_monotonic_time () +
3320 socket->priv->timeout * 1000000;
3323 socket_source->timeout_time = 0;
3329 * g_socket_create_source: (skip)
3330 * @socket: a #GSocket
3331 * @condition: a #GIOCondition mask to monitor
3332 * @cancellable: (allow-none): a %GCancellable or %NULL
3334 * Creates a %GSource that can be attached to a %GMainContext to monitor
3335 * for the availibility of the specified @condition on the socket.
3337 * The callback on the source is of the #GSocketSourceFunc type.
3339 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3340 * these conditions will always be reported output if they are true.
3342 * @cancellable if not %NULL can be used to cancel the source, which will
3343 * cause the source to trigger, reporting the current condition (which
3344 * is likely 0 unless cancellation happened at the same time as a
3345 * condition change). You can check for this in the callback using
3346 * g_cancellable_is_cancelled().
3348 * If @socket has a timeout set, and it is reached before @condition
3349 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3350 * %G_IO_OUT depending on @condition. However, @socket will have been
3351 * marked as having had a timeout, and so the next #GSocket I/O method
3352 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3354 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3359 g_socket_create_source (GSocket *socket,
3360 GIOCondition condition,
3361 GCancellable *cancellable)
3363 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3365 return socket_source_new (socket, condition, cancellable);
3369 * g_socket_condition_check:
3370 * @socket: a #GSocket
3371 * @condition: a #GIOCondition mask to check
3373 * Checks on the readiness of @socket to perform operations.
3374 * The operations specified in @condition are checked for and masked
3375 * against the currently-satisfied conditions on @socket. The result
3378 * Note that on Windows, it is possible for an operation to return
3379 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3380 * g_socket_condition_check() has claimed that the socket is ready for
3381 * writing. Rather than calling g_socket_condition_check() and then
3382 * writing to the socket if it succeeds, it is generally better to
3383 * simply try writing to the socket right away, and try again later if
3384 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3386 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3387 * these conditions will always be set in the output if they are true.
3389 * This call never blocks.
3391 * Returns: the @GIOCondition mask of the current state
3396 g_socket_condition_check (GSocket *socket,
3397 GIOCondition condition)
3399 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3401 if (!check_socket (socket, NULL))
3406 GIOCondition current_condition;
3408 condition |= G_IO_ERR | G_IO_HUP;
3410 add_condition_watch (socket, &condition);
3411 current_condition = update_condition (socket);
3412 remove_condition_watch (socket, &condition);
3413 return condition & current_condition;
3419 poll_fd.fd = socket->priv->fd;
3420 poll_fd.events = condition;
3421 poll_fd.revents = 0;
3424 result = g_poll (&poll_fd, 1, 0);
3425 while (result == -1 && get_socket_errno () == EINTR);
3427 return poll_fd.revents;
3433 * g_socket_condition_wait:
3434 * @socket: a #GSocket
3435 * @condition: a #GIOCondition mask to wait for
3436 * @cancellable: (allow-none): a #GCancellable, or %NULL
3437 * @error: a #GError pointer, or %NULL
3439 * Waits for @condition to become true on @socket. When the condition
3440 * is met, %TRUE is returned.
3442 * If @cancellable is cancelled before the condition is met, or if the
3443 * socket has a timeout set and it is reached before the condition is
3444 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3445 * the appropriate value (%G_IO_ERROR_CANCELLED or
3446 * %G_IO_ERROR_TIMED_OUT).
3448 * See also g_socket_condition_timed_wait().
3450 * Returns: %TRUE if the condition was met, %FALSE otherwise
3455 g_socket_condition_wait (GSocket *socket,
3456 GIOCondition condition,
3457 GCancellable *cancellable,
3460 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3462 return g_socket_condition_timed_wait (socket, condition, -1,
3463 cancellable, error);
3467 * g_socket_condition_timed_wait:
3468 * @socket: a #GSocket
3469 * @condition: a #GIOCondition mask to wait for
3470 * @timeout: the maximum time (in microseconds) to wait, or -1
3471 * @cancellable: (allow-none): a #GCancellable, or %NULL
3472 * @error: a #GError pointer, or %NULL
3474 * Waits for up to @timeout microseconds for @condition to become true
3475 * on @socket. If the condition is met, %TRUE is returned.
3477 * If @cancellable is cancelled before the condition is met, or if
3478 * @timeout (or the socket's #GSocket:timeout) is reached before the
3479 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3480 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3481 * %G_IO_ERROR_TIMED_OUT).
3483 * If you don't want a timeout, use g_socket_condition_wait().
3484 * (Alternatively, you can pass -1 for @timeout.)
3486 * Note that although @timeout is in microseconds for consistency with
3487 * other GLib APIs, this function actually only has millisecond
3488 * resolution, and the behavior is undefined if @timeout is not an
3489 * exact number of milliseconds.
3491 * Returns: %TRUE if the condition was met, %FALSE otherwise
3496 g_socket_condition_timed_wait (GSocket *socket,
3497 GIOCondition condition,
3499 GCancellable *cancellable,
3504 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3506 if (!check_socket (socket, error))
3509 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3512 if (socket->priv->timeout &&
3513 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3514 timeout = socket->priv->timeout * 1000;
3515 else if (timeout != -1)
3516 timeout = timeout / 1000;
3518 start_time = g_get_monotonic_time ();
3522 GIOCondition current_condition;
3528 /* Always check these */
3529 condition |= G_IO_ERR | G_IO_HUP;
3531 add_condition_watch (socket, &condition);
3534 events[num_events++] = socket->priv->event;
3536 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3537 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3540 timeout = WSA_INFINITE;
3542 current_condition = update_condition (socket);
3543 while ((condition & current_condition) == 0)
3545 res = WSAWaitForMultipleEvents (num_events, events,
3546 FALSE, timeout, FALSE);
3547 if (res == WSA_WAIT_FAILED)
3549 int errsv = get_socket_errno ();
3551 g_set_error (error, G_IO_ERROR,
3552 socket_io_error_from_errno (errsv),
3553 _("Waiting for socket condition: %s"),
3554 socket_strerror (errsv));
3557 else if (res == WSA_WAIT_TIMEOUT)
3559 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3560 _("Socket I/O timed out"));
3564 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3567 current_condition = update_condition (socket);
3569 if (timeout != WSA_INFINITE)
3571 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3576 remove_condition_watch (socket, &condition);
3578 g_cancellable_release_fd (cancellable);
3580 return (condition & current_condition) != 0;
3588 poll_fd[0].fd = socket->priv->fd;
3589 poll_fd[0].events = condition;
3592 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3597 result = g_poll (poll_fd, num, timeout);
3598 if (result != -1 || errno != EINTR)
3603 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3610 g_cancellable_release_fd (cancellable);
3614 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3615 _("Socket I/O timed out"));
3619 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3625 * g_socket_send_message:
3626 * @socket: a #GSocket
3627 * @address: (allow-none): a #GSocketAddress, or %NULL
3628 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3629 * @num_vectors: the number of elements in @vectors, or -1
3630 * @messages: (array length=num_messages) (allow-none): a pointer to an
3631 * array of #GSocketControlMessages, or %NULL.
3632 * @num_messages: number of elements in @messages, or -1.
3633 * @flags: an int containing #GSocketMsgFlags flags
3634 * @cancellable: (allow-none): a %GCancellable or %NULL
3635 * @error: #GError for error reporting, or %NULL to ignore.
3637 * Send data to @address on @socket. This is the most complicated and
3638 * fully-featured version of this call. For easier use, see
3639 * g_socket_send() and g_socket_send_to().
3641 * If @address is %NULL then the message is sent to the default receiver
3642 * (set by g_socket_connect()).
3644 * @vectors must point to an array of #GOutputVector structs and
3645 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3646 * then @vectors is assumed to be terminated by a #GOutputVector with a
3647 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3648 * that the sent data will be gathered from. Using multiple
3649 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3650 * data from multiple sources into a single buffer, and more
3651 * network-efficient than making multiple calls to g_socket_send().
3653 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3654 * #GSocketControlMessage instances. These correspond to the control
3655 * messages to be sent on the socket.
3656 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3659 * @flags modify how the message is sent. The commonly available arguments
3660 * for this are available in the #GSocketMsgFlags enum, but the
3661 * values there are the same as the system values, and the flags
3662 * are passed in as-is, so you can pass in system-specific flags too.
3664 * If the socket is in blocking mode the call will block until there is
3665 * space for the data in the socket queue. If there is no space available
3666 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3667 * will be returned. To be notified when space is available, wait for the
3668 * %G_IO_OUT condition. Note though that you may still receive
3669 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3670 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3671 * very common due to the way the underlying APIs work.)
3673 * On error -1 is returned and @error is set accordingly.
3675 * Returns: Number of bytes written (which may be less than @size), or -1
3681 g_socket_send_message (GSocket *socket,
3682 GSocketAddress *address,
3683 GOutputVector *vectors,
3685 GSocketControlMessage **messages,
3688 GCancellable *cancellable,
3691 GOutputVector one_vector;
3694 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3696 if (!check_socket (socket, error))
3699 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3702 if (num_vectors == -1)
3704 for (num_vectors = 0;
3705 vectors[num_vectors].buffer != NULL;
3710 if (num_messages == -1)
3712 for (num_messages = 0;
3713 messages != NULL && messages[num_messages] != NULL;
3718 if (num_vectors == 0)
3722 one_vector.buffer = &zero;
3723 one_vector.size = 1;
3725 vectors = &one_vector;
3738 msg.msg_namelen = g_socket_address_get_native_size (address);
3739 msg.msg_name = g_alloca (msg.msg_namelen);
3740 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3745 msg.msg_name = NULL;
3746 msg.msg_namelen = 0;
3751 /* this entire expression will be evaluated at compile time */
3752 if (sizeof *msg.msg_iov == sizeof *vectors &&
3753 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3754 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3755 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3756 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3757 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3758 G_STRUCT_OFFSET (GOutputVector, size))
3759 /* ABI is compatible */
3761 msg.msg_iov = (struct iovec *) vectors;
3762 msg.msg_iovlen = num_vectors;
3765 /* ABI is incompatible */
3769 msg.msg_iov = g_newa (struct iovec, num_vectors);
3770 for (i = 0; i < num_vectors; i++)
3772 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3773 msg.msg_iov[i].iov_len = vectors[i].size;
3775 msg.msg_iovlen = num_vectors;
3781 struct cmsghdr *cmsg;
3784 msg.msg_controllen = 0;
3785 for (i = 0; i < num_messages; i++)
3786 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3788 if (msg.msg_controllen == 0)
3789 msg.msg_control = NULL;
3792 msg.msg_control = g_alloca (msg.msg_controllen);
3793 memset (msg.msg_control, '\0', msg.msg_controllen);
3796 cmsg = CMSG_FIRSTHDR (&msg);
3797 for (i = 0; i < num_messages; i++)
3799 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3800 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3801 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3802 g_socket_control_message_serialize (messages[i],
3804 cmsg = CMSG_NXTHDR (&msg, cmsg);
3806 g_assert (cmsg == NULL);
3811 if (socket->priv->blocking &&
3812 !g_socket_condition_wait (socket,
3813 G_IO_OUT, cancellable, error))
3816 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3819 int errsv = get_socket_errno ();
3824 if (socket->priv->blocking &&
3825 (errsv == EWOULDBLOCK ||
3829 g_set_error (error, G_IO_ERROR,
3830 socket_io_error_from_errno (errsv),
3831 _("Error sending message: %s"), socket_strerror (errsv));
3842 struct sockaddr_storage addr;
3849 /* Win32 doesn't support control messages.
3850 Actually this is possible for raw and datagram sockets
3851 via WSASendMessage on Vista or later, but that doesn't
3853 if (num_messages != 0)
3855 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3856 _("GSocketControlMessage not supported on Windows"));
3861 bufs = g_newa (WSABUF, num_vectors);
3862 for (i = 0; i < num_vectors; i++)
3864 bufs[i].buf = (char *)vectors[i].buffer;
3865 bufs[i].len = (gulong)vectors[i].size;
3869 addrlen = 0; /* Avoid warning */
3872 addrlen = g_socket_address_get_native_size (address);
3873 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3879 if (socket->priv->blocking &&
3880 !g_socket_condition_wait (socket,
3881 G_IO_OUT, cancellable, error))
3885 result = WSASendTo (socket->priv->fd,
3888 (const struct sockaddr *)&addr, addrlen,
3891 result = WSASend (socket->priv->fd,
3898 int errsv = get_socket_errno ();
3900 if (errsv == WSAEINTR)
3903 if (errsv == WSAEWOULDBLOCK)
3904 win32_unset_event_mask (socket, FD_WRITE);
3906 if (socket->priv->blocking &&
3907 errsv == WSAEWOULDBLOCK)
3910 g_set_error (error, G_IO_ERROR,
3911 socket_io_error_from_errno (errsv),
3912 _("Error sending message: %s"), socket_strerror (errsv));
3924 static GSocketAddress *
3925 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
3927 GSocketAddress *saddr;
3929 guint64 oldest_time = G_MAXUINT64;
3930 gint oldest_index = 0;
3932 if (native_len <= 0)
3936 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
3938 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
3939 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
3940 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
3945 if (tmp_native_len != native_len)
3948 if (memcmp (tmp_native, native, native_len) == 0)
3950 saddr = g_object_ref (tmp);
3951 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
3955 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
3957 oldest_time = socket->priv->recv_addr_cache[i].last_used;
3962 saddr = g_socket_address_new_from_native (native, native_len);
3964 if (socket->priv->recv_addr_cache[oldest_index].addr)
3966 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
3967 g_free (socket->priv->recv_addr_cache[oldest_index].native);
3970 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
3971 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
3972 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
3973 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
3979 * g_socket_receive_message:
3980 * @socket: a #GSocket
3981 * @address: (out) (allow-none): a pointer to a #GSocketAddress
3983 * @vectors: (array length=num_vectors): an array of #GInputVector structs
3984 * @num_vectors: the number of elements in @vectors, or -1
3985 * @messages: (array length=num_messages) (allow-none): a pointer which
3986 * may be filled with an array of #GSocketControlMessages, or %NULL
3987 * @num_messages: a pointer which will be filled with the number of
3988 * elements in @messages, or %NULL
3989 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3990 * @cancellable: (allow-none): a %GCancellable or %NULL
3991 * @error: a #GError pointer, or %NULL
3993 * Receive data from a socket. This is the most complicated and
3994 * fully-featured version of this call. For easier use, see
3995 * g_socket_receive() and g_socket_receive_from().
3997 * If @address is non-%NULL then @address will be set equal to the
3998 * source address of the received packet.
3999 * @address is owned by the caller.
4001 * @vector must point to an array of #GInputVector structs and
4002 * @num_vectors must be the length of this array. These structs
4003 * describe the buffers that received data will be scattered into.
4004 * If @num_vectors is -1, then @vectors is assumed to be terminated
4005 * by a #GInputVector with a %NULL buffer pointer.
4007 * As a special case, if @num_vectors is 0 (in which case, @vectors
4008 * may of course be %NULL), then a single byte is received and
4009 * discarded. This is to facilitate the common practice of sending a
4010 * single '\0' byte for the purposes of transferring ancillary data.
4012 * @messages, if non-%NULL, will be set to point to a newly-allocated
4013 * array of #GSocketControlMessage instances or %NULL if no such
4014 * messages was received. These correspond to the control messages
4015 * received from the kernel, one #GSocketControlMessage per message
4016 * from the kernel. This array is %NULL-terminated and must be freed
4017 * by the caller using g_free() after calling g_object_unref() on each
4018 * element. If @messages is %NULL, any control messages received will
4021 * @num_messages, if non-%NULL, will be set to the number of control
4022 * messages received.
4024 * If both @messages and @num_messages are non-%NULL, then
4025 * @num_messages gives the number of #GSocketControlMessage instances
4026 * in @messages (ie: not including the %NULL terminator).
4028 * @flags is an in/out parameter. The commonly available arguments
4029 * for this are available in the #GSocketMsgFlags enum, but the
4030 * values there are the same as the system values, and the flags
4031 * are passed in as-is, so you can pass in system-specific flags too
4032 * (and g_socket_receive_message() may pass system-specific flags out).
4034 * As with g_socket_receive(), data may be discarded if @socket is
4035 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
4036 * provide enough buffer space to read a complete message. You can pass
4037 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
4038 * removing it from the receive queue, but there is no portable way to find
4039 * out the length of the message other than by reading it into a
4040 * sufficiently-large buffer.
4042 * If the socket is in blocking mode the call will block until there
4043 * is some data to receive, the connection is closed, or there is an
4044 * error. If there is no data available and the socket is in
4045 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
4046 * returned. To be notified when data is available, wait for the
4047 * %G_IO_IN condition.
4049 * On error -1 is returned and @error is set accordingly.
4051 * Returns: Number of bytes read, or 0 if the connection was closed by
4052 * the peer, or -1 on error
4057 g_socket_receive_message (GSocket *socket,
4058 GSocketAddress **address,
4059 GInputVector *vectors,
4061 GSocketControlMessage ***messages,
4064 GCancellable *cancellable,
4067 GInputVector one_vector;
4070 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4072 if (!check_socket (socket, error))
4075 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4078 if (num_vectors == -1)
4080 for (num_vectors = 0;
4081 vectors[num_vectors].buffer != NULL;
4086 if (num_vectors == 0)
4088 one_vector.buffer = &one_byte;
4089 one_vector.size = 1;
4091 vectors = &one_vector;
4098 struct sockaddr_storage one_sockaddr;
4103 msg.msg_name = &one_sockaddr;
4104 msg.msg_namelen = sizeof (struct sockaddr_storage);
4108 msg.msg_name = NULL;
4109 msg.msg_namelen = 0;
4113 /* this entire expression will be evaluated at compile time */
4114 if (sizeof *msg.msg_iov == sizeof *vectors &&
4115 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4116 G_STRUCT_OFFSET (struct iovec, iov_base) ==
4117 G_STRUCT_OFFSET (GInputVector, buffer) &&
4118 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4119 G_STRUCT_OFFSET (struct iovec, iov_len) ==
4120 G_STRUCT_OFFSET (GInputVector, size))
4121 /* ABI is compatible */
4123 msg.msg_iov = (struct iovec *) vectors;
4124 msg.msg_iovlen = num_vectors;
4127 /* ABI is incompatible */
4131 msg.msg_iov = g_newa (struct iovec, num_vectors);
4132 for (i = 0; i < num_vectors; i++)
4134 msg.msg_iov[i].iov_base = vectors[i].buffer;
4135 msg.msg_iov[i].iov_len = vectors[i].size;
4137 msg.msg_iovlen = num_vectors;
4141 msg.msg_control = g_alloca (2048);
4142 msg.msg_controllen = 2048;
4146 msg.msg_flags = *flags;
4150 /* We always set the close-on-exec flag so we don't leak file
4151 * descriptors into child processes. Note that gunixfdmessage.c
4152 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4154 #ifdef MSG_CMSG_CLOEXEC
4155 msg.msg_flags |= MSG_CMSG_CLOEXEC;
4161 if (socket->priv->blocking &&
4162 !g_socket_condition_wait (socket,
4163 G_IO_IN, cancellable, error))
4166 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4167 #ifdef MSG_CMSG_CLOEXEC
4168 if (result < 0 && get_socket_errno () == EINVAL)
4170 /* We must be running on an old kernel. Call without the flag. */
4171 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4172 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4178 int errsv = get_socket_errno ();
4183 if (socket->priv->blocking &&
4184 (errsv == EWOULDBLOCK ||
4188 g_set_error (error, G_IO_ERROR,
4189 socket_io_error_from_errno (errsv),
4190 _("Error receiving message: %s"), socket_strerror (errsv));
4197 /* decode address */
4198 if (address != NULL)
4200 *address = cache_recv_address (socket, msg.msg_name, msg.msg_namelen);
4203 /* decode control messages */
4205 GPtrArray *my_messages = NULL;
4206 struct cmsghdr *cmsg;
4208 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4210 GSocketControlMessage *message;
4212 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4214 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4216 if (message == NULL)
4217 /* We've already spewed about the problem in the
4218 deserialization code, so just continue */
4221 if (messages == NULL)
4223 /* we have to do it this way if the user ignores the
4224 * messages so that we will close any received fds.
4226 g_object_unref (message);
4230 if (my_messages == NULL)
4231 my_messages = g_ptr_array_new ();
4232 g_ptr_array_add (my_messages, message);
4237 *num_messages = my_messages != NULL ? my_messages->len : 0;
4241 if (my_messages == NULL)
4247 g_ptr_array_add (my_messages, NULL);
4248 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4253 g_assert (my_messages == NULL);
4257 /* capture the flags */
4259 *flags = msg.msg_flags;
4265 struct sockaddr_storage addr;
4267 DWORD bytes_received;
4274 bufs = g_newa (WSABUF, num_vectors);
4275 for (i = 0; i < num_vectors; i++)
4277 bufs[i].buf = (char *)vectors[i].buffer;
4278 bufs[i].len = (gulong)vectors[i].size;
4290 if (socket->priv->blocking &&
4291 !g_socket_condition_wait (socket,
4292 G_IO_IN, cancellable, error))
4295 addrlen = sizeof addr;
4297 result = WSARecvFrom (socket->priv->fd,
4299 &bytes_received, &win_flags,
4300 (struct sockaddr *)&addr, &addrlen,
4303 result = WSARecv (socket->priv->fd,
4305 &bytes_received, &win_flags,
4309 int errsv = get_socket_errno ();
4311 if (errsv == WSAEINTR)
4314 win32_unset_event_mask (socket, FD_READ);
4316 if (socket->priv->blocking &&
4317 errsv == WSAEWOULDBLOCK)
4320 g_set_error (error, G_IO_ERROR,
4321 socket_io_error_from_errno (errsv),
4322 _("Error receiving message: %s"), socket_strerror (errsv));
4326 win32_unset_event_mask (socket, FD_READ);
4330 /* decode address */
4331 if (address != NULL)
4333 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
4336 /* capture the flags */
4340 if (messages != NULL)
4342 if (num_messages != NULL)
4345 return bytes_received;
4351 * g_socket_get_credentials:
4352 * @socket: a #GSocket.
4353 * @error: #GError for error reporting, or %NULL to ignore.
4355 * Returns the credentials of the foreign process connected to this
4356 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4359 * If this operation isn't supported on the OS, the method fails with
4360 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4361 * by reading the %SO_PEERCRED option on the underlying socket.
4363 * Other ways to obtain credentials from a foreign peer includes the
4364 * #GUnixCredentialsMessage type and
4365 * g_unix_connection_send_credentials() /
4366 * g_unix_connection_receive_credentials() functions.
4368 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4369 * that must be freed with g_object_unref().
4374 g_socket_get_credentials (GSocket *socket,
4379 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4380 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4384 #if defined(__linux__) || defined(__OpenBSD__)
4387 #if defined(__linux__)
4388 struct ucred native_creds;
4389 optlen = sizeof (struct ucred);
4390 #elif defined(__OpenBSD__)
4391 struct sockpeercred native_creds;
4392 optlen = sizeof (struct sockpeercred);
4394 if (getsockopt (socket->priv->fd,
4397 (void *)&native_creds,
4400 int errsv = get_socket_errno ();
4403 socket_io_error_from_errno (errsv),
4404 _("Unable to get pending error: %s"),
4405 socket_strerror (errsv));
4409 ret = g_credentials_new ();
4410 g_credentials_set_native (ret,
4411 #if defined(__linux__)
4412 G_CREDENTIALS_TYPE_LINUX_UCRED,
4413 #elif defined(__OpenBSD__)
4414 G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
4420 g_set_error_literal (error,
4422 G_IO_ERROR_NOT_SUPPORTED,
4423 _("g_socket_get_credentials not implemented for this OS"));