1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2008 Christian Kellner, Samuel Cormier-Iijima
4 * Copyright © 2009 Codethink Limited
5 * Copyright © 2009 Red Hat, Inc
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General
18 * Public License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20 * Boston, MA 02111-1307, USA.
22 * Authors: Christian Kellner <gicmo@gnome.org>
23 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
24 * Ryan Lortie <desrt@desrt.ca>
25 * Alexander Larsson <alexl@redhat.com>
33 #include "glib-unix.h"
44 # include <sys/ioctl.h>
47 #ifdef HAVE_SYS_FILIO_H
48 # include <sys/filio.h>
55 #include "gcancellable.h"
56 #include "gioenumtypes.h"
57 #include "ginetaddress.h"
58 #include "ginitable.h"
62 #include "gnetworkingprivate.h"
63 #include "gsocketaddress.h"
64 #include "gsocketcontrolmessage.h"
65 #include "gcredentials.h"
66 #include "gcredentialsprivate.h"
71 * @short_description: Low-level socket object
73 * @see_also: #GInitable, <link linkend="gio-gnetworking.h">gnetworking.h</link>
75 * A #GSocket is a low-level networking primitive. It is a more or less
76 * direct mapping of the BSD socket API in a portable GObject based API.
77 * It supports both the UNIX socket implementations and winsock2 on Windows.
79 * #GSocket is the platform independent base upon which the higher level
80 * network primitives are based. Applications are not typically meant to
81 * use it directly, but rather through classes like #GSocketClient,
82 * #GSocketService and #GSocketConnection. However there may be cases where
83 * direct use of #GSocket is useful.
85 * #GSocket implements the #GInitable interface, so if it is manually constructed
86 * by e.g. g_object_new() you must call g_initable_init() and check the
87 * results before using the object. This is done automatically in
88 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
91 * Sockets operate in two general modes, blocking or non-blocking. When
92 * in blocking mode all operations block until the requested operation
93 * is finished or there is an error. In non-blocking mode all calls that
94 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
95 * To know when a call would successfully run you can call g_socket_condition_check(),
96 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
97 * attach it to a #GMainContext to get callbacks when I/O is possible.
98 * Note that all sockets are always set to non blocking mode in the system, and
99 * blocking mode is emulated in GSocket.
101 * When working in non-blocking mode applications should always be able to
102 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
103 * function said that I/O was possible. This can easily happen in case
104 * of a race condition in the application, but it can also happen for other
105 * reasons. For instance, on Windows a socket is always seen as writable
106 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
108 * #GSocket<!-- -->s can be either connection oriented or datagram based.
109 * For connection oriented types you must first establish a connection by
110 * either connecting to an address or accepting a connection from another
111 * address. For connectionless socket types the target/source address is
112 * specified or received in each I/O operation.
114 * All socket file descriptors are set to be close-on-exec.
116 * Note that creating a #GSocket causes the signal %SIGPIPE to be
117 * ignored for the remainder of the program. If you are writing a
118 * command-line utility that uses #GSocket, you may need to take into
119 * account the fact that your program will not automatically be killed
120 * if it tries to write to %stdout after it has been closed.
125 static void g_socket_initable_iface_init (GInitableIface *iface);
126 static gboolean g_socket_initable_init (GInitable *initable,
127 GCancellable *cancellable,
145 PROP_MULTICAST_LOOPBACK,
149 /* Size of the receiver cache for g_socket_receive_from() */
150 #define RECV_ADDR_CACHE_SIZE 8
152 struct _GSocketPrivate
154 GSocketFamily family;
156 GSocketProtocol protocol;
160 GError *construct_error;
161 GSocketAddress *remote_address;
169 guint connect_pending : 1;
175 GList *requested_conditions; /* list of requested GIOCondition * */
176 GMutex win32_source_lock;
180 GSocketAddress *addr;
181 struct sockaddr *native;
184 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
187 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
188 G_ADD_PRIVATE (GSocket)
189 g_networking_init ();
190 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
191 g_socket_initable_iface_init));
194 get_socket_errno (void)
199 return WSAGetLastError ();
204 socket_io_error_from_errno (int err)
207 return g_io_error_from_errno (err);
212 return G_IO_ERROR_ADDRESS_IN_USE;
214 return G_IO_ERROR_WOULD_BLOCK;
216 return G_IO_ERROR_PERMISSION_DENIED;
217 case WSA_INVALID_HANDLE:
218 case WSA_INVALID_PARAMETER:
221 return G_IO_ERROR_INVALID_ARGUMENT;
222 case WSAEPROTONOSUPPORT:
223 return G_IO_ERROR_NOT_SUPPORTED;
225 return G_IO_ERROR_CANCELLED;
226 case WSAESOCKTNOSUPPORT:
228 case WSAEPFNOSUPPORT:
229 case WSAEAFNOSUPPORT:
230 return G_IO_ERROR_NOT_SUPPORTED;
232 return G_IO_ERROR_FAILED;
238 socket_strerror (int err)
241 return g_strerror (err);
246 msg = g_win32_error_message (err);
248 msg_ret = g_intern_string (msg);
256 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
258 _win32_unset_event_mask (GSocket *socket, int mask)
260 socket->priv->current_events &= ~mask;
261 socket->priv->current_errors &= ~mask;
264 #define win32_unset_event_mask(_socket, _mask)
267 /* Windows has broken prototypes... */
269 #define getsockopt(sockfd, level, optname, optval, optlen) \
270 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
271 #define setsockopt(sockfd, level, optname, optval, optlen) \
272 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
273 #define getsockname(sockfd, addr, addrlen) \
274 getsockname (sockfd, addr, (int *)addrlen)
275 #define getpeername(sockfd, addr, addrlen) \
276 getpeername (sockfd, addr, (int *)addrlen)
277 #define recv(sockfd, buf, len, flags) \
278 recv (sockfd, (gpointer)buf, len, flags)
282 set_fd_nonblocking (int fd)
285 GError *error = NULL;
291 if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
293 g_warning ("Error setting socket nonblocking: %s", error->message);
294 g_clear_error (&error);
299 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
301 int errsv = get_socket_errno ();
302 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
308 check_socket (GSocket *socket,
311 if (!socket->priv->inited)
313 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
314 _("Invalid socket, not initialized"));
318 if (socket->priv->construct_error)
320 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
321 _("Invalid socket, initialization failed due to: %s"),
322 socket->priv->construct_error->message);
326 if (socket->priv->closed)
328 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
329 _("Socket is already closed"));
333 if (socket->priv->timed_out)
335 socket->priv->timed_out = FALSE;
336 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
337 _("Socket I/O timed out"));
345 g_socket_details_from_fd (GSocket *socket)
347 struct sockaddr_storage address;
353 fd = socket->priv->fd;
354 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
356 errsv = get_socket_errno ();
368 /* programmer error */
369 g_error ("creating GSocket from fd %d: %s\n",
370 fd, socket_strerror (errsv));
381 socket->priv->type = G_SOCKET_TYPE_STREAM;
385 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
389 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
393 socket->priv->type = G_SOCKET_TYPE_INVALID;
397 addrlen = sizeof address;
398 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
400 errsv = get_socket_errno ();
406 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
407 sizeof address.ss_family <= addrlen);
408 family = address.ss_family;
412 /* On Solaris, this happens if the socket is not yet connected.
413 * But we can use SO_DOMAIN as a workaround there.
416 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
418 errsv = get_socket_errno ();
422 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
430 case G_SOCKET_FAMILY_IPV4:
431 case G_SOCKET_FAMILY_IPV6:
432 socket->priv->family = address.ss_family;
433 switch (socket->priv->type)
435 case G_SOCKET_TYPE_STREAM:
436 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
439 case G_SOCKET_TYPE_DATAGRAM:
440 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
443 case G_SOCKET_TYPE_SEQPACKET:
444 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
452 case G_SOCKET_FAMILY_UNIX:
453 socket->priv->family = G_SOCKET_FAMILY_UNIX;
454 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
458 socket->priv->family = G_SOCKET_FAMILY_INVALID;
462 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
464 addrlen = sizeof address;
465 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
466 socket->priv->connected = TRUE;
469 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
471 socket->priv->keepalive = !!value;
475 /* Can't read, maybe not supported, assume FALSE */
476 socket->priv->keepalive = FALSE;
482 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
483 socket_io_error_from_errno (errsv),
484 _("creating GSocket from fd: %s"),
485 socket_strerror (errsv));
488 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
490 g_socket (gint domain,
498 fd = socket (domain, type | SOCK_CLOEXEC, protocol);
502 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
503 if (fd < 0 && (errno == EINVAL || errno == EPROTOTYPE))
505 fd = socket (domain, type, protocol);
509 int errsv = get_socket_errno ();
511 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
512 _("Unable to create socket: %s"), socket_strerror (errsv));
521 /* We always want to set close-on-exec to protect users. If you
522 need to so some weird inheritance to exec you can re-enable this
523 using lower level hacks with g_socket_get_fd(). */
524 flags = fcntl (fd, F_GETFD, 0);
526 (flags & FD_CLOEXEC) == 0)
529 fcntl (fd, F_SETFD, flags);
538 g_socket_create_socket (GSocketFamily family,
547 case G_SOCKET_TYPE_STREAM:
548 native_type = SOCK_STREAM;
551 case G_SOCKET_TYPE_DATAGRAM:
552 native_type = SOCK_DGRAM;
555 case G_SOCKET_TYPE_SEQPACKET:
556 native_type = SOCK_SEQPACKET;
560 g_assert_not_reached ();
565 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
566 _("Unable to create socket: %s"), _("Unknown family was specified"));
572 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
573 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
577 return g_socket (family, native_type, protocol, error);
581 g_socket_constructed (GObject *object)
583 GSocket *socket = G_SOCKET (object);
585 if (socket->priv->fd >= 0)
586 /* create socket->priv info from the fd */
587 g_socket_details_from_fd (socket);
590 /* create the fd from socket->priv info */
591 socket->priv->fd = g_socket_create_socket (socket->priv->family,
593 socket->priv->protocol,
594 &socket->priv->construct_error);
596 /* Always use native nonblocking sockets, as
597 windows sets sockets to nonblocking automatically
598 in certain operations. This way we make things work
599 the same on all platforms */
600 if (socket->priv->fd != -1)
601 set_fd_nonblocking (socket->priv->fd);
605 g_socket_get_property (GObject *object,
610 GSocket *socket = G_SOCKET (object);
611 GSocketAddress *address;
616 g_value_set_enum (value, socket->priv->family);
620 g_value_set_enum (value, socket->priv->type);
624 g_value_set_enum (value, socket->priv->protocol);
628 g_value_set_int (value, socket->priv->fd);
632 g_value_set_boolean (value, socket->priv->blocking);
635 case PROP_LISTEN_BACKLOG:
636 g_value_set_int (value, socket->priv->listen_backlog);
640 g_value_set_boolean (value, socket->priv->keepalive);
643 case PROP_LOCAL_ADDRESS:
644 address = g_socket_get_local_address (socket, NULL);
645 g_value_take_object (value, address);
648 case PROP_REMOTE_ADDRESS:
649 address = g_socket_get_remote_address (socket, NULL);
650 g_value_take_object (value, address);
654 g_value_set_uint (value, socket->priv->timeout);
658 g_value_set_uint (value, g_socket_get_ttl (socket));
662 g_value_set_boolean (value, g_socket_get_broadcast (socket));
665 case PROP_MULTICAST_LOOPBACK:
666 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
669 case PROP_MULTICAST_TTL:
670 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
674 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
679 g_socket_set_property (GObject *object,
684 GSocket *socket = G_SOCKET (object);
689 socket->priv->family = g_value_get_enum (value);
693 socket->priv->type = g_value_get_enum (value);
697 socket->priv->protocol = g_value_get_enum (value);
701 socket->priv->fd = g_value_get_int (value);
705 g_socket_set_blocking (socket, g_value_get_boolean (value));
708 case PROP_LISTEN_BACKLOG:
709 g_socket_set_listen_backlog (socket, g_value_get_int (value));
713 g_socket_set_keepalive (socket, g_value_get_boolean (value));
717 g_socket_set_timeout (socket, g_value_get_uint (value));
721 g_socket_set_ttl (socket, g_value_get_uint (value));
725 g_socket_set_broadcast (socket, g_value_get_boolean (value));
728 case PROP_MULTICAST_LOOPBACK:
729 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
732 case PROP_MULTICAST_TTL:
733 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
737 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
742 g_socket_finalize (GObject *object)
744 GSocket *socket = G_SOCKET (object);
747 g_clear_error (&socket->priv->construct_error);
749 if (socket->priv->fd != -1 &&
750 !socket->priv->closed)
751 g_socket_close (socket, NULL);
753 if (socket->priv->remote_address)
754 g_object_unref (socket->priv->remote_address);
757 if (socket->priv->event != WSA_INVALID_EVENT)
759 WSACloseEvent (socket->priv->event);
760 socket->priv->event = WSA_INVALID_EVENT;
763 g_assert (socket->priv->requested_conditions == NULL);
764 g_mutex_clear (&socket->priv->win32_source_lock);
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 gobject_class->finalize = g_socket_finalize;
794 gobject_class->constructed = g_socket_constructed;
795 gobject_class->set_property = g_socket_set_property;
796 gobject_class->get_property = g_socket_get_property;
798 g_object_class_install_property (gobject_class, PROP_FAMILY,
799 g_param_spec_enum ("family",
801 P_("The sockets address family"),
802 G_TYPE_SOCKET_FAMILY,
803 G_SOCKET_FAMILY_INVALID,
804 G_PARAM_CONSTRUCT_ONLY |
806 G_PARAM_STATIC_STRINGS));
808 g_object_class_install_property (gobject_class, PROP_TYPE,
809 g_param_spec_enum ("type",
811 P_("The sockets type"),
813 G_SOCKET_TYPE_STREAM,
814 G_PARAM_CONSTRUCT_ONLY |
816 G_PARAM_STATIC_STRINGS));
818 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
819 g_param_spec_enum ("protocol",
820 P_("Socket protocol"),
821 P_("The id of the protocol to use, or -1 for unknown"),
822 G_TYPE_SOCKET_PROTOCOL,
823 G_SOCKET_PROTOCOL_UNKNOWN,
824 G_PARAM_CONSTRUCT_ONLY |
826 G_PARAM_STATIC_STRINGS));
828 g_object_class_install_property (gobject_class, PROP_FD,
829 g_param_spec_int ("fd",
830 P_("File descriptor"),
831 P_("The sockets file descriptor"),
835 G_PARAM_CONSTRUCT_ONLY |
837 G_PARAM_STATIC_STRINGS));
839 g_object_class_install_property (gobject_class, PROP_BLOCKING,
840 g_param_spec_boolean ("blocking",
842 P_("Whether or not I/O on this socket is blocking"),
845 G_PARAM_STATIC_STRINGS));
847 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
848 g_param_spec_int ("listen-backlog",
849 P_("Listen backlog"),
850 P_("Outstanding connections in the listen queue"),
855 G_PARAM_STATIC_STRINGS));
857 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
858 g_param_spec_boolean ("keepalive",
859 P_("Keep connection alive"),
860 P_("Keep connection alive by sending periodic pings"),
863 G_PARAM_STATIC_STRINGS));
865 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
866 g_param_spec_object ("local-address",
868 P_("The local address the socket is bound to"),
869 G_TYPE_SOCKET_ADDRESS,
871 G_PARAM_STATIC_STRINGS));
873 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
874 g_param_spec_object ("remote-address",
875 P_("Remote address"),
876 P_("The remote address the socket is connected to"),
877 G_TYPE_SOCKET_ADDRESS,
879 G_PARAM_STATIC_STRINGS));
884 * The timeout in seconds on socket I/O
888 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
889 g_param_spec_uint ("timeout",
891 P_("The timeout in seconds on socket I/O"),
896 G_PARAM_STATIC_STRINGS));
901 * Whether the socket should allow sending to broadcast addresses.
905 g_object_class_install_property (gobject_class, PROP_BROADCAST,
906 g_param_spec_boolean ("broadcast",
908 P_("Whether to allow sending to broadcast addresses"),
911 G_PARAM_STATIC_STRINGS));
916 * Time-to-live for outgoing unicast packets
920 g_object_class_install_property (gobject_class, PROP_TTL,
921 g_param_spec_uint ("ttl",
923 P_("Time-to-live of outgoing unicast packets"),
926 G_PARAM_STATIC_STRINGS));
929 * GSocket:multicast-loopback:
931 * Whether outgoing multicast packets loop back to the local host.
935 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
936 g_param_spec_boolean ("multicast-loopback",
937 P_("Multicast loopback"),
938 P_("Whether outgoing multicast packets loop back to the local host"),
941 G_PARAM_STATIC_STRINGS));
944 * GSocket:multicast-ttl:
946 * Time-to-live out outgoing multicast packets
950 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
951 g_param_spec_uint ("multicast-ttl",
953 P_("Time-to-live of outgoing multicast packets"),
956 G_PARAM_STATIC_STRINGS));
960 g_socket_initable_iface_init (GInitableIface *iface)
962 iface->init = g_socket_initable_init;
966 g_socket_init (GSocket *socket)
968 socket->priv = g_socket_get_instance_private (socket);
970 socket->priv->fd = -1;
971 socket->priv->blocking = TRUE;
972 socket->priv->listen_backlog = 10;
973 socket->priv->construct_error = NULL;
975 socket->priv->event = WSA_INVALID_EVENT;
976 g_mutex_init (&socket->priv->win32_source_lock);
981 g_socket_initable_init (GInitable *initable,
982 GCancellable *cancellable,
987 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
989 socket = G_SOCKET (initable);
991 if (cancellable != NULL)
993 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
994 _("Cancellable initialization not supported"));
998 socket->priv->inited = TRUE;
1000 if (socket->priv->construct_error)
1003 *error = g_error_copy (socket->priv->construct_error);
1013 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1014 * @type: the socket type to use.
1015 * @protocol: the id of the protocol to use, or 0 for default.
1016 * @error: #GError for error reporting, or %NULL to ignore.
1018 * Creates a new #GSocket with the defined family, type and protocol.
1019 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1020 * for the family and type is used.
1022 * The @protocol is a family and type specific int that specifies what
1023 * kind of protocol to use. #GSocketProtocol lists several common ones.
1024 * Many families only support one protocol, and use 0 for this, others
1025 * support several and using 0 means to use the default protocol for
1026 * the family and type.
1028 * The protocol id is passed directly to the operating
1029 * system, so you can use protocols not listed in #GSocketProtocol if you
1030 * know the protocol number used for it.
1032 * Returns: a #GSocket or %NULL on error.
1033 * Free the returned object with g_object_unref().
1038 g_socket_new (GSocketFamily family,
1040 GSocketProtocol protocol,
1043 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1047 "protocol", protocol,
1052 * g_socket_new_from_fd:
1053 * @fd: a native socket file descriptor.
1054 * @error: #GError for error reporting, or %NULL to ignore.
1056 * Creates a new #GSocket from a native file descriptor
1057 * or winsock SOCKET handle.
1059 * This reads all the settings from the file descriptor so that
1060 * all properties should work. Note that the file descriptor
1061 * will be set to non-blocking mode, independent on the blocking
1062 * mode of the #GSocket.
1064 * Returns: a #GSocket or %NULL on error.
1065 * Free the returned object with g_object_unref().
1070 g_socket_new_from_fd (gint fd,
1073 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1080 * g_socket_set_blocking:
1081 * @socket: a #GSocket.
1082 * @blocking: Whether to use blocking I/O or not.
1084 * Sets the blocking mode of the socket. In blocking mode
1085 * all operations block until they succeed or there is an error. In
1086 * non-blocking mode all functions return results immediately or
1087 * with a %G_IO_ERROR_WOULD_BLOCK error.
1089 * All sockets are created in blocking mode. However, note that the
1090 * platform level socket is always non-blocking, and blocking mode
1091 * is a GSocket level feature.
1096 g_socket_set_blocking (GSocket *socket,
1099 g_return_if_fail (G_IS_SOCKET (socket));
1101 blocking = !!blocking;
1103 if (socket->priv->blocking == blocking)
1106 socket->priv->blocking = blocking;
1107 g_object_notify (G_OBJECT (socket), "blocking");
1111 * g_socket_get_blocking:
1112 * @socket: a #GSocket.
1114 * Gets the blocking mode of the socket. For details on blocking I/O,
1115 * see g_socket_set_blocking().
1117 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1122 g_socket_get_blocking (GSocket *socket)
1124 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1126 return socket->priv->blocking;
1130 * g_socket_set_keepalive:
1131 * @socket: a #GSocket.
1132 * @keepalive: Value for the keepalive flag
1134 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1135 * this flag is set on a socket, the system will attempt to verify that the
1136 * remote socket endpoint is still present if a sufficiently long period of
1137 * time passes with no data being exchanged. If the system is unable to
1138 * verify the presence of the remote endpoint, it will automatically close
1141 * This option is only functional on certain kinds of sockets. (Notably,
1142 * %G_SOCKET_PROTOCOL_TCP sockets.)
1144 * The exact time between pings is system- and protocol-dependent, but will
1145 * normally be at least two hours. Most commonly, you would set this flag
1146 * on a server socket if you want to allow clients to remain idle for long
1147 * periods of time, but also want to ensure that connections are eventually
1148 * garbage-collected if clients crash or become unreachable.
1153 g_socket_set_keepalive (GSocket *socket,
1156 GError *error = NULL;
1158 g_return_if_fail (G_IS_SOCKET (socket));
1160 keepalive = !!keepalive;
1161 if (socket->priv->keepalive == keepalive)
1164 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1167 g_warning ("error setting keepalive: %s", error->message);
1168 g_error_free (error);
1172 socket->priv->keepalive = keepalive;
1173 g_object_notify (G_OBJECT (socket), "keepalive");
1177 * g_socket_get_keepalive:
1178 * @socket: a #GSocket.
1180 * Gets the keepalive mode of the socket. For details on this,
1181 * see g_socket_set_keepalive().
1183 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1188 g_socket_get_keepalive (GSocket *socket)
1190 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1192 return socket->priv->keepalive;
1196 * g_socket_get_listen_backlog:
1197 * @socket: a #GSocket.
1199 * Gets the listen backlog setting of the socket. For details on this,
1200 * see g_socket_set_listen_backlog().
1202 * Returns: the maximum number of pending connections.
1207 g_socket_get_listen_backlog (GSocket *socket)
1209 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1211 return socket->priv->listen_backlog;
1215 * g_socket_set_listen_backlog:
1216 * @socket: a #GSocket.
1217 * @backlog: the maximum number of pending connections.
1219 * Sets the maximum number of outstanding connections allowed
1220 * when listening on this socket. If more clients than this are
1221 * connecting to the socket and the application is not handling them
1222 * on time then the new connections will be refused.
1224 * Note that this must be called before g_socket_listen() and has no
1225 * effect if called after that.
1230 g_socket_set_listen_backlog (GSocket *socket,
1233 g_return_if_fail (G_IS_SOCKET (socket));
1234 g_return_if_fail (!socket->priv->listening);
1236 if (backlog != socket->priv->listen_backlog)
1238 socket->priv->listen_backlog = backlog;
1239 g_object_notify (G_OBJECT (socket), "listen-backlog");
1244 * g_socket_get_timeout:
1245 * @socket: a #GSocket.
1247 * Gets the timeout setting of the socket. For details on this, see
1248 * g_socket_set_timeout().
1250 * Returns: the timeout in seconds
1255 g_socket_get_timeout (GSocket *socket)
1257 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1259 return socket->priv->timeout;
1263 * g_socket_set_timeout:
1264 * @socket: a #GSocket.
1265 * @timeout: the timeout for @socket, in seconds, or 0 for none
1267 * Sets the time in seconds after which I/O operations on @socket will
1268 * time out if they have not yet completed.
1270 * On a blocking socket, this means that any blocking #GSocket
1271 * operation will time out after @timeout seconds of inactivity,
1272 * returning %G_IO_ERROR_TIMED_OUT.
1274 * On a non-blocking socket, calls to g_socket_condition_wait() will
1275 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1276 * created with g_socket_create_source() will trigger after
1277 * @timeout seconds of inactivity, with the requested condition
1278 * set, at which point calling g_socket_receive(), g_socket_send(),
1279 * g_socket_check_connect_result(), etc, will fail with
1280 * %G_IO_ERROR_TIMED_OUT.
1282 * If @timeout is 0 (the default), operations will never time out
1285 * Note that if an I/O operation is interrupted by a signal, this may
1286 * cause the timeout to be reset.
1291 g_socket_set_timeout (GSocket *socket,
1294 g_return_if_fail (G_IS_SOCKET (socket));
1296 if (timeout != socket->priv->timeout)
1298 socket->priv->timeout = timeout;
1299 g_object_notify (G_OBJECT (socket), "timeout");
1305 * @socket: a #GSocket.
1307 * Gets the unicast time-to-live setting on @socket; see
1308 * g_socket_set_ttl() for more details.
1310 * Returns: the time-to-live setting on @socket
1315 g_socket_get_ttl (GSocket *socket)
1317 GError *error = NULL;
1320 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1322 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1324 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1327 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1329 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1333 g_return_val_if_reached (0);
1337 g_warning ("error getting unicast ttl: %s", error->message);
1338 g_error_free (error);
1347 * @socket: a #GSocket.
1348 * @ttl: the time-to-live value for all unicast packets on @socket
1350 * Sets the time-to-live for outgoing unicast packets on @socket.
1351 * By default the platform-specific default value is used.
1356 g_socket_set_ttl (GSocket *socket,
1359 GError *error = NULL;
1361 g_return_if_fail (G_IS_SOCKET (socket));
1363 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1365 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1368 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1370 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1372 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1376 g_return_if_reached ();
1380 g_warning ("error setting unicast ttl: %s", error->message);
1381 g_error_free (error);
1385 g_object_notify (G_OBJECT (socket), "ttl");
1389 * g_socket_get_broadcast:
1390 * @socket: a #GSocket.
1392 * Gets the broadcast setting on @socket; if %TRUE,
1393 * it is possible to send packets to broadcast
1396 * Returns: the broadcast setting on @socket
1401 g_socket_get_broadcast (GSocket *socket)
1403 GError *error = NULL;
1406 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1408 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1411 g_warning ("error getting broadcast: %s", error->message);
1412 g_error_free (error);
1420 * g_socket_set_broadcast:
1421 * @socket: a #GSocket.
1422 * @broadcast: whether @socket should allow sending to broadcast
1425 * Sets whether @socket should allow sending to broadcast addresses.
1426 * This is %FALSE by default.
1431 g_socket_set_broadcast (GSocket *socket,
1434 GError *error = NULL;
1436 g_return_if_fail (G_IS_SOCKET (socket));
1438 broadcast = !!broadcast;
1440 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1443 g_warning ("error setting broadcast: %s", error->message);
1444 g_error_free (error);
1448 g_object_notify (G_OBJECT (socket), "broadcast");
1452 * g_socket_get_multicast_loopback:
1453 * @socket: a #GSocket.
1455 * Gets the multicast loopback setting on @socket; if %TRUE (the
1456 * default), outgoing multicast packets will be looped back to
1457 * multicast listeners on the same host.
1459 * Returns: the multicast loopback setting on @socket
1464 g_socket_get_multicast_loopback (GSocket *socket)
1466 GError *error = NULL;
1469 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1471 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1473 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1476 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1478 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1482 g_return_val_if_reached (FALSE);
1486 g_warning ("error getting multicast loopback: %s", error->message);
1487 g_error_free (error);
1495 * g_socket_set_multicast_loopback:
1496 * @socket: a #GSocket.
1497 * @loopback: whether @socket should receive messages sent to its
1498 * multicast groups from the local host
1500 * Sets whether outgoing multicast packets will be received by sockets
1501 * listening on that multicast address on the same host. This is %TRUE
1507 g_socket_set_multicast_loopback (GSocket *socket,
1510 GError *error = NULL;
1512 g_return_if_fail (G_IS_SOCKET (socket));
1514 loopback = !!loopback;
1516 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1518 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1521 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1523 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1525 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1529 g_return_if_reached ();
1533 g_warning ("error setting multicast loopback: %s", error->message);
1534 g_error_free (error);
1538 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1542 * g_socket_get_multicast_ttl:
1543 * @socket: a #GSocket.
1545 * Gets the multicast time-to-live setting on @socket; see
1546 * g_socket_set_multicast_ttl() for more details.
1548 * Returns: the multicast time-to-live setting on @socket
1553 g_socket_get_multicast_ttl (GSocket *socket)
1555 GError *error = NULL;
1558 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1560 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1562 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1565 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1567 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1571 g_return_val_if_reached (FALSE);
1575 g_warning ("error getting multicast ttl: %s", error->message);
1576 g_error_free (error);
1584 * g_socket_set_multicast_ttl:
1585 * @socket: a #GSocket.
1586 * @ttl: the time-to-live value for all multicast datagrams on @socket
1588 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1589 * By default, this is 1, meaning that multicast packets will not leave
1590 * the local network.
1595 g_socket_set_multicast_ttl (GSocket *socket,
1598 GError *error = NULL;
1600 g_return_if_fail (G_IS_SOCKET (socket));
1602 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1604 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1607 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1609 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1611 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1615 g_return_if_reached ();
1619 g_warning ("error setting multicast ttl: %s", error->message);
1620 g_error_free (error);
1624 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1628 * g_socket_get_family:
1629 * @socket: a #GSocket.
1631 * Gets the socket family of the socket.
1633 * Returns: a #GSocketFamily
1638 g_socket_get_family (GSocket *socket)
1640 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1642 return socket->priv->family;
1646 * g_socket_get_socket_type:
1647 * @socket: a #GSocket.
1649 * Gets the socket type of the socket.
1651 * Returns: a #GSocketType
1656 g_socket_get_socket_type (GSocket *socket)
1658 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1660 return socket->priv->type;
1664 * g_socket_get_protocol:
1665 * @socket: a #GSocket.
1667 * Gets the socket protocol id the socket was created with.
1668 * In case the protocol is unknown, -1 is returned.
1670 * Returns: a protocol id, or -1 if unknown
1675 g_socket_get_protocol (GSocket *socket)
1677 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1679 return socket->priv->protocol;
1684 * @socket: a #GSocket.
1686 * Returns the underlying OS socket object. On unix this
1687 * is a socket file descriptor, and on Windows this is
1688 * a Winsock2 SOCKET handle. This may be useful for
1689 * doing platform specific or otherwise unusual operations
1692 * Returns: the file descriptor of the socket.
1697 g_socket_get_fd (GSocket *socket)
1699 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1701 return socket->priv->fd;
1705 * g_socket_get_local_address:
1706 * @socket: a #GSocket.
1707 * @error: #GError for error reporting, or %NULL to ignore.
1709 * Try to get the local address of a bound socket. This is only
1710 * useful if the socket has been bound to a local address,
1711 * either explicitly or implicitly when connecting.
1713 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1714 * Free the returned object with g_object_unref().
1719 g_socket_get_local_address (GSocket *socket,
1722 struct sockaddr_storage buffer;
1723 guint len = sizeof (buffer);
1725 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1727 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1729 int errsv = get_socket_errno ();
1730 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1731 _("could not get local address: %s"), socket_strerror (errsv));
1735 return g_socket_address_new_from_native (&buffer, len);
1739 * g_socket_get_remote_address:
1740 * @socket: a #GSocket.
1741 * @error: #GError for error reporting, or %NULL to ignore.
1743 * Try to get the remove address of a connected socket. This is only
1744 * useful for connection oriented sockets that have been connected.
1746 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1747 * Free the returned object with g_object_unref().
1752 g_socket_get_remote_address (GSocket *socket,
1755 struct sockaddr_storage buffer;
1756 guint len = sizeof (buffer);
1758 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1760 if (socket->priv->connect_pending)
1762 if (!g_socket_check_connect_result (socket, error))
1765 socket->priv->connect_pending = FALSE;
1768 if (!socket->priv->remote_address)
1770 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1772 int errsv = get_socket_errno ();
1773 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1774 _("could not get remote address: %s"), socket_strerror (errsv));
1778 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1781 return g_object_ref (socket->priv->remote_address);
1785 * g_socket_is_connected:
1786 * @socket: a #GSocket.
1788 * Check whether the socket is connected. This is only useful for
1789 * connection-oriented sockets.
1791 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1796 g_socket_is_connected (GSocket *socket)
1798 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1800 return socket->priv->connected;
1805 * @socket: a #GSocket.
1806 * @error: #GError for error reporting, or %NULL to ignore.
1808 * Marks the socket as a server socket, i.e. a socket that is used
1809 * to accept incoming requests using g_socket_accept().
1811 * Before calling this the socket must be bound to a local address using
1814 * To set the maximum amount of outstanding clients, use
1815 * g_socket_set_listen_backlog().
1817 * Returns: %TRUE on success, %FALSE on error.
1822 g_socket_listen (GSocket *socket,
1825 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1827 if (!check_socket (socket, error))
1830 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1832 int errsv = get_socket_errno ();
1834 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1835 _("could not listen: %s"), socket_strerror (errsv));
1839 socket->priv->listening = TRUE;
1846 * @socket: a #GSocket.
1847 * @address: a #GSocketAddress specifying the local address.
1848 * @allow_reuse: whether to allow reusing this address
1849 * @error: #GError for error reporting, or %NULL to ignore.
1851 * When a socket is created it is attached to an address family, but it
1852 * doesn't have an address in this family. g_socket_bind() assigns the
1853 * address (sometimes called name) of the socket.
1855 * It is generally required to bind to a local address before you can
1856 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1857 * In certain situations, you may also want to bind a socket that will be
1858 * used to initiate connections, though this is not normally required.
1860 * If @socket is a TCP socket, then @allow_reuse controls the setting
1861 * of the <literal>SO_REUSEADDR</literal> socket option; normally it
1862 * should be %TRUE for server sockets (sockets that you will
1863 * eventually call g_socket_accept() on), and %FALSE for client
1864 * sockets. (Failing to set this flag on a server socket may cause
1865 * g_socket_bind() to return %G_IO_ERROR_ADDRESS_IN_USE if the server
1866 * program is stopped and then immediately restarted.)
1868 * If @socket is a UDP socket, then @allow_reuse determines whether or
1869 * not other UDP sockets can be bound to the same address at the same
1870 * time. In particular, you can have several UDP sockets bound to the
1871 * same address, and they will all receive all of the multicast and
1872 * broadcast packets sent to that address. (The behavior of unicast
1873 * UDP packets to an address with multiple listeners is not defined.)
1875 * Returns: %TRUE on success, %FALSE on error.
1880 g_socket_bind (GSocket *socket,
1881 GSocketAddress *address,
1882 gboolean reuse_address,
1885 struct sockaddr_storage addr;
1886 gboolean so_reuseaddr;
1888 gboolean so_reuseport;
1891 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1893 if (!check_socket (socket, error))
1896 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1899 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
1900 * sockets, but has nasty side effects we don't want for TCP
1903 * On other platforms, we set SO_REUSEPORT, if it exists, for
1904 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
1905 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
1906 * the desired semantics on UDP (as it does on Linux, although
1907 * Linux has SO_REUSEPORT too as of 3.9).
1911 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1913 so_reuseaddr = !!reuse_address;
1917 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1920 /* Ignore errors here, the only likely error is "not supported", and
1921 * this is a "best effort" thing mainly.
1923 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
1925 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
1928 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1929 g_socket_address_get_native_size (address)) < 0)
1931 int errsv = get_socket_errno ();
1933 G_IO_ERROR, socket_io_error_from_errno (errsv),
1934 _("Error binding to address: %s"), socket_strerror (errsv));
1941 #if !defined(HAVE_IF_NAMETOINDEX) && defined(G_OS_WIN32)
1943 if_nametoindex (const gchar *iface)
1945 PIP_ADAPTER_ADDRESSES addresses = NULL, p;
1946 gulong addresses_len = 0;
1950 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, NULL, &addresses_len);
1951 if (res != NO_ERROR && res != ERROR_BUFFER_OVERFLOW)
1953 if (res == ERROR_NO_DATA)
1960 addresses = g_malloc (addresses_len);
1961 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, addresses, &addresses_len);
1963 if (res != NO_ERROR)
1966 if (res == ERROR_NO_DATA)
1976 if (strcmp (p->AdapterName, iface) == 0)
1992 #define HAVE_IF_NAMETOINDEX 1
1996 g_socket_multicast_group_operation (GSocket *socket,
1997 GInetAddress *group,
1998 gboolean source_specific,
2000 gboolean join_group,
2003 const guint8 *native_addr;
2004 gint optname, result;
2006 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2007 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2008 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2010 if (!check_socket (socket, error))
2013 native_addr = g_inet_address_to_bytes (group);
2014 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2016 #ifdef HAVE_IP_MREQN
2017 struct ip_mreqn mc_req;
2019 struct ip_mreq mc_req;
2022 memset (&mc_req, 0, sizeof (mc_req));
2023 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2025 #ifdef HAVE_IP_MREQN
2027 mc_req.imr_ifindex = if_nametoindex (iface);
2029 mc_req.imr_ifindex = 0; /* Pick any. */
2030 #elif defined(G_OS_WIN32)
2032 mc_req.imr_interface.s_addr = g_htonl (if_nametoindex (iface));
2034 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2036 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2039 if (source_specific)
2041 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2042 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2044 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2046 _("Error joining multicast group: %s") :
2047 _("Error leaving multicast group: %s"),
2048 _("No support for source-specific multicast"));
2053 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2054 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2055 &mc_req, sizeof (mc_req));
2057 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2059 struct ipv6_mreq mc_req_ipv6;
2061 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2062 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2063 #ifdef HAVE_IF_NAMETOINDEX
2065 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2068 mc_req_ipv6.ipv6mr_interface = 0;
2070 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2071 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2072 &mc_req_ipv6, sizeof (mc_req_ipv6));
2075 g_return_val_if_reached (FALSE);
2079 int errsv = get_socket_errno ();
2081 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2083 _("Error joining multicast group: %s") :
2084 _("Error leaving multicast group: %s"),
2085 socket_strerror (errsv));
2093 * g_socket_join_multicast_group:
2094 * @socket: a #GSocket.
2095 * @group: a #GInetAddress specifying the group address to join.
2096 * @iface: (allow-none): Name of the interface to use, or %NULL
2097 * @source_specific: %TRUE if source-specific multicast should be used
2098 * @error: #GError for error reporting, or %NULL to ignore.
2100 * Registers @socket to receive multicast messages sent to @group.
2101 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2102 * been bound to an appropriate interface and port with
2105 * If @iface is %NULL, the system will automatically pick an interface
2106 * to bind to based on @group.
2108 * If @source_specific is %TRUE, source-specific multicast as defined
2109 * in RFC 4604 is used. Note that on older platforms this may fail
2110 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2112 * Returns: %TRUE on success, %FALSE on error.
2117 g_socket_join_multicast_group (GSocket *socket,
2118 GInetAddress *group,
2119 gboolean source_specific,
2123 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2127 * g_socket_leave_multicast_group:
2128 * @socket: a #GSocket.
2129 * @group: a #GInetAddress specifying the group address to leave.
2130 * @iface: (allow-none): Interface used
2131 * @source_specific: %TRUE if source-specific multicast was used
2132 * @error: #GError for error reporting, or %NULL to ignore.
2134 * Removes @socket from the multicast group defined by @group, @iface,
2135 * and @source_specific (which must all have the same values they had
2136 * when you joined the group).
2138 * @socket remains bound to its address and port, and can still receive
2139 * unicast messages after calling this.
2141 * Returns: %TRUE on success, %FALSE on error.
2146 g_socket_leave_multicast_group (GSocket *socket,
2147 GInetAddress *group,
2148 gboolean source_specific,
2152 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2156 * g_socket_speaks_ipv4:
2157 * @socket: a #GSocket
2159 * Checks if a socket is capable of speaking IPv4.
2161 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2162 * and under some combinations of circumstances IPv6 sockets are also
2163 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2166 * No other types of sockets are currently considered as being capable
2169 * Returns: %TRUE if this socket can be used with IPv4.
2174 g_socket_speaks_ipv4 (GSocket *socket)
2176 switch (socket->priv->family)
2178 case G_SOCKET_FAMILY_IPV4:
2181 case G_SOCKET_FAMILY_IPV6:
2182 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2186 if (!g_socket_get_option (socket,
2187 IPPROTO_IPV6, IPV6_V6ONLY,
2204 * @socket: a #GSocket.
2205 * @cancellable: (allow-none): a %GCancellable or %NULL
2206 * @error: #GError for error reporting, or %NULL to ignore.
2208 * Accept incoming connections on a connection-based socket. This removes
2209 * the first outstanding connection request from the listening socket and
2210 * creates a #GSocket object for it.
2212 * The @socket must be bound to a local address with g_socket_bind() and
2213 * must be listening for incoming connections (g_socket_listen()).
2215 * If there are no outstanding connections then the operation will block
2216 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2217 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2219 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2220 * Free the returned object with g_object_unref().
2225 g_socket_accept (GSocket *socket,
2226 GCancellable *cancellable,
2229 GSocket *new_socket;
2232 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2234 if (!check_socket (socket, error))
2239 if (socket->priv->blocking &&
2240 !g_socket_condition_wait (socket,
2241 G_IO_IN, cancellable, error))
2244 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2246 int errsv = get_socket_errno ();
2248 win32_unset_event_mask (socket, FD_ACCEPT);
2253 if (socket->priv->blocking)
2255 #ifdef WSAEWOULDBLOCK
2256 if (errsv == WSAEWOULDBLOCK)
2259 if (errsv == EWOULDBLOCK ||
2265 g_set_error (error, G_IO_ERROR,
2266 socket_io_error_from_errno (errsv),
2267 _("Error accepting connection: %s"), socket_strerror (errsv));
2273 win32_unset_event_mask (socket, FD_ACCEPT);
2277 /* The socket inherits the accepting sockets event mask and even object,
2278 we need to remove that */
2279 WSAEventSelect (ret, NULL, 0);
2285 /* We always want to set close-on-exec to protect users. If you
2286 need to so some weird inheritance to exec you can re-enable this
2287 using lower level hacks with g_socket_get_fd(). */
2288 flags = fcntl (ret, F_GETFD, 0);
2290 (flags & FD_CLOEXEC) == 0)
2292 flags |= FD_CLOEXEC;
2293 fcntl (ret, F_SETFD, flags);
2298 new_socket = g_socket_new_from_fd (ret, error);
2299 if (new_socket == NULL)
2308 new_socket->priv->protocol = socket->priv->protocol;
2315 * @socket: a #GSocket.
2316 * @address: a #GSocketAddress specifying the remote address.
2317 * @cancellable: (allow-none): a %GCancellable or %NULL
2318 * @error: #GError for error reporting, or %NULL to ignore.
2320 * Connect the socket to the specified remote address.
2322 * For connection oriented socket this generally means we attempt to make
2323 * a connection to the @address. For a connection-less socket it sets
2324 * the default address for g_socket_send() and discards all incoming datagrams
2325 * from other sources.
2327 * Generally connection oriented sockets can only connect once, but
2328 * connection-less sockets can connect multiple times to change the
2331 * If the connect call needs to do network I/O it will block, unless
2332 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2333 * and the user can be notified of the connection finishing by waiting
2334 * for the G_IO_OUT condition. The result of the connection must then be
2335 * checked with g_socket_check_connect_result().
2337 * Returns: %TRUE if connected, %FALSE on error.
2342 g_socket_connect (GSocket *socket,
2343 GSocketAddress *address,
2344 GCancellable *cancellable,
2347 struct sockaddr_storage buffer;
2349 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2351 if (!check_socket (socket, error))
2354 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2357 if (socket->priv->remote_address)
2358 g_object_unref (socket->priv->remote_address);
2359 socket->priv->remote_address = g_object_ref (address);
2363 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2364 g_socket_address_get_native_size (address)) < 0)
2366 int errsv = get_socket_errno ();
2372 if (errsv == EINPROGRESS)
2374 if (errsv == WSAEWOULDBLOCK)
2377 if (socket->priv->blocking)
2379 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2381 if (g_socket_check_connect_result (socket, error))
2387 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2388 _("Connection in progress"));
2389 socket->priv->connect_pending = TRUE;
2393 g_set_error_literal (error, G_IO_ERROR,
2394 socket_io_error_from_errno (errsv),
2395 socket_strerror (errsv));
2402 win32_unset_event_mask (socket, FD_CONNECT);
2404 socket->priv->connected = TRUE;
2410 * g_socket_check_connect_result:
2411 * @socket: a #GSocket
2412 * @error: #GError for error reporting, or %NULL to ignore.
2414 * Checks and resets the pending connect error for the socket.
2415 * This is used to check for errors when g_socket_connect() is
2416 * used in non-blocking mode.
2418 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2423 g_socket_check_connect_result (GSocket *socket,
2428 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2430 if (!check_socket (socket, error))
2433 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
2435 g_prefix_error (error, _("Unable to get pending error: "));
2441 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2442 socket_strerror (value));
2443 if (socket->priv->remote_address)
2445 g_object_unref (socket->priv->remote_address);
2446 socket->priv->remote_address = NULL;
2451 socket->priv->connected = TRUE;
2456 * g_socket_get_available_bytes:
2457 * @socket: a #GSocket
2459 * Get the amount of data pending in the OS input buffer.
2461 * If @socket is a UDP or SCTP socket, this will return the size of
2462 * just the next packet, even if additional packets are buffered after
2465 * Note that on Windows, this function is rather inefficient in the
2466 * UDP case, and so if you know any plausible upper bound on the size
2467 * of the incoming packet, it is better to just do a
2468 * g_socket_receive() with a buffer of that size, rather than calling
2469 * g_socket_get_available_bytes() first and then doing a receive of
2470 * exactly the right size.
2472 * Returns: the number of bytes that can be read from the socket
2473 * without blocking or truncating, or -1 on error.
2478 g_socket_get_available_bytes (GSocket *socket)
2481 const gint bufsize = 64 * 1024;
2482 static guchar *buf = NULL;
2486 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2488 #if defined (SO_NREAD)
2489 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
2491 #elif !defined (G_OS_WIN32)
2492 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2495 if (G_UNLIKELY (g_once_init_enter (&buf)))
2496 g_once_init_leave (&buf, g_malloc (bufsize));
2498 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
2506 * @socket: a #GSocket
2507 * @buffer: (array length=size) (element-type guint8): a buffer to
2508 * read data into (which should be at least @size bytes long).
2509 * @size: the number of bytes you want to read from the socket
2510 * @cancellable: (allow-none): a %GCancellable or %NULL
2511 * @error: #GError for error reporting, or %NULL to ignore.
2513 * Receive data (up to @size bytes) from a socket. This is mainly used by
2514 * connection-oriented sockets; it is identical to g_socket_receive_from()
2515 * with @address set to %NULL.
2517 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2518 * g_socket_receive() will always read either 0 or 1 complete messages from
2519 * the socket. If the received message is too large to fit in @buffer, then
2520 * the data beyond @size bytes will be discarded, without any explicit
2521 * indication that this has occurred.
2523 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2524 * number of bytes, up to @size. If more than @size bytes have been
2525 * received, the additional data will be returned in future calls to
2526 * g_socket_receive().
2528 * If the socket is in blocking mode the call will block until there
2529 * is some data to receive, the connection is closed, or there is an
2530 * error. If there is no data available and the socket is in
2531 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2532 * returned. To be notified when data is available, wait for the
2533 * %G_IO_IN condition.
2535 * On error -1 is returned and @error is set accordingly.
2537 * Returns: Number of bytes read, or 0 if the connection was closed by
2538 * the peer, or -1 on error
2543 g_socket_receive (GSocket *socket,
2546 GCancellable *cancellable,
2549 return g_socket_receive_with_blocking (socket, buffer, size,
2550 socket->priv->blocking,
2551 cancellable, error);
2555 * g_socket_receive_with_blocking:
2556 * @socket: a #GSocket
2557 * @buffer: (array length=size) (element-type guint8): a buffer to
2558 * read data into (which should be at least @size bytes long).
2559 * @size: the number of bytes you want to read from the socket
2560 * @blocking: whether to do blocking or non-blocking I/O
2561 * @cancellable: (allow-none): a %GCancellable or %NULL
2562 * @error: #GError for error reporting, or %NULL to ignore.
2564 * This behaves exactly the same as g_socket_receive(), except that
2565 * the choice of blocking or non-blocking behavior is determined by
2566 * the @blocking argument rather than by @socket's properties.
2568 * Returns: Number of bytes read, or 0 if the connection was closed by
2569 * the peer, or -1 on error
2574 g_socket_receive_with_blocking (GSocket *socket,
2578 GCancellable *cancellable,
2583 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2585 if (!check_socket (socket, error))
2588 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2594 !g_socket_condition_wait (socket,
2595 G_IO_IN, cancellable, error))
2598 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2600 int errsv = get_socket_errno ();
2607 #ifdef WSAEWOULDBLOCK
2608 if (errsv == WSAEWOULDBLOCK)
2611 if (errsv == EWOULDBLOCK ||
2617 win32_unset_event_mask (socket, FD_READ);
2619 g_set_error (error, G_IO_ERROR,
2620 socket_io_error_from_errno (errsv),
2621 _("Error receiving data: %s"), socket_strerror (errsv));
2625 win32_unset_event_mask (socket, FD_READ);
2634 * g_socket_receive_from:
2635 * @socket: a #GSocket
2636 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2638 * @buffer: (array length=size) (element-type guint8): a buffer to
2639 * read data into (which should be at least @size bytes long).
2640 * @size: the number of bytes you want to read from the socket
2641 * @cancellable: (allow-none): a %GCancellable or %NULL
2642 * @error: #GError for error reporting, or %NULL to ignore.
2644 * Receive data (up to @size bytes) from a socket.
2646 * If @address is non-%NULL then @address will be set equal to the
2647 * source address of the received packet.
2648 * @address is owned by the caller.
2650 * See g_socket_receive() for additional information.
2652 * Returns: Number of bytes read, or 0 if the connection was closed by
2653 * the peer, or -1 on error
2658 g_socket_receive_from (GSocket *socket,
2659 GSocketAddress **address,
2662 GCancellable *cancellable,
2670 return g_socket_receive_message (socket,
2678 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2679 * one, which can be confusing and annoying. So if possible, we want
2680 * to suppress the signal entirely.
2683 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2685 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2690 * @socket: a #GSocket
2691 * @buffer: (array length=size) (element-type guint8): the buffer
2692 * containing the data to send.
2693 * @size: the number of bytes to send
2694 * @cancellable: (allow-none): a %GCancellable or %NULL
2695 * @error: #GError for error reporting, or %NULL to ignore.
2697 * Tries to send @size bytes from @buffer on the socket. This is
2698 * mainly used by connection-oriented sockets; it is identical to
2699 * g_socket_send_to() with @address set to %NULL.
2701 * If the socket is in blocking mode the call will block until there is
2702 * space for the data in the socket queue. If there is no space available
2703 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2704 * will be returned. To be notified when space is available, wait for the
2705 * %G_IO_OUT condition. Note though that you may still receive
2706 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2707 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2708 * very common due to the way the underlying APIs work.)
2710 * On error -1 is returned and @error is set accordingly.
2712 * Returns: Number of bytes written (which may be less than @size), or -1
2718 g_socket_send (GSocket *socket,
2719 const gchar *buffer,
2721 GCancellable *cancellable,
2724 return g_socket_send_with_blocking (socket, buffer, size,
2725 socket->priv->blocking,
2726 cancellable, error);
2730 * g_socket_send_with_blocking:
2731 * @socket: a #GSocket
2732 * @buffer: (array length=size) (element-type guint8): the buffer
2733 * containing the data to send.
2734 * @size: the number of bytes to send
2735 * @blocking: whether to do blocking or non-blocking I/O
2736 * @cancellable: (allow-none): a %GCancellable or %NULL
2737 * @error: #GError for error reporting, or %NULL to ignore.
2739 * This behaves exactly the same as g_socket_send(), except that
2740 * the choice of blocking or non-blocking behavior is determined by
2741 * the @blocking argument rather than by @socket's properties.
2743 * Returns: Number of bytes written (which may be less than @size), or -1
2749 g_socket_send_with_blocking (GSocket *socket,
2750 const gchar *buffer,
2753 GCancellable *cancellable,
2758 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2760 if (!check_socket (socket, error))
2763 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2769 !g_socket_condition_wait (socket,
2770 G_IO_OUT, cancellable, error))
2773 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2775 int errsv = get_socket_errno ();
2780 #ifdef WSAEWOULDBLOCK
2781 if (errsv == WSAEWOULDBLOCK)
2782 win32_unset_event_mask (socket, FD_WRITE);
2787 #ifdef WSAEWOULDBLOCK
2788 if (errsv == WSAEWOULDBLOCK)
2791 if (errsv == EWOULDBLOCK ||
2797 g_set_error (error, G_IO_ERROR,
2798 socket_io_error_from_errno (errsv),
2799 _("Error sending data: %s"), socket_strerror (errsv));
2810 * @socket: a #GSocket
2811 * @address: (allow-none): a #GSocketAddress, or %NULL
2812 * @buffer: (array length=size) (element-type guint8): the buffer
2813 * containing the data to send.
2814 * @size: the number of bytes to send
2815 * @cancellable: (allow-none): a %GCancellable or %NULL
2816 * @error: #GError for error reporting, or %NULL to ignore.
2818 * Tries to send @size bytes from @buffer to @address. If @address is
2819 * %NULL then the message is sent to the default receiver (set by
2820 * g_socket_connect()).
2822 * See g_socket_send() for additional information.
2824 * Returns: Number of bytes written (which may be less than @size), or -1
2830 g_socket_send_to (GSocket *socket,
2831 GSocketAddress *address,
2832 const gchar *buffer,
2834 GCancellable *cancellable,
2842 return g_socket_send_message (socket,
2852 * g_socket_shutdown:
2853 * @socket: a #GSocket
2854 * @shutdown_read: whether to shut down the read side
2855 * @shutdown_write: whether to shut down the write side
2856 * @error: #GError for error reporting, or %NULL to ignore.
2858 * Shut down part of a full-duplex connection.
2860 * If @shutdown_read is %TRUE then the receiving side of the connection
2861 * is shut down, and further reading is disallowed.
2863 * If @shutdown_write is %TRUE then the sending side of the connection
2864 * is shut down, and further writing is disallowed.
2866 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2868 * One example where this is used is graceful disconnect for TCP connections
2869 * where you close the sending side, then wait for the other side to close
2870 * the connection, thus ensuring that the other side saw all sent data.
2872 * Returns: %TRUE on success, %FALSE on error
2877 g_socket_shutdown (GSocket *socket,
2878 gboolean shutdown_read,
2879 gboolean shutdown_write,
2884 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2886 if (!check_socket (socket, error))
2890 if (!shutdown_read && !shutdown_write)
2894 if (shutdown_read && shutdown_write)
2896 else if (shutdown_read)
2901 if (shutdown_read && shutdown_write)
2903 else if (shutdown_read)
2909 if (shutdown (socket->priv->fd, how) != 0)
2911 int errsv = get_socket_errno ();
2912 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2913 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2917 if (shutdown_read && shutdown_write)
2918 socket->priv->connected = FALSE;
2925 * @socket: a #GSocket
2926 * @error: #GError for error reporting, or %NULL to ignore.
2928 * Closes the socket, shutting down any active connection.
2930 * Closing a socket does not wait for all outstanding I/O operations
2931 * to finish, so the caller should not rely on them to be guaranteed
2932 * to complete even if the close returns with no error.
2934 * Once the socket is closed, all other operations will return
2935 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2938 * Sockets will be automatically closed when the last reference
2939 * is dropped, but you might want to call this function to make sure
2940 * resources are released as early as possible.
2942 * Beware that due to the way that TCP works, it is possible for
2943 * recently-sent data to be lost if either you close a socket while the
2944 * %G_IO_IN condition is set, or else if the remote connection tries to
2945 * send something to you after you close the socket but before it has
2946 * finished reading all of the data you sent. There is no easy generic
2947 * way to avoid this problem; the easiest fix is to design the network
2948 * protocol such that the client will never send data "out of turn".
2949 * Another solution is for the server to half-close the connection by
2950 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2951 * and then wait for the client to notice this and close its side of the
2952 * connection, after which the server can safely call g_socket_close().
2953 * (This is what #GTcpConnection does if you call
2954 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2955 * only works if the client will close its connection after the server
2958 * Returns: %TRUE on success, %FALSE on error
2963 g_socket_close (GSocket *socket,
2968 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2970 if (socket->priv->closed)
2971 return TRUE; /* Multiple close not an error */
2973 if (!check_socket (socket, error))
2979 res = closesocket (socket->priv->fd);
2981 res = close (socket->priv->fd);
2985 int errsv = get_socket_errno ();
2990 g_set_error (error, G_IO_ERROR,
2991 socket_io_error_from_errno (errsv),
2992 _("Error closing socket: %s"),
2993 socket_strerror (errsv));
2999 socket->priv->connected = FALSE;
3000 socket->priv->closed = TRUE;
3001 if (socket->priv->remote_address)
3003 g_object_unref (socket->priv->remote_address);
3004 socket->priv->remote_address = NULL;
3011 * g_socket_is_closed:
3012 * @socket: a #GSocket
3014 * Checks whether a socket is closed.
3016 * Returns: %TRUE if socket is closed, %FALSE otherwise
3021 g_socket_is_closed (GSocket *socket)
3023 return socket->priv->closed;
3027 /* Broken source, used on errors */
3029 broken_dispatch (GSource *source,
3030 GSourceFunc callback,
3036 static GSourceFuncs broken_funcs =
3045 network_events_for_condition (GIOCondition condition)
3049 if (condition & G_IO_IN)
3050 event_mask |= (FD_READ | FD_ACCEPT);
3051 if (condition & G_IO_OUT)
3052 event_mask |= (FD_WRITE | FD_CONNECT);
3053 event_mask |= FD_CLOSE;
3059 ensure_event (GSocket *socket)
3061 if (socket->priv->event == WSA_INVALID_EVENT)
3062 socket->priv->event = WSACreateEvent();
3066 update_select_events (GSocket *socket)
3073 ensure_event (socket);
3076 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3079 event_mask |= network_events_for_condition (*ptr);
3082 if (event_mask != socket->priv->selected_events)
3084 /* If no events selected, disable event so we can unset
3087 if (event_mask == 0)
3090 event = socket->priv->event;
3092 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3093 socket->priv->selected_events = event_mask;
3098 add_condition_watch (GSocket *socket,
3099 GIOCondition *condition)
3101 g_mutex_lock (&socket->priv->win32_source_lock);
3102 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3104 socket->priv->requested_conditions =
3105 g_list_prepend (socket->priv->requested_conditions, condition);
3107 update_select_events (socket);
3108 g_mutex_unlock (&socket->priv->win32_source_lock);
3112 remove_condition_watch (GSocket *socket,
3113 GIOCondition *condition)
3115 g_mutex_lock (&socket->priv->win32_source_lock);
3116 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3118 socket->priv->requested_conditions =
3119 g_list_remove (socket->priv->requested_conditions, condition);
3121 update_select_events (socket);
3122 g_mutex_unlock (&socket->priv->win32_source_lock);
3126 update_condition (GSocket *socket)
3128 WSANETWORKEVENTS events;
3129 GIOCondition condition;
3131 if (WSAEnumNetworkEvents (socket->priv->fd,
3132 socket->priv->event,
3135 socket->priv->current_events |= events.lNetworkEvents;
3136 if (events.lNetworkEvents & FD_WRITE &&
3137 events.iErrorCode[FD_WRITE_BIT] != 0)
3138 socket->priv->current_errors |= FD_WRITE;
3139 if (events.lNetworkEvents & FD_CONNECT &&
3140 events.iErrorCode[FD_CONNECT_BIT] != 0)
3141 socket->priv->current_errors |= FD_CONNECT;
3145 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3146 condition |= G_IO_IN;
3148 if (socket->priv->current_events & FD_CLOSE)
3150 int r, errsv, buffer;
3152 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3154 errsv = get_socket_errno ();
3157 (r < 0 && errsv == WSAENOTCONN))
3158 condition |= G_IO_IN;
3160 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3161 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3162 condition |= G_IO_HUP;
3164 condition |= G_IO_ERR;
3167 if (socket->priv->closed)
3168 condition |= G_IO_HUP;
3170 /* Never report both G_IO_OUT and HUP, these are
3171 mutually exclusive (can't write to a closed socket) */
3172 if ((condition & G_IO_HUP) == 0 &&
3173 socket->priv->current_events & FD_WRITE)
3175 if (socket->priv->current_errors & FD_WRITE)
3176 condition |= G_IO_ERR;
3178 condition |= G_IO_OUT;
3182 if (socket->priv->current_events & FD_CONNECT)
3184 if (socket->priv->current_errors & FD_CONNECT)
3185 condition |= (G_IO_HUP | G_IO_ERR);
3187 condition |= G_IO_OUT;
3199 GIOCondition condition;
3200 GCancellable *cancellable;
3201 GPollFD cancel_pollfd;
3202 gint64 timeout_time;
3206 socket_source_prepare (GSource *source,
3209 GSocketSource *socket_source = (GSocketSource *)source;
3211 if (g_cancellable_is_cancelled (socket_source->cancellable))
3214 if (socket_source->timeout_time)
3218 now = g_source_get_time (source);
3219 /* Round up to ensure that we don't try again too early */
3220 *timeout = (socket_source->timeout_time - now + 999) / 1000;
3223 socket_source->socket->priv->timed_out = TRUE;
3232 socket_source->pollfd.revents = update_condition (socket_source->socket);
3235 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
3242 socket_source_check (GSource *source)
3246 return socket_source_prepare (source, &timeout);
3250 socket_source_dispatch (GSource *source,
3251 GSourceFunc callback,
3254 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3255 GSocketSource *socket_source = (GSocketSource *)source;
3256 GSocket *socket = socket_source->socket;
3260 socket_source->pollfd.revents = update_condition (socket_source->socket);
3262 if (socket_source->socket->priv->timed_out)
3263 socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
3265 ret = (*func) (socket,
3266 socket_source->pollfd.revents & socket_source->condition,
3269 if (socket->priv->timeout)
3270 socket_source->timeout_time = g_get_monotonic_time () +
3271 socket->priv->timeout * 1000000;
3274 socket_source->timeout_time = 0;
3280 socket_source_finalize (GSource *source)
3282 GSocketSource *socket_source = (GSocketSource *)source;
3285 socket = socket_source->socket;
3288 remove_condition_watch (socket, &socket_source->condition);
3291 g_object_unref (socket);
3293 if (socket_source->cancellable)
3295 g_cancellable_release_fd (socket_source->cancellable);
3296 g_object_unref (socket_source->cancellable);
3301 socket_source_closure_callback (GSocket *socket,
3302 GIOCondition condition,
3305 GClosure *closure = data;
3307 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3308 GValue result_value = G_VALUE_INIT;
3311 g_value_init (&result_value, G_TYPE_BOOLEAN);
3313 g_value_init (¶ms[0], G_TYPE_SOCKET);
3314 g_value_set_object (¶ms[0], socket);
3315 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
3316 g_value_set_flags (¶ms[1], condition);
3318 g_closure_invoke (closure, &result_value, 2, params, NULL);
3320 result = g_value_get_boolean (&result_value);
3321 g_value_unset (&result_value);
3322 g_value_unset (¶ms[0]);
3323 g_value_unset (¶ms[1]);
3328 static GSourceFuncs socket_source_funcs =
3330 socket_source_prepare,
3331 socket_source_check,
3332 socket_source_dispatch,
3333 socket_source_finalize,
3334 (GSourceFunc)socket_source_closure_callback,
3338 socket_source_new (GSocket *socket,
3339 GIOCondition condition,
3340 GCancellable *cancellable)
3343 GSocketSource *socket_source;
3346 ensure_event (socket);
3348 if (socket->priv->event == WSA_INVALID_EVENT)
3350 g_warning ("Failed to create WSAEvent");
3351 return g_source_new (&broken_funcs, sizeof (GSource));
3355 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
3357 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3358 g_source_set_name (source, "GSocket");
3359 socket_source = (GSocketSource *)source;
3361 socket_source->socket = g_object_ref (socket);
3362 socket_source->condition = condition;
3364 if (g_cancellable_make_pollfd (cancellable,
3365 &socket_source->cancel_pollfd))
3367 socket_source->cancellable = g_object_ref (cancellable);
3368 g_source_add_poll (source, &socket_source->cancel_pollfd);
3372 add_condition_watch (socket, &socket_source->condition);
3373 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3375 socket_source->pollfd.fd = socket->priv->fd;
3378 socket_source->pollfd.events = condition;
3379 socket_source->pollfd.revents = 0;
3380 g_source_add_poll (source, &socket_source->pollfd);
3382 if (socket->priv->timeout)
3383 socket_source->timeout_time = g_get_monotonic_time () +
3384 socket->priv->timeout * 1000000;
3387 socket_source->timeout_time = 0;
3393 * g_socket_create_source: (skip)
3394 * @socket: a #GSocket
3395 * @condition: a #GIOCondition mask to monitor
3396 * @cancellable: (allow-none): a %GCancellable or %NULL
3398 * Creates a %GSource that can be attached to a %GMainContext to monitor
3399 * for the availibility of the specified @condition on the socket.
3401 * The callback on the source is of the #GSocketSourceFunc type.
3403 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3404 * these conditions will always be reported output if they are true.
3406 * @cancellable if not %NULL can be used to cancel the source, which will
3407 * cause the source to trigger, reporting the current condition (which
3408 * is likely 0 unless cancellation happened at the same time as a
3409 * condition change). You can check for this in the callback using
3410 * g_cancellable_is_cancelled().
3412 * If @socket has a timeout set, and it is reached before @condition
3413 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3414 * %G_IO_OUT depending on @condition. However, @socket will have been
3415 * marked as having had a timeout, and so the next #GSocket I/O method
3416 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3418 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3423 g_socket_create_source (GSocket *socket,
3424 GIOCondition condition,
3425 GCancellable *cancellable)
3427 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3429 return socket_source_new (socket, condition, cancellable);
3433 * g_socket_condition_check:
3434 * @socket: a #GSocket
3435 * @condition: a #GIOCondition mask to check
3437 * Checks on the readiness of @socket to perform operations.
3438 * The operations specified in @condition are checked for and masked
3439 * against the currently-satisfied conditions on @socket. The result
3442 * Note that on Windows, it is possible for an operation to return
3443 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3444 * g_socket_condition_check() has claimed that the socket is ready for
3445 * writing. Rather than calling g_socket_condition_check() and then
3446 * writing to the socket if it succeeds, it is generally better to
3447 * simply try writing to the socket right away, and try again later if
3448 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3450 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3451 * these conditions will always be set in the output if they are true.
3453 * This call never blocks.
3455 * Returns: the @GIOCondition mask of the current state
3460 g_socket_condition_check (GSocket *socket,
3461 GIOCondition condition)
3463 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3465 if (!check_socket (socket, NULL))
3470 GIOCondition current_condition;
3472 condition |= G_IO_ERR | G_IO_HUP;
3474 add_condition_watch (socket, &condition);
3475 current_condition = update_condition (socket);
3476 remove_condition_watch (socket, &condition);
3477 return condition & current_condition;
3483 poll_fd.fd = socket->priv->fd;
3484 poll_fd.events = condition;
3485 poll_fd.revents = 0;
3488 result = g_poll (&poll_fd, 1, 0);
3489 while (result == -1 && get_socket_errno () == EINTR);
3491 return poll_fd.revents;
3497 * g_socket_condition_wait:
3498 * @socket: a #GSocket
3499 * @condition: a #GIOCondition mask to wait for
3500 * @cancellable: (allow-none): a #GCancellable, or %NULL
3501 * @error: a #GError pointer, or %NULL
3503 * Waits for @condition to become true on @socket. When the condition
3504 * is met, %TRUE is returned.
3506 * If @cancellable is cancelled before the condition is met, or if the
3507 * socket has a timeout set and it is reached before the condition is
3508 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3509 * the appropriate value (%G_IO_ERROR_CANCELLED or
3510 * %G_IO_ERROR_TIMED_OUT).
3512 * See also g_socket_condition_timed_wait().
3514 * Returns: %TRUE if the condition was met, %FALSE otherwise
3519 g_socket_condition_wait (GSocket *socket,
3520 GIOCondition condition,
3521 GCancellable *cancellable,
3524 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3526 return g_socket_condition_timed_wait (socket, condition, -1,
3527 cancellable, error);
3531 * g_socket_condition_timed_wait:
3532 * @socket: a #GSocket
3533 * @condition: a #GIOCondition mask to wait for
3534 * @timeout: the maximum time (in microseconds) to wait, or -1
3535 * @cancellable: (allow-none): a #GCancellable, or %NULL
3536 * @error: a #GError pointer, or %NULL
3538 * Waits for up to @timeout microseconds for @condition to become true
3539 * on @socket. If the condition is met, %TRUE is returned.
3541 * If @cancellable is cancelled before the condition is met, or if
3542 * @timeout (or the socket's #GSocket:timeout) is reached before the
3543 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3544 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3545 * %G_IO_ERROR_TIMED_OUT).
3547 * If you don't want a timeout, use g_socket_condition_wait().
3548 * (Alternatively, you can pass -1 for @timeout.)
3550 * Note that although @timeout is in microseconds for consistency with
3551 * other GLib APIs, this function actually only has millisecond
3552 * resolution, and the behavior is undefined if @timeout is not an
3553 * exact number of milliseconds.
3555 * Returns: %TRUE if the condition was met, %FALSE otherwise
3560 g_socket_condition_timed_wait (GSocket *socket,
3561 GIOCondition condition,
3563 GCancellable *cancellable,
3568 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3570 if (!check_socket (socket, error))
3573 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3576 if (socket->priv->timeout &&
3577 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3578 timeout = socket->priv->timeout * 1000;
3579 else if (timeout != -1)
3580 timeout = timeout / 1000;
3582 start_time = g_get_monotonic_time ();
3586 GIOCondition current_condition;
3592 /* Always check these */
3593 condition |= G_IO_ERR | G_IO_HUP;
3595 add_condition_watch (socket, &condition);
3598 events[num_events++] = socket->priv->event;
3600 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3601 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3604 timeout = WSA_INFINITE;
3606 current_condition = update_condition (socket);
3607 while ((condition & current_condition) == 0)
3609 res = WSAWaitForMultipleEvents (num_events, events,
3610 FALSE, timeout, FALSE);
3611 if (res == WSA_WAIT_FAILED)
3613 int errsv = get_socket_errno ();
3615 g_set_error (error, G_IO_ERROR,
3616 socket_io_error_from_errno (errsv),
3617 _("Waiting for socket condition: %s"),
3618 socket_strerror (errsv));
3621 else if (res == WSA_WAIT_TIMEOUT)
3623 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3624 _("Socket I/O timed out"));
3628 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3631 current_condition = update_condition (socket);
3633 if (timeout != WSA_INFINITE)
3635 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3640 remove_condition_watch (socket, &condition);
3642 g_cancellable_release_fd (cancellable);
3644 return (condition & current_condition) != 0;
3652 poll_fd[0].fd = socket->priv->fd;
3653 poll_fd[0].events = condition;
3656 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3661 result = g_poll (poll_fd, num, timeout);
3662 if (result != -1 || errno != EINTR)
3667 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3674 g_cancellable_release_fd (cancellable);
3678 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3679 _("Socket I/O timed out"));
3683 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3689 * g_socket_send_message:
3690 * @socket: a #GSocket
3691 * @address: (allow-none): a #GSocketAddress, or %NULL
3692 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3693 * @num_vectors: the number of elements in @vectors, or -1
3694 * @messages: (array length=num_messages) (allow-none): a pointer to an
3695 * array of #GSocketControlMessages, or %NULL.
3696 * @num_messages: number of elements in @messages, or -1.
3697 * @flags: an int containing #GSocketMsgFlags flags
3698 * @cancellable: (allow-none): a %GCancellable or %NULL
3699 * @error: #GError for error reporting, or %NULL to ignore.
3701 * Send data to @address on @socket. This is the most complicated and
3702 * fully-featured version of this call. For easier use, see
3703 * g_socket_send() and g_socket_send_to().
3705 * If @address is %NULL then the message is sent to the default receiver
3706 * (set by g_socket_connect()).
3708 * @vectors must point to an array of #GOutputVector structs and
3709 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3710 * then @vectors is assumed to be terminated by a #GOutputVector with a
3711 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3712 * that the sent data will be gathered from. Using multiple
3713 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3714 * data from multiple sources into a single buffer, and more
3715 * network-efficient than making multiple calls to g_socket_send().
3717 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3718 * #GSocketControlMessage instances. These correspond to the control
3719 * messages to be sent on the socket.
3720 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3723 * @flags modify how the message is sent. The commonly available arguments
3724 * for this are available in the #GSocketMsgFlags enum, but the
3725 * values there are the same as the system values, and the flags
3726 * are passed in as-is, so you can pass in system-specific flags too.
3728 * If the socket is in blocking mode the call will block until there is
3729 * space for the data in the socket queue. If there is no space available
3730 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3731 * will be returned. To be notified when space is available, wait for the
3732 * %G_IO_OUT condition. Note though that you may still receive
3733 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3734 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3735 * very common due to the way the underlying APIs work.)
3737 * On error -1 is returned and @error is set accordingly.
3739 * Returns: Number of bytes written (which may be less than @size), or -1
3745 g_socket_send_message (GSocket *socket,
3746 GSocketAddress *address,
3747 GOutputVector *vectors,
3749 GSocketControlMessage **messages,
3752 GCancellable *cancellable,
3755 GOutputVector one_vector;
3758 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3760 if (!check_socket (socket, error))
3763 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3766 if (num_vectors == -1)
3768 for (num_vectors = 0;
3769 vectors[num_vectors].buffer != NULL;
3774 if (num_messages == -1)
3776 for (num_messages = 0;
3777 messages != NULL && messages[num_messages] != NULL;
3782 if (num_vectors == 0)
3786 one_vector.buffer = &zero;
3787 one_vector.size = 1;
3789 vectors = &one_vector;
3802 msg.msg_namelen = g_socket_address_get_native_size (address);
3803 msg.msg_name = g_alloca (msg.msg_namelen);
3804 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3809 msg.msg_name = NULL;
3810 msg.msg_namelen = 0;
3815 /* this entire expression will be evaluated at compile time */
3816 if (sizeof *msg.msg_iov == sizeof *vectors &&
3817 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3818 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3819 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3820 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3821 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3822 G_STRUCT_OFFSET (GOutputVector, size))
3823 /* ABI is compatible */
3825 msg.msg_iov = (struct iovec *) vectors;
3826 msg.msg_iovlen = num_vectors;
3829 /* ABI is incompatible */
3833 msg.msg_iov = g_newa (struct iovec, num_vectors);
3834 for (i = 0; i < num_vectors; i++)
3836 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3837 msg.msg_iov[i].iov_len = vectors[i].size;
3839 msg.msg_iovlen = num_vectors;
3845 struct cmsghdr *cmsg;
3848 msg.msg_controllen = 0;
3849 for (i = 0; i < num_messages; i++)
3850 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3852 if (msg.msg_controllen == 0)
3853 msg.msg_control = NULL;
3856 msg.msg_control = g_alloca (msg.msg_controllen);
3857 memset (msg.msg_control, '\0', msg.msg_controllen);
3860 cmsg = CMSG_FIRSTHDR (&msg);
3861 for (i = 0; i < num_messages; i++)
3863 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3864 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3865 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3866 g_socket_control_message_serialize (messages[i],
3868 cmsg = CMSG_NXTHDR (&msg, cmsg);
3870 g_assert (cmsg == NULL);
3875 if (socket->priv->blocking &&
3876 !g_socket_condition_wait (socket,
3877 G_IO_OUT, cancellable, error))
3880 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3883 int errsv = get_socket_errno ();
3888 if (socket->priv->blocking &&
3889 (errsv == EWOULDBLOCK ||
3893 g_set_error (error, G_IO_ERROR,
3894 socket_io_error_from_errno (errsv),
3895 _("Error sending message: %s"), socket_strerror (errsv));
3906 struct sockaddr_storage addr;
3913 /* Win32 doesn't support control messages.
3914 Actually this is possible for raw and datagram sockets
3915 via WSASendMessage on Vista or later, but that doesn't
3917 if (num_messages != 0)
3919 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3920 _("GSocketControlMessage not supported on Windows"));
3925 bufs = g_newa (WSABUF, num_vectors);
3926 for (i = 0; i < num_vectors; i++)
3928 bufs[i].buf = (char *)vectors[i].buffer;
3929 bufs[i].len = (gulong)vectors[i].size;
3933 addrlen = 0; /* Avoid warning */
3936 addrlen = g_socket_address_get_native_size (address);
3937 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3943 if (socket->priv->blocking &&
3944 !g_socket_condition_wait (socket,
3945 G_IO_OUT, cancellable, error))
3949 result = WSASendTo (socket->priv->fd,
3952 (const struct sockaddr *)&addr, addrlen,
3955 result = WSASend (socket->priv->fd,
3962 int errsv = get_socket_errno ();
3964 if (errsv == WSAEINTR)
3967 if (errsv == WSAEWOULDBLOCK)
3968 win32_unset_event_mask (socket, FD_WRITE);
3970 if (socket->priv->blocking &&
3971 errsv == WSAEWOULDBLOCK)
3974 g_set_error (error, G_IO_ERROR,
3975 socket_io_error_from_errno (errsv),
3976 _("Error sending message: %s"), socket_strerror (errsv));
3988 static GSocketAddress *
3989 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
3991 GSocketAddress *saddr;
3993 guint64 oldest_time = G_MAXUINT64;
3994 gint oldest_index = 0;
3996 if (native_len <= 0)
4000 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
4002 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
4003 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
4004 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
4009 if (tmp_native_len != native_len)
4012 if (memcmp (tmp_native, native, native_len) == 0)
4014 saddr = g_object_ref (tmp);
4015 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
4019 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
4021 oldest_time = socket->priv->recv_addr_cache[i].last_used;
4026 saddr = g_socket_address_new_from_native (native, native_len);
4028 if (socket->priv->recv_addr_cache[oldest_index].addr)
4030 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
4031 g_free (socket->priv->recv_addr_cache[oldest_index].native);
4034 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
4035 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
4036 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
4037 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
4043 * g_socket_receive_message:
4044 * @socket: a #GSocket
4045 * @address: (out) (allow-none): a pointer to a #GSocketAddress
4047 * @vectors: (array length=num_vectors): an array of #GInputVector structs
4048 * @num_vectors: the number of elements in @vectors, or -1
4049 * @messages: (array length=num_messages) (allow-none): a pointer which
4050 * may be filled with an array of #GSocketControlMessages, or %NULL
4051 * @num_messages: a pointer which will be filled with the number of
4052 * elements in @messages, or %NULL
4053 * @flags: a pointer to an int containing #GSocketMsgFlags flags
4054 * @cancellable: (allow-none): a %GCancellable or %NULL
4055 * @error: a #GError pointer, or %NULL
4057 * Receive data from a socket. This is the most complicated and
4058 * fully-featured version of this call. For easier use, see
4059 * g_socket_receive() and g_socket_receive_from().
4061 * If @address is non-%NULL then @address will be set equal to the
4062 * source address of the received packet.
4063 * @address is owned by the caller.
4065 * @vector must point to an array of #GInputVector structs and
4066 * @num_vectors must be the length of this array. These structs
4067 * describe the buffers that received data will be scattered into.
4068 * If @num_vectors is -1, then @vectors is assumed to be terminated
4069 * by a #GInputVector with a %NULL buffer pointer.
4071 * As a special case, if @num_vectors is 0 (in which case, @vectors
4072 * may of course be %NULL), then a single byte is received and
4073 * discarded. This is to facilitate the common practice of sending a
4074 * single '\0' byte for the purposes of transferring ancillary data.
4076 * @messages, if non-%NULL, will be set to point to a newly-allocated
4077 * array of #GSocketControlMessage instances or %NULL if no such
4078 * messages was received. These correspond to the control messages
4079 * received from the kernel, one #GSocketControlMessage per message
4080 * from the kernel. This array is %NULL-terminated and must be freed
4081 * by the caller using g_free() after calling g_object_unref() on each
4082 * element. If @messages is %NULL, any control messages received will
4085 * @num_messages, if non-%NULL, will be set to the number of control
4086 * messages received.
4088 * If both @messages and @num_messages are non-%NULL, then
4089 * @num_messages gives the number of #GSocketControlMessage instances
4090 * in @messages (ie: not including the %NULL terminator).
4092 * @flags is an in/out parameter. The commonly available arguments
4093 * for this are available in the #GSocketMsgFlags enum, but the
4094 * values there are the same as the system values, and the flags
4095 * are passed in as-is, so you can pass in system-specific flags too
4096 * (and g_socket_receive_message() may pass system-specific flags out).
4098 * As with g_socket_receive(), data may be discarded if @socket is
4099 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
4100 * provide enough buffer space to read a complete message. You can pass
4101 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
4102 * removing it from the receive queue, but there is no portable way to find
4103 * out the length of the message other than by reading it into a
4104 * sufficiently-large buffer.
4106 * If the socket is in blocking mode the call will block until there
4107 * is some data to receive, the connection is closed, or there is an
4108 * error. If there is no data available and the socket is in
4109 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
4110 * returned. To be notified when data is available, wait for the
4111 * %G_IO_IN condition.
4113 * On error -1 is returned and @error is set accordingly.
4115 * Returns: Number of bytes read, or 0 if the connection was closed by
4116 * the peer, or -1 on error
4121 g_socket_receive_message (GSocket *socket,
4122 GSocketAddress **address,
4123 GInputVector *vectors,
4125 GSocketControlMessage ***messages,
4128 GCancellable *cancellable,
4131 GInputVector one_vector;
4134 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4136 if (!check_socket (socket, error))
4139 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4142 if (num_vectors == -1)
4144 for (num_vectors = 0;
4145 vectors[num_vectors].buffer != NULL;
4150 if (num_vectors == 0)
4152 one_vector.buffer = &one_byte;
4153 one_vector.size = 1;
4155 vectors = &one_vector;
4162 struct sockaddr_storage one_sockaddr;
4167 msg.msg_name = &one_sockaddr;
4168 msg.msg_namelen = sizeof (struct sockaddr_storage);
4172 msg.msg_name = NULL;
4173 msg.msg_namelen = 0;
4177 /* this entire expression will be evaluated at compile time */
4178 if (sizeof *msg.msg_iov == sizeof *vectors &&
4179 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4180 G_STRUCT_OFFSET (struct iovec, iov_base) ==
4181 G_STRUCT_OFFSET (GInputVector, buffer) &&
4182 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4183 G_STRUCT_OFFSET (struct iovec, iov_len) ==
4184 G_STRUCT_OFFSET (GInputVector, size))
4185 /* ABI is compatible */
4187 msg.msg_iov = (struct iovec *) vectors;
4188 msg.msg_iovlen = num_vectors;
4191 /* ABI is incompatible */
4195 msg.msg_iov = g_newa (struct iovec, num_vectors);
4196 for (i = 0; i < num_vectors; i++)
4198 msg.msg_iov[i].iov_base = vectors[i].buffer;
4199 msg.msg_iov[i].iov_len = vectors[i].size;
4201 msg.msg_iovlen = num_vectors;
4205 msg.msg_control = g_alloca (2048);
4206 msg.msg_controllen = 2048;
4210 msg.msg_flags = *flags;
4214 /* We always set the close-on-exec flag so we don't leak file
4215 * descriptors into child processes. Note that gunixfdmessage.c
4216 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4218 #ifdef MSG_CMSG_CLOEXEC
4219 msg.msg_flags |= MSG_CMSG_CLOEXEC;
4225 if (socket->priv->blocking &&
4226 !g_socket_condition_wait (socket,
4227 G_IO_IN, cancellable, error))
4230 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4231 #ifdef MSG_CMSG_CLOEXEC
4232 if (result < 0 && get_socket_errno () == EINVAL)
4234 /* We must be running on an old kernel. Call without the flag. */
4235 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4236 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4242 int errsv = get_socket_errno ();
4247 if (socket->priv->blocking &&
4248 (errsv == EWOULDBLOCK ||
4252 g_set_error (error, G_IO_ERROR,
4253 socket_io_error_from_errno (errsv),
4254 _("Error receiving message: %s"), socket_strerror (errsv));
4261 /* decode address */
4262 if (address != NULL)
4264 *address = cache_recv_address (socket, msg.msg_name, msg.msg_namelen);
4267 /* decode control messages */
4269 GPtrArray *my_messages = NULL;
4270 struct cmsghdr *cmsg;
4272 if (msg.msg_controllen >= sizeof (struct cmsghdr))
4274 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4276 GSocketControlMessage *message;
4278 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4280 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4282 if (message == NULL)
4283 /* We've already spewed about the problem in the
4284 deserialization code, so just continue */
4287 if (messages == NULL)
4289 /* we have to do it this way if the user ignores the
4290 * messages so that we will close any received fds.
4292 g_object_unref (message);
4296 if (my_messages == NULL)
4297 my_messages = g_ptr_array_new ();
4298 g_ptr_array_add (my_messages, message);
4304 *num_messages = my_messages != NULL ? my_messages->len : 0;
4308 if (my_messages == NULL)
4314 g_ptr_array_add (my_messages, NULL);
4315 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4320 g_assert (my_messages == NULL);
4324 /* capture the flags */
4326 *flags = msg.msg_flags;
4332 struct sockaddr_storage addr;
4334 DWORD bytes_received;
4341 bufs = g_newa (WSABUF, num_vectors);
4342 for (i = 0; i < num_vectors; i++)
4344 bufs[i].buf = (char *)vectors[i].buffer;
4345 bufs[i].len = (gulong)vectors[i].size;
4357 if (socket->priv->blocking &&
4358 !g_socket_condition_wait (socket,
4359 G_IO_IN, cancellable, error))
4362 addrlen = sizeof addr;
4364 result = WSARecvFrom (socket->priv->fd,
4366 &bytes_received, &win_flags,
4367 (struct sockaddr *)&addr, &addrlen,
4370 result = WSARecv (socket->priv->fd,
4372 &bytes_received, &win_flags,
4376 int errsv = get_socket_errno ();
4378 if (errsv == WSAEINTR)
4381 win32_unset_event_mask (socket, FD_READ);
4383 if (socket->priv->blocking &&
4384 errsv == WSAEWOULDBLOCK)
4387 g_set_error (error, G_IO_ERROR,
4388 socket_io_error_from_errno (errsv),
4389 _("Error receiving message: %s"), socket_strerror (errsv));
4393 win32_unset_event_mask (socket, FD_READ);
4397 /* decode address */
4398 if (address != NULL)
4400 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
4403 /* capture the flags */
4407 if (messages != NULL)
4409 if (num_messages != NULL)
4412 return bytes_received;
4418 * g_socket_get_credentials:
4419 * @socket: a #GSocket.
4420 * @error: #GError for error reporting, or %NULL to ignore.
4422 * Returns the credentials of the foreign process connected to this
4423 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4426 * If this operation isn't supported on the OS, the method fails with
4427 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4428 * by reading the %SO_PEERCRED option on the underlying socket.
4430 * Other ways to obtain credentials from a foreign peer includes the
4431 * #GUnixCredentialsMessage type and
4432 * g_unix_connection_send_credentials() /
4433 * g_unix_connection_receive_credentials() functions.
4435 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4436 * that must be freed with g_object_unref().
4441 g_socket_get_credentials (GSocket *socket,
4446 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4447 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4451 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
4455 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
4456 socklen_t optlen = sizeof (native_creds_buf);
4458 if (getsockopt (socket->priv->fd,
4464 ret = g_credentials_new ();
4465 g_credentials_set_native (ret,
4466 G_CREDENTIALS_NATIVE_TYPE,
4470 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
4472 ucred_t *ucred = NULL;
4474 if (getpeerucred (socket->priv->fd, &ucred) == 0)
4476 ret = g_credentials_new ();
4477 g_credentials_set_native (ret,
4478 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
4484 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
4489 int errsv = get_socket_errno ();
4493 socket_io_error_from_errno (errsv),
4494 _("Unable to read socket credentials: %s"),
4495 socket_strerror (errsv));
4500 g_set_error_literal (error,
4502 G_IO_ERROR_NOT_SUPPORTED,
4503 _("g_socket_get_credentials not implemented for this OS"));
4510 * g_socket_get_option:
4511 * @socket: a #GSocket
4512 * @level: the "API level" of the option (eg, <literal>SOL_SOCKET</literal>)
4513 * @optname: the "name" of the option (eg, <literal>SO_BROADCAST</literal>)
4514 * @value: (out): return location for the option value
4515 * @error: #GError for error reporting, or %NULL to ignore.
4517 * Gets the value of an integer-valued option on @socket, as with
4518 * <literal>getsockopt ()</literal>. (If you need to fetch a
4519 * non-integer-valued option, you will need to call
4520 * <literal>getsockopt ()</literal> directly.)
4522 * The <link linkend="gio-gnetworking.h"><literal><gio/gnetworking.h></literal></link>
4523 * header pulls in system headers that will define most of the
4524 * standard/portable socket options. For unusual socket protocols or
4525 * platform-dependent options, you may need to include additional
4528 * Note that even for socket options that are a single byte in size,
4529 * @value is still a pointer to a #gint variable, not a #guchar;
4530 * g_socket_get_option() will handle the conversion internally.
4532 * Returns: success or failure. On failure, @error will be set, and
4533 * the system error value (<literal>errno</literal> or
4534 * <literal>WSAGetLastError ()</literal>) will still be set to the
4535 * result of the <literal>getsockopt ()</literal> call.
4540 g_socket_get_option (GSocket *socket,
4548 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4551 size = sizeof (gint);
4552 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
4554 int errsv = get_socket_errno ();
4556 g_set_error_literal (error,
4558 socket_io_error_from_errno (errsv),
4559 socket_strerror (errsv));
4561 /* Reset errno in case the caller wants to look at it */
4567 #if G_BYTE_ORDER == G_BIG_ENDIAN
4568 /* If the returned value is smaller than an int then we need to
4569 * slide it over into the low-order bytes of *value.
4571 if (size != sizeof (gint))
4572 *value = *value >> (8 * (sizeof (gint) - size));
4579 * g_socket_set_option:
4580 * @socket: a #GSocket
4581 * @level: the "API level" of the option (eg, <literal>SOL_SOCKET</literal>)
4582 * @optname: the "name" of the option (eg, <literal>SO_BROADCAST</literal>)
4583 * @value: the value to set the option to
4584 * @error: #GError for error reporting, or %NULL to ignore.
4586 * Sets the value of an integer-valued option on @socket, as with
4587 * <literal>setsockopt ()</literal>. (If you need to set a
4588 * non-integer-valued option, you will need to call
4589 * <literal>setsockopt ()</literal> directly.)
4591 * The <link linkend="gio-gnetworking.h"><literal><gio/gnetworking.h></literal></link>
4592 * header pulls in system headers that will define most of the
4593 * standard/portable socket options. For unusual socket protocols or
4594 * platform-dependent options, you may need to include additional
4597 * Returns: success or failure. On failure, @error will be set, and
4598 * the system error value (<literal>errno</literal> or
4599 * <literal>WSAGetLastError ()</literal>) will still be set to the
4600 * result of the <literal>setsockopt ()</literal> call.
4605 g_socket_set_option (GSocket *socket,
4613 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4615 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
4618 #if !defined (__linux__) && !defined (G_OS_WIN32)
4619 /* Linux and Windows let you set a single-byte value from an int,
4620 * but most other platforms don't.
4622 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
4624 #if G_BYTE_ORDER == G_BIG_ENDIAN
4625 value = value << (8 * (sizeof (gint) - 1));
4627 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
4632 errsv = get_socket_errno ();
4634 g_set_error_literal (error,
4636 socket_io_error_from_errno (errsv),
4637 socket_strerror (errsv));