1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2008 Christian Kellner, Samuel Cormier-Iijima
4 * Copyright © 2009 Codethink Limited
5 * Copyright © 2009 Red Hat, Inc
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General
18 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 * Authors: Christian Kellner <gicmo@gnome.org>
21 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
22 * Ryan Lortie <desrt@desrt.ca>
23 * Alexander Larsson <alexl@redhat.com>
31 #include "glib-unix.h"
42 # include <sys/ioctl.h>
45 #ifdef HAVE_SYS_FILIO_H
46 # include <sys/filio.h>
53 #include "gcancellable.h"
54 #include "gioenumtypes.h"
55 #include "ginetaddress.h"
56 #include "ginitable.h"
60 #include "gnetworkingprivate.h"
61 #include "gsocketaddress.h"
62 #include "gsocketcontrolmessage.h"
63 #include "gcredentials.h"
64 #include "gcredentialsprivate.h"
69 * @short_description: Low-level socket object
71 * @see_also: #GInitable, <link linkend="gio-gnetworking.h">gnetworking.h</link>
73 * A #GSocket is a low-level networking primitive. It is a more or less
74 * direct mapping of the BSD socket API in a portable GObject based API.
75 * It supports both the UNIX socket implementations and winsock2 on Windows.
77 * #GSocket is the platform independent base upon which the higher level
78 * network primitives are based. Applications are not typically meant to
79 * use it directly, but rather through classes like #GSocketClient,
80 * #GSocketService and #GSocketConnection. However there may be cases where
81 * direct use of #GSocket is useful.
83 * #GSocket implements the #GInitable interface, so if it is manually constructed
84 * by e.g. g_object_new() you must call g_initable_init() and check the
85 * results before using the object. This is done automatically in
86 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
89 * Sockets operate in two general modes, blocking or non-blocking. When
90 * in blocking mode all operations block until the requested operation
91 * is finished or there is an error. In non-blocking mode all calls that
92 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
93 * To know when a call would successfully run you can call g_socket_condition_check(),
94 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
95 * attach it to a #GMainContext to get callbacks when I/O is possible.
96 * Note that all sockets are always set to non blocking mode in the system, and
97 * blocking mode is emulated in GSocket.
99 * When working in non-blocking mode applications should always be able to
100 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
101 * function said that I/O was possible. This can easily happen in case
102 * of a race condition in the application, but it can also happen for other
103 * reasons. For instance, on Windows a socket is always seen as writable
104 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
106 * #GSocket<!-- -->s can be either connection oriented or datagram based.
107 * For connection oriented types you must first establish a connection by
108 * either connecting to an address or accepting a connection from another
109 * address. For connectionless socket types the target/source address is
110 * specified or received in each I/O operation.
112 * All socket file descriptors are set to be close-on-exec.
114 * Note that creating a #GSocket causes the signal %SIGPIPE to be
115 * ignored for the remainder of the program. If you are writing a
116 * command-line utility that uses #GSocket, you may need to take into
117 * account the fact that your program will not automatically be killed
118 * if it tries to write to %stdout after it has been closed.
123 static void g_socket_initable_iface_init (GInitableIface *iface);
124 static gboolean g_socket_initable_init (GInitable *initable,
125 GCancellable *cancellable,
143 PROP_MULTICAST_LOOPBACK,
147 /* Size of the receiver cache for g_socket_receive_from() */
148 #define RECV_ADDR_CACHE_SIZE 8
150 struct _GSocketPrivate
152 GSocketFamily family;
154 GSocketProtocol protocol;
158 GError *construct_error;
159 GSocketAddress *remote_address;
167 guint connect_pending : 1;
173 GList *requested_conditions; /* list of requested GIOCondition * */
174 GMutex win32_source_lock;
178 GSocketAddress *addr;
179 struct sockaddr *native;
182 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
185 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
186 G_ADD_PRIVATE (GSocket)
187 g_networking_init ();
188 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
189 g_socket_initable_iface_init));
192 get_socket_errno (void)
197 return WSAGetLastError ();
202 socket_io_error_from_errno (int err)
205 return g_io_error_from_errno (err);
210 return G_IO_ERROR_ADDRESS_IN_USE;
212 return G_IO_ERROR_WOULD_BLOCK;
214 return G_IO_ERROR_PERMISSION_DENIED;
215 case WSA_INVALID_HANDLE:
216 case WSA_INVALID_PARAMETER:
219 return G_IO_ERROR_INVALID_ARGUMENT;
220 case WSAEPROTONOSUPPORT:
221 return G_IO_ERROR_NOT_SUPPORTED;
223 return G_IO_ERROR_CANCELLED;
224 case WSAESOCKTNOSUPPORT:
226 case WSAEPFNOSUPPORT:
227 case WSAEAFNOSUPPORT:
228 return G_IO_ERROR_NOT_SUPPORTED;
230 return G_IO_ERROR_FAILED;
236 socket_strerror (int err)
239 return g_strerror (err);
244 msg = g_win32_error_message (err);
246 msg_ret = g_intern_string (msg);
254 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
256 _win32_unset_event_mask (GSocket *socket, int mask)
258 socket->priv->current_events &= ~mask;
259 socket->priv->current_errors &= ~mask;
262 #define win32_unset_event_mask(_socket, _mask)
265 /* Windows has broken prototypes... */
267 #define getsockopt(sockfd, level, optname, optval, optlen) \
268 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
269 #define setsockopt(sockfd, level, optname, optval, optlen) \
270 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
271 #define getsockname(sockfd, addr, addrlen) \
272 getsockname (sockfd, addr, (int *)addrlen)
273 #define getpeername(sockfd, addr, addrlen) \
274 getpeername (sockfd, addr, (int *)addrlen)
275 #define recv(sockfd, buf, len, flags) \
276 recv (sockfd, (gpointer)buf, len, flags)
280 set_fd_nonblocking (int fd)
283 GError *error = NULL;
289 if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
291 g_warning ("Error setting socket nonblocking: %s", error->message);
292 g_clear_error (&error);
297 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
299 int errsv = get_socket_errno ();
300 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
306 check_socket (GSocket *socket,
309 if (!socket->priv->inited)
311 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
312 _("Invalid socket, not initialized"));
316 if (socket->priv->construct_error)
318 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
319 _("Invalid socket, initialization failed due to: %s"),
320 socket->priv->construct_error->message);
324 if (socket->priv->closed)
326 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
327 _("Socket is already closed"));
331 if (socket->priv->timed_out)
333 socket->priv->timed_out = FALSE;
334 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
335 _("Socket I/O timed out"));
343 g_socket_details_from_fd (GSocket *socket)
345 struct sockaddr_storage address;
351 fd = socket->priv->fd;
352 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
354 errsv = get_socket_errno ();
366 /* programmer error */
367 g_error ("creating GSocket from fd %d: %s\n",
368 fd, socket_strerror (errsv));
379 socket->priv->type = G_SOCKET_TYPE_STREAM;
383 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
387 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
391 socket->priv->type = G_SOCKET_TYPE_INVALID;
395 addrlen = sizeof address;
396 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
398 errsv = get_socket_errno ();
404 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
405 sizeof address.ss_family <= addrlen);
406 family = address.ss_family;
410 /* On Solaris, this happens if the socket is not yet connected.
411 * But we can use SO_DOMAIN as a workaround there.
414 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
416 errsv = get_socket_errno ();
420 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
428 case G_SOCKET_FAMILY_IPV4:
429 case G_SOCKET_FAMILY_IPV6:
430 socket->priv->family = address.ss_family;
431 switch (socket->priv->type)
433 case G_SOCKET_TYPE_STREAM:
434 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
437 case G_SOCKET_TYPE_DATAGRAM:
438 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
441 case G_SOCKET_TYPE_SEQPACKET:
442 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
450 case G_SOCKET_FAMILY_UNIX:
451 socket->priv->family = G_SOCKET_FAMILY_UNIX;
452 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
456 socket->priv->family = G_SOCKET_FAMILY_INVALID;
460 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
462 addrlen = sizeof address;
463 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
464 socket->priv->connected = TRUE;
467 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
469 socket->priv->keepalive = !!value;
473 /* Can't read, maybe not supported, assume FALSE */
474 socket->priv->keepalive = FALSE;
480 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
481 socket_io_error_from_errno (errsv),
482 _("creating GSocket from fd: %s"),
483 socket_strerror (errsv));
486 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
488 g_socket (gint domain,
496 fd = socket (domain, type | SOCK_CLOEXEC, protocol);
500 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
501 if (fd < 0 && (errno == EINVAL || errno == EPROTOTYPE))
503 fd = socket (domain, type, protocol);
507 int errsv = get_socket_errno ();
509 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
510 _("Unable to create socket: %s"), socket_strerror (errsv));
519 /* We always want to set close-on-exec to protect users. If you
520 need to so some weird inheritance to exec you can re-enable this
521 using lower level hacks with g_socket_get_fd(). */
522 flags = fcntl (fd, F_GETFD, 0);
524 (flags & FD_CLOEXEC) == 0)
527 fcntl (fd, F_SETFD, flags);
536 g_socket_create_socket (GSocketFamily family,
545 case G_SOCKET_TYPE_STREAM:
546 native_type = SOCK_STREAM;
549 case G_SOCKET_TYPE_DATAGRAM:
550 native_type = SOCK_DGRAM;
553 case G_SOCKET_TYPE_SEQPACKET:
554 native_type = SOCK_SEQPACKET;
558 g_assert_not_reached ();
563 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
564 _("Unable to create socket: %s"), _("Unknown family was specified"));
570 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
571 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
575 return g_socket (family, native_type, protocol, error);
579 g_socket_constructed (GObject *object)
581 GSocket *socket = G_SOCKET (object);
583 if (socket->priv->fd >= 0)
584 /* create socket->priv info from the fd */
585 g_socket_details_from_fd (socket);
588 /* create the fd from socket->priv info */
589 socket->priv->fd = g_socket_create_socket (socket->priv->family,
591 socket->priv->protocol,
592 &socket->priv->construct_error);
594 /* Always use native nonblocking sockets, as
595 windows sets sockets to nonblocking automatically
596 in certain operations. This way we make things work
597 the same on all platforms */
598 if (socket->priv->fd != -1)
599 set_fd_nonblocking (socket->priv->fd);
603 g_socket_get_property (GObject *object,
608 GSocket *socket = G_SOCKET (object);
609 GSocketAddress *address;
614 g_value_set_enum (value, socket->priv->family);
618 g_value_set_enum (value, socket->priv->type);
622 g_value_set_enum (value, socket->priv->protocol);
626 g_value_set_int (value, socket->priv->fd);
630 g_value_set_boolean (value, socket->priv->blocking);
633 case PROP_LISTEN_BACKLOG:
634 g_value_set_int (value, socket->priv->listen_backlog);
638 g_value_set_boolean (value, socket->priv->keepalive);
641 case PROP_LOCAL_ADDRESS:
642 address = g_socket_get_local_address (socket, NULL);
643 g_value_take_object (value, address);
646 case PROP_REMOTE_ADDRESS:
647 address = g_socket_get_remote_address (socket, NULL);
648 g_value_take_object (value, address);
652 g_value_set_uint (value, socket->priv->timeout);
656 g_value_set_uint (value, g_socket_get_ttl (socket));
660 g_value_set_boolean (value, g_socket_get_broadcast (socket));
663 case PROP_MULTICAST_LOOPBACK:
664 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
667 case PROP_MULTICAST_TTL:
668 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
672 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
677 g_socket_set_property (GObject *object,
682 GSocket *socket = G_SOCKET (object);
687 socket->priv->family = g_value_get_enum (value);
691 socket->priv->type = g_value_get_enum (value);
695 socket->priv->protocol = g_value_get_enum (value);
699 socket->priv->fd = g_value_get_int (value);
703 g_socket_set_blocking (socket, g_value_get_boolean (value));
706 case PROP_LISTEN_BACKLOG:
707 g_socket_set_listen_backlog (socket, g_value_get_int (value));
711 g_socket_set_keepalive (socket, g_value_get_boolean (value));
715 g_socket_set_timeout (socket, g_value_get_uint (value));
719 g_socket_set_ttl (socket, g_value_get_uint (value));
723 g_socket_set_broadcast (socket, g_value_get_boolean (value));
726 case PROP_MULTICAST_LOOPBACK:
727 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
730 case PROP_MULTICAST_TTL:
731 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
735 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
740 g_socket_finalize (GObject *object)
742 GSocket *socket = G_SOCKET (object);
745 g_clear_error (&socket->priv->construct_error);
747 if (socket->priv->fd != -1 &&
748 !socket->priv->closed)
749 g_socket_close (socket, NULL);
751 if (socket->priv->remote_address)
752 g_object_unref (socket->priv->remote_address);
755 if (socket->priv->event != WSA_INVALID_EVENT)
757 WSACloseEvent (socket->priv->event);
758 socket->priv->event = WSA_INVALID_EVENT;
761 g_assert (socket->priv->requested_conditions == NULL);
762 g_mutex_clear (&socket->priv->win32_source_lock);
765 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
767 if (socket->priv->recv_addr_cache[i].addr)
769 g_object_unref (socket->priv->recv_addr_cache[i].addr);
770 g_free (socket->priv->recv_addr_cache[i].native);
774 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
775 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
779 g_socket_class_init (GSocketClass *klass)
781 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
784 /* There is no portable, thread-safe way to avoid having the process
785 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
786 * forced to simply ignore the signal process-wide.
788 signal (SIGPIPE, SIG_IGN);
791 gobject_class->finalize = g_socket_finalize;
792 gobject_class->constructed = g_socket_constructed;
793 gobject_class->set_property = g_socket_set_property;
794 gobject_class->get_property = g_socket_get_property;
796 g_object_class_install_property (gobject_class, PROP_FAMILY,
797 g_param_spec_enum ("family",
799 P_("The sockets address family"),
800 G_TYPE_SOCKET_FAMILY,
801 G_SOCKET_FAMILY_INVALID,
802 G_PARAM_CONSTRUCT_ONLY |
804 G_PARAM_STATIC_STRINGS));
806 g_object_class_install_property (gobject_class, PROP_TYPE,
807 g_param_spec_enum ("type",
809 P_("The sockets type"),
811 G_SOCKET_TYPE_STREAM,
812 G_PARAM_CONSTRUCT_ONLY |
814 G_PARAM_STATIC_STRINGS));
816 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
817 g_param_spec_enum ("protocol",
818 P_("Socket protocol"),
819 P_("The id of the protocol to use, or -1 for unknown"),
820 G_TYPE_SOCKET_PROTOCOL,
821 G_SOCKET_PROTOCOL_UNKNOWN,
822 G_PARAM_CONSTRUCT_ONLY |
824 G_PARAM_STATIC_STRINGS));
826 g_object_class_install_property (gobject_class, PROP_FD,
827 g_param_spec_int ("fd",
828 P_("File descriptor"),
829 P_("The sockets file descriptor"),
833 G_PARAM_CONSTRUCT_ONLY |
835 G_PARAM_STATIC_STRINGS));
837 g_object_class_install_property (gobject_class, PROP_BLOCKING,
838 g_param_spec_boolean ("blocking",
840 P_("Whether or not I/O on this socket is blocking"),
843 G_PARAM_STATIC_STRINGS));
845 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
846 g_param_spec_int ("listen-backlog",
847 P_("Listen backlog"),
848 P_("Outstanding connections in the listen queue"),
853 G_PARAM_STATIC_STRINGS));
855 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
856 g_param_spec_boolean ("keepalive",
857 P_("Keep connection alive"),
858 P_("Keep connection alive by sending periodic pings"),
861 G_PARAM_STATIC_STRINGS));
863 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
864 g_param_spec_object ("local-address",
866 P_("The local address the socket is bound to"),
867 G_TYPE_SOCKET_ADDRESS,
869 G_PARAM_STATIC_STRINGS));
871 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
872 g_param_spec_object ("remote-address",
873 P_("Remote address"),
874 P_("The remote address the socket is connected to"),
875 G_TYPE_SOCKET_ADDRESS,
877 G_PARAM_STATIC_STRINGS));
882 * The timeout in seconds on socket I/O
886 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
887 g_param_spec_uint ("timeout",
889 P_("The timeout in seconds on socket I/O"),
894 G_PARAM_STATIC_STRINGS));
899 * Whether the socket should allow sending to broadcast addresses.
903 g_object_class_install_property (gobject_class, PROP_BROADCAST,
904 g_param_spec_boolean ("broadcast",
906 P_("Whether to allow sending to broadcast addresses"),
909 G_PARAM_STATIC_STRINGS));
914 * Time-to-live for outgoing unicast packets
918 g_object_class_install_property (gobject_class, PROP_TTL,
919 g_param_spec_uint ("ttl",
921 P_("Time-to-live of outgoing unicast packets"),
924 G_PARAM_STATIC_STRINGS));
927 * GSocket:multicast-loopback:
929 * Whether outgoing multicast packets loop back to the local host.
933 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
934 g_param_spec_boolean ("multicast-loopback",
935 P_("Multicast loopback"),
936 P_("Whether outgoing multicast packets loop back to the local host"),
939 G_PARAM_STATIC_STRINGS));
942 * GSocket:multicast-ttl:
944 * Time-to-live out outgoing multicast packets
948 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
949 g_param_spec_uint ("multicast-ttl",
951 P_("Time-to-live of outgoing multicast packets"),
954 G_PARAM_STATIC_STRINGS));
958 g_socket_initable_iface_init (GInitableIface *iface)
960 iface->init = g_socket_initable_init;
964 g_socket_init (GSocket *socket)
966 socket->priv = g_socket_get_instance_private (socket);
968 socket->priv->fd = -1;
969 socket->priv->blocking = TRUE;
970 socket->priv->listen_backlog = 10;
971 socket->priv->construct_error = NULL;
973 socket->priv->event = WSA_INVALID_EVENT;
974 g_mutex_init (&socket->priv->win32_source_lock);
979 g_socket_initable_init (GInitable *initable,
980 GCancellable *cancellable,
985 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
987 socket = G_SOCKET (initable);
989 if (cancellable != NULL)
991 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
992 _("Cancellable initialization not supported"));
996 socket->priv->inited = TRUE;
998 if (socket->priv->construct_error)
1001 *error = g_error_copy (socket->priv->construct_error);
1011 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1012 * @type: the socket type to use.
1013 * @protocol: the id of the protocol to use, or 0 for default.
1014 * @error: #GError for error reporting, or %NULL to ignore.
1016 * Creates a new #GSocket with the defined family, type and protocol.
1017 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1018 * for the family and type is used.
1020 * The @protocol is a family and type specific int that specifies what
1021 * kind of protocol to use. #GSocketProtocol lists several common ones.
1022 * Many families only support one protocol, and use 0 for this, others
1023 * support several and using 0 means to use the default protocol for
1024 * the family and type.
1026 * The protocol id is passed directly to the operating
1027 * system, so you can use protocols not listed in #GSocketProtocol if you
1028 * know the protocol number used for it.
1030 * Returns: a #GSocket or %NULL on error.
1031 * Free the returned object with g_object_unref().
1036 g_socket_new (GSocketFamily family,
1038 GSocketProtocol protocol,
1041 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1045 "protocol", protocol,
1050 * g_socket_new_from_fd:
1051 * @fd: a native socket file descriptor.
1052 * @error: #GError for error reporting, or %NULL to ignore.
1054 * Creates a new #GSocket from a native file descriptor
1055 * or winsock SOCKET handle.
1057 * This reads all the settings from the file descriptor so that
1058 * all properties should work. Note that the file descriptor
1059 * will be set to non-blocking mode, independent on the blocking
1060 * mode of the #GSocket.
1062 * Returns: a #GSocket or %NULL on error.
1063 * Free the returned object with g_object_unref().
1068 g_socket_new_from_fd (gint fd,
1071 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1078 * g_socket_set_blocking:
1079 * @socket: a #GSocket.
1080 * @blocking: Whether to use blocking I/O or not.
1082 * Sets the blocking mode of the socket. In blocking mode
1083 * all operations block until they succeed or there is an error. In
1084 * non-blocking mode all functions return results immediately or
1085 * with a %G_IO_ERROR_WOULD_BLOCK error.
1087 * All sockets are created in blocking mode. However, note that the
1088 * platform level socket is always non-blocking, and blocking mode
1089 * is a GSocket level feature.
1094 g_socket_set_blocking (GSocket *socket,
1097 g_return_if_fail (G_IS_SOCKET (socket));
1099 blocking = !!blocking;
1101 if (socket->priv->blocking == blocking)
1104 socket->priv->blocking = blocking;
1105 g_object_notify (G_OBJECT (socket), "blocking");
1109 * g_socket_get_blocking:
1110 * @socket: a #GSocket.
1112 * Gets the blocking mode of the socket. For details on blocking I/O,
1113 * see g_socket_set_blocking().
1115 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1120 g_socket_get_blocking (GSocket *socket)
1122 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1124 return socket->priv->blocking;
1128 * g_socket_set_keepalive:
1129 * @socket: a #GSocket.
1130 * @keepalive: Value for the keepalive flag
1132 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1133 * this flag is set on a socket, the system will attempt to verify that the
1134 * remote socket endpoint is still present if a sufficiently long period of
1135 * time passes with no data being exchanged. If the system is unable to
1136 * verify the presence of the remote endpoint, it will automatically close
1139 * This option is only functional on certain kinds of sockets. (Notably,
1140 * %G_SOCKET_PROTOCOL_TCP sockets.)
1142 * The exact time between pings is system- and protocol-dependent, but will
1143 * normally be at least two hours. Most commonly, you would set this flag
1144 * on a server socket if you want to allow clients to remain idle for long
1145 * periods of time, but also want to ensure that connections are eventually
1146 * garbage-collected if clients crash or become unreachable.
1151 g_socket_set_keepalive (GSocket *socket,
1154 GError *error = NULL;
1156 g_return_if_fail (G_IS_SOCKET (socket));
1158 keepalive = !!keepalive;
1159 if (socket->priv->keepalive == keepalive)
1162 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1165 g_warning ("error setting keepalive: %s", error->message);
1166 g_error_free (error);
1170 socket->priv->keepalive = keepalive;
1171 g_object_notify (G_OBJECT (socket), "keepalive");
1175 * g_socket_get_keepalive:
1176 * @socket: a #GSocket.
1178 * Gets the keepalive mode of the socket. For details on this,
1179 * see g_socket_set_keepalive().
1181 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1186 g_socket_get_keepalive (GSocket *socket)
1188 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1190 return socket->priv->keepalive;
1194 * g_socket_get_listen_backlog:
1195 * @socket: a #GSocket.
1197 * Gets the listen backlog setting of the socket. For details on this,
1198 * see g_socket_set_listen_backlog().
1200 * Returns: the maximum number of pending connections.
1205 g_socket_get_listen_backlog (GSocket *socket)
1207 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1209 return socket->priv->listen_backlog;
1213 * g_socket_set_listen_backlog:
1214 * @socket: a #GSocket.
1215 * @backlog: the maximum number of pending connections.
1217 * Sets the maximum number of outstanding connections allowed
1218 * when listening on this socket. If more clients than this are
1219 * connecting to the socket and the application is not handling them
1220 * on time then the new connections will be refused.
1222 * Note that this must be called before g_socket_listen() and has no
1223 * effect if called after that.
1228 g_socket_set_listen_backlog (GSocket *socket,
1231 g_return_if_fail (G_IS_SOCKET (socket));
1232 g_return_if_fail (!socket->priv->listening);
1234 if (backlog != socket->priv->listen_backlog)
1236 socket->priv->listen_backlog = backlog;
1237 g_object_notify (G_OBJECT (socket), "listen-backlog");
1242 * g_socket_get_timeout:
1243 * @socket: a #GSocket.
1245 * Gets the timeout setting of the socket. For details on this, see
1246 * g_socket_set_timeout().
1248 * Returns: the timeout in seconds
1253 g_socket_get_timeout (GSocket *socket)
1255 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1257 return socket->priv->timeout;
1261 * g_socket_set_timeout:
1262 * @socket: a #GSocket.
1263 * @timeout: the timeout for @socket, in seconds, or 0 for none
1265 * Sets the time in seconds after which I/O operations on @socket will
1266 * time out if they have not yet completed.
1268 * On a blocking socket, this means that any blocking #GSocket
1269 * operation will time out after @timeout seconds of inactivity,
1270 * returning %G_IO_ERROR_TIMED_OUT.
1272 * On a non-blocking socket, calls to g_socket_condition_wait() will
1273 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1274 * created with g_socket_create_source() will trigger after
1275 * @timeout seconds of inactivity, with the requested condition
1276 * set, at which point calling g_socket_receive(), g_socket_send(),
1277 * g_socket_check_connect_result(), etc, will fail with
1278 * %G_IO_ERROR_TIMED_OUT.
1280 * If @timeout is 0 (the default), operations will never time out
1283 * Note that if an I/O operation is interrupted by a signal, this may
1284 * cause the timeout to be reset.
1289 g_socket_set_timeout (GSocket *socket,
1292 g_return_if_fail (G_IS_SOCKET (socket));
1294 if (timeout != socket->priv->timeout)
1296 socket->priv->timeout = timeout;
1297 g_object_notify (G_OBJECT (socket), "timeout");
1303 * @socket: a #GSocket.
1305 * Gets the unicast time-to-live setting on @socket; see
1306 * g_socket_set_ttl() for more details.
1308 * Returns: the time-to-live setting on @socket
1313 g_socket_get_ttl (GSocket *socket)
1315 GError *error = NULL;
1318 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1320 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1322 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1325 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1327 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1331 g_return_val_if_reached (0);
1335 g_warning ("error getting unicast ttl: %s", error->message);
1336 g_error_free (error);
1345 * @socket: a #GSocket.
1346 * @ttl: the time-to-live value for all unicast packets on @socket
1348 * Sets the time-to-live for outgoing unicast packets on @socket.
1349 * By default the platform-specific default value is used.
1354 g_socket_set_ttl (GSocket *socket,
1357 GError *error = NULL;
1359 g_return_if_fail (G_IS_SOCKET (socket));
1361 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1363 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1366 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1368 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1370 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1374 g_return_if_reached ();
1378 g_warning ("error setting unicast ttl: %s", error->message);
1379 g_error_free (error);
1383 g_object_notify (G_OBJECT (socket), "ttl");
1387 * g_socket_get_broadcast:
1388 * @socket: a #GSocket.
1390 * Gets the broadcast setting on @socket; if %TRUE,
1391 * it is possible to send packets to broadcast
1394 * Returns: the broadcast setting on @socket
1399 g_socket_get_broadcast (GSocket *socket)
1401 GError *error = NULL;
1404 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1406 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1409 g_warning ("error getting broadcast: %s", error->message);
1410 g_error_free (error);
1418 * g_socket_set_broadcast:
1419 * @socket: a #GSocket.
1420 * @broadcast: whether @socket should allow sending to broadcast
1423 * Sets whether @socket should allow sending to broadcast addresses.
1424 * This is %FALSE by default.
1429 g_socket_set_broadcast (GSocket *socket,
1432 GError *error = NULL;
1434 g_return_if_fail (G_IS_SOCKET (socket));
1436 broadcast = !!broadcast;
1438 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1441 g_warning ("error setting broadcast: %s", error->message);
1442 g_error_free (error);
1446 g_object_notify (G_OBJECT (socket), "broadcast");
1450 * g_socket_get_multicast_loopback:
1451 * @socket: a #GSocket.
1453 * Gets the multicast loopback setting on @socket; if %TRUE (the
1454 * default), outgoing multicast packets will be looped back to
1455 * multicast listeners on the same host.
1457 * Returns: the multicast loopback setting on @socket
1462 g_socket_get_multicast_loopback (GSocket *socket)
1464 GError *error = NULL;
1467 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1469 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1471 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1474 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1476 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1480 g_return_val_if_reached (FALSE);
1484 g_warning ("error getting multicast loopback: %s", error->message);
1485 g_error_free (error);
1493 * g_socket_set_multicast_loopback:
1494 * @socket: a #GSocket.
1495 * @loopback: whether @socket should receive messages sent to its
1496 * multicast groups from the local host
1498 * Sets whether outgoing multicast packets will be received by sockets
1499 * listening on that multicast address on the same host. This is %TRUE
1505 g_socket_set_multicast_loopback (GSocket *socket,
1508 GError *error = NULL;
1510 g_return_if_fail (G_IS_SOCKET (socket));
1512 loopback = !!loopback;
1514 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1516 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1519 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1521 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1523 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1527 g_return_if_reached ();
1531 g_warning ("error setting multicast loopback: %s", error->message);
1532 g_error_free (error);
1536 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1540 * g_socket_get_multicast_ttl:
1541 * @socket: a #GSocket.
1543 * Gets the multicast time-to-live setting on @socket; see
1544 * g_socket_set_multicast_ttl() for more details.
1546 * Returns: the multicast time-to-live setting on @socket
1551 g_socket_get_multicast_ttl (GSocket *socket)
1553 GError *error = NULL;
1556 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1558 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1560 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1563 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1565 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1569 g_return_val_if_reached (FALSE);
1573 g_warning ("error getting multicast ttl: %s", error->message);
1574 g_error_free (error);
1582 * g_socket_set_multicast_ttl:
1583 * @socket: a #GSocket.
1584 * @ttl: the time-to-live value for all multicast datagrams on @socket
1586 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1587 * By default, this is 1, meaning that multicast packets will not leave
1588 * the local network.
1593 g_socket_set_multicast_ttl (GSocket *socket,
1596 GError *error = NULL;
1598 g_return_if_fail (G_IS_SOCKET (socket));
1600 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1602 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1605 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1607 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1609 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1613 g_return_if_reached ();
1617 g_warning ("error setting multicast ttl: %s", error->message);
1618 g_error_free (error);
1622 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1626 * g_socket_get_family:
1627 * @socket: a #GSocket.
1629 * Gets the socket family of the socket.
1631 * Returns: a #GSocketFamily
1636 g_socket_get_family (GSocket *socket)
1638 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1640 return socket->priv->family;
1644 * g_socket_get_socket_type:
1645 * @socket: a #GSocket.
1647 * Gets the socket type of the socket.
1649 * Returns: a #GSocketType
1654 g_socket_get_socket_type (GSocket *socket)
1656 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1658 return socket->priv->type;
1662 * g_socket_get_protocol:
1663 * @socket: a #GSocket.
1665 * Gets the socket protocol id the socket was created with.
1666 * In case the protocol is unknown, -1 is returned.
1668 * Returns: a protocol id, or -1 if unknown
1673 g_socket_get_protocol (GSocket *socket)
1675 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1677 return socket->priv->protocol;
1682 * @socket: a #GSocket.
1684 * Returns the underlying OS socket object. On unix this
1685 * is a socket file descriptor, and on Windows this is
1686 * a Winsock2 SOCKET handle. This may be useful for
1687 * doing platform specific or otherwise unusual operations
1690 * Returns: the file descriptor of the socket.
1695 g_socket_get_fd (GSocket *socket)
1697 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1699 return socket->priv->fd;
1703 * g_socket_get_local_address:
1704 * @socket: a #GSocket.
1705 * @error: #GError for error reporting, or %NULL to ignore.
1707 * Try to get the local address of a bound socket. This is only
1708 * useful if the socket has been bound to a local address,
1709 * either explicitly or implicitly when connecting.
1711 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1712 * Free the returned object with g_object_unref().
1717 g_socket_get_local_address (GSocket *socket,
1720 struct sockaddr_storage buffer;
1721 guint len = sizeof (buffer);
1723 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1725 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1727 int errsv = get_socket_errno ();
1728 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1729 _("could not get local address: %s"), socket_strerror (errsv));
1733 return g_socket_address_new_from_native (&buffer, len);
1737 * g_socket_get_remote_address:
1738 * @socket: a #GSocket.
1739 * @error: #GError for error reporting, or %NULL to ignore.
1741 * Try to get the remove address of a connected socket. This is only
1742 * useful for connection oriented sockets that have been connected.
1744 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1745 * Free the returned object with g_object_unref().
1750 g_socket_get_remote_address (GSocket *socket,
1753 struct sockaddr_storage buffer;
1754 guint len = sizeof (buffer);
1756 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1758 if (socket->priv->connect_pending)
1760 if (!g_socket_check_connect_result (socket, error))
1763 socket->priv->connect_pending = FALSE;
1766 if (!socket->priv->remote_address)
1768 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1770 int errsv = get_socket_errno ();
1771 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1772 _("could not get remote address: %s"), socket_strerror (errsv));
1776 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1779 return g_object_ref (socket->priv->remote_address);
1783 * g_socket_is_connected:
1784 * @socket: a #GSocket.
1786 * Check whether the socket is connected. This is only useful for
1787 * connection-oriented sockets.
1789 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1794 g_socket_is_connected (GSocket *socket)
1796 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1798 return socket->priv->connected;
1803 * @socket: a #GSocket.
1804 * @error: #GError for error reporting, or %NULL to ignore.
1806 * Marks the socket as a server socket, i.e. a socket that is used
1807 * to accept incoming requests using g_socket_accept().
1809 * Before calling this the socket must be bound to a local address using
1812 * To set the maximum amount of outstanding clients, use
1813 * g_socket_set_listen_backlog().
1815 * Returns: %TRUE on success, %FALSE on error.
1820 g_socket_listen (GSocket *socket,
1823 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1825 if (!check_socket (socket, error))
1828 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1830 int errsv = get_socket_errno ();
1832 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1833 _("could not listen: %s"), socket_strerror (errsv));
1837 socket->priv->listening = TRUE;
1844 * @socket: a #GSocket.
1845 * @address: a #GSocketAddress specifying the local address.
1846 * @allow_reuse: whether to allow reusing this address
1847 * @error: #GError for error reporting, or %NULL to ignore.
1849 * When a socket is created it is attached to an address family, but it
1850 * doesn't have an address in this family. g_socket_bind() assigns the
1851 * address (sometimes called name) of the socket.
1853 * It is generally required to bind to a local address before you can
1854 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1855 * In certain situations, you may also want to bind a socket that will be
1856 * used to initiate connections, though this is not normally required.
1858 * If @socket is a TCP socket, then @allow_reuse controls the setting
1859 * of the <literal>SO_REUSEADDR</literal> socket option; normally it
1860 * should be %TRUE for server sockets (sockets that you will
1861 * eventually call g_socket_accept() on), and %FALSE for client
1862 * sockets. (Failing to set this flag on a server socket may cause
1863 * g_socket_bind() to return %G_IO_ERROR_ADDRESS_IN_USE if the server
1864 * program is stopped and then immediately restarted.)
1866 * If @socket is a UDP socket, then @allow_reuse determines whether or
1867 * not other UDP sockets can be bound to the same address at the same
1868 * time. In particular, you can have several UDP sockets bound to the
1869 * same address, and they will all receive all of the multicast and
1870 * broadcast packets sent to that address. (The behavior of unicast
1871 * UDP packets to an address with multiple listeners is not defined.)
1873 * Returns: %TRUE on success, %FALSE on error.
1878 g_socket_bind (GSocket *socket,
1879 GSocketAddress *address,
1880 gboolean reuse_address,
1883 struct sockaddr_storage addr;
1884 gboolean so_reuseaddr;
1886 gboolean so_reuseport;
1889 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1891 if (!check_socket (socket, error))
1894 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1897 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
1898 * sockets, but has nasty side effects we don't want for TCP
1901 * On other platforms, we set SO_REUSEPORT, if it exists, for
1902 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
1903 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
1904 * the desired semantics on UDP (as it does on Linux, although
1905 * Linux has SO_REUSEPORT too as of 3.9).
1909 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1911 so_reuseaddr = !!reuse_address;
1915 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1918 /* Ignore errors here, the only likely error is "not supported", and
1919 * this is a "best effort" thing mainly.
1921 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
1923 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
1926 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1927 g_socket_address_get_native_size (address)) < 0)
1929 int errsv = get_socket_errno ();
1931 G_IO_ERROR, socket_io_error_from_errno (errsv),
1932 _("Error binding to address: %s"), socket_strerror (errsv));
1939 #if !defined(HAVE_IF_NAMETOINDEX) && defined(G_OS_WIN32)
1941 if_nametoindex (const gchar *iface)
1943 PIP_ADAPTER_ADDRESSES addresses = NULL, p;
1944 gulong addresses_len = 0;
1948 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, NULL, &addresses_len);
1949 if (res != NO_ERROR && res != ERROR_BUFFER_OVERFLOW)
1951 if (res == ERROR_NO_DATA)
1958 addresses = g_malloc (addresses_len);
1959 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, addresses, &addresses_len);
1961 if (res != NO_ERROR)
1964 if (res == ERROR_NO_DATA)
1974 if (strcmp (p->AdapterName, iface) == 0)
1990 #define HAVE_IF_NAMETOINDEX 1
1994 g_socket_multicast_group_operation (GSocket *socket,
1995 GInetAddress *group,
1996 gboolean source_specific,
1998 gboolean join_group,
2001 const guint8 *native_addr;
2002 gint optname, result;
2004 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2005 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2006 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2008 if (!check_socket (socket, error))
2011 native_addr = g_inet_address_to_bytes (group);
2012 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2014 #ifdef HAVE_IP_MREQN
2015 struct ip_mreqn mc_req;
2017 struct ip_mreq mc_req;
2020 memset (&mc_req, 0, sizeof (mc_req));
2021 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2023 #ifdef HAVE_IP_MREQN
2025 mc_req.imr_ifindex = if_nametoindex (iface);
2027 mc_req.imr_ifindex = 0; /* Pick any. */
2028 #elif defined(G_OS_WIN32)
2030 mc_req.imr_interface.s_addr = g_htonl (if_nametoindex (iface));
2032 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2034 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2037 if (source_specific)
2039 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2040 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2042 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2044 _("Error joining multicast group: %s") :
2045 _("Error leaving multicast group: %s"),
2046 _("No support for source-specific multicast"));
2051 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2052 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2053 &mc_req, sizeof (mc_req));
2055 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2057 struct ipv6_mreq mc_req_ipv6;
2059 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2060 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2061 #ifdef HAVE_IF_NAMETOINDEX
2063 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2066 mc_req_ipv6.ipv6mr_interface = 0;
2068 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2069 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2070 &mc_req_ipv6, sizeof (mc_req_ipv6));
2073 g_return_val_if_reached (FALSE);
2077 int errsv = get_socket_errno ();
2079 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2081 _("Error joining multicast group: %s") :
2082 _("Error leaving multicast group: %s"),
2083 socket_strerror (errsv));
2091 * g_socket_join_multicast_group:
2092 * @socket: a #GSocket.
2093 * @group: a #GInetAddress specifying the group address to join.
2094 * @iface: (allow-none): Name of the interface to use, or %NULL
2095 * @source_specific: %TRUE if source-specific multicast should be used
2096 * @error: #GError for error reporting, or %NULL to ignore.
2098 * Registers @socket to receive multicast messages sent to @group.
2099 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2100 * been bound to an appropriate interface and port with
2103 * If @iface is %NULL, the system will automatically pick an interface
2104 * to bind to based on @group.
2106 * If @source_specific is %TRUE, source-specific multicast as defined
2107 * in RFC 4604 is used. Note that on older platforms this may fail
2108 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2110 * Returns: %TRUE on success, %FALSE on error.
2115 g_socket_join_multicast_group (GSocket *socket,
2116 GInetAddress *group,
2117 gboolean source_specific,
2121 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2125 * g_socket_leave_multicast_group:
2126 * @socket: a #GSocket.
2127 * @group: a #GInetAddress specifying the group address to leave.
2128 * @iface: (allow-none): Interface used
2129 * @source_specific: %TRUE if source-specific multicast was used
2130 * @error: #GError for error reporting, or %NULL to ignore.
2132 * Removes @socket from the multicast group defined by @group, @iface,
2133 * and @source_specific (which must all have the same values they had
2134 * when you joined the group).
2136 * @socket remains bound to its address and port, and can still receive
2137 * unicast messages after calling this.
2139 * Returns: %TRUE on success, %FALSE on error.
2144 g_socket_leave_multicast_group (GSocket *socket,
2145 GInetAddress *group,
2146 gboolean source_specific,
2150 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2154 * g_socket_speaks_ipv4:
2155 * @socket: a #GSocket
2157 * Checks if a socket is capable of speaking IPv4.
2159 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2160 * and under some combinations of circumstances IPv6 sockets are also
2161 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2164 * No other types of sockets are currently considered as being capable
2167 * Returns: %TRUE if this socket can be used with IPv4.
2172 g_socket_speaks_ipv4 (GSocket *socket)
2174 switch (socket->priv->family)
2176 case G_SOCKET_FAMILY_IPV4:
2179 case G_SOCKET_FAMILY_IPV6:
2180 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2184 if (!g_socket_get_option (socket,
2185 IPPROTO_IPV6, IPV6_V6ONLY,
2202 * @socket: a #GSocket.
2203 * @cancellable: (allow-none): a %GCancellable or %NULL
2204 * @error: #GError for error reporting, or %NULL to ignore.
2206 * Accept incoming connections on a connection-based socket. This removes
2207 * the first outstanding connection request from the listening socket and
2208 * creates a #GSocket object for it.
2210 * The @socket must be bound to a local address with g_socket_bind() and
2211 * must be listening for incoming connections (g_socket_listen()).
2213 * If there are no outstanding connections then the operation will block
2214 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2215 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2217 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2218 * Free the returned object with g_object_unref().
2223 g_socket_accept (GSocket *socket,
2224 GCancellable *cancellable,
2227 GSocket *new_socket;
2230 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2232 if (!check_socket (socket, error))
2237 if (socket->priv->blocking &&
2238 !g_socket_condition_wait (socket,
2239 G_IO_IN, cancellable, error))
2242 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2244 int errsv = get_socket_errno ();
2246 win32_unset_event_mask (socket, FD_ACCEPT);
2251 if (socket->priv->blocking)
2253 #ifdef WSAEWOULDBLOCK
2254 if (errsv == WSAEWOULDBLOCK)
2257 if (errsv == EWOULDBLOCK ||
2263 g_set_error (error, G_IO_ERROR,
2264 socket_io_error_from_errno (errsv),
2265 _("Error accepting connection: %s"), socket_strerror (errsv));
2271 win32_unset_event_mask (socket, FD_ACCEPT);
2275 /* The socket inherits the accepting sockets event mask and even object,
2276 we need to remove that */
2277 WSAEventSelect (ret, NULL, 0);
2283 /* We always want to set close-on-exec to protect users. If you
2284 need to so some weird inheritance to exec you can re-enable this
2285 using lower level hacks with g_socket_get_fd(). */
2286 flags = fcntl (ret, F_GETFD, 0);
2288 (flags & FD_CLOEXEC) == 0)
2290 flags |= FD_CLOEXEC;
2291 fcntl (ret, F_SETFD, flags);
2296 new_socket = g_socket_new_from_fd (ret, error);
2297 if (new_socket == NULL)
2306 new_socket->priv->protocol = socket->priv->protocol;
2313 * @socket: a #GSocket.
2314 * @address: a #GSocketAddress specifying the remote address.
2315 * @cancellable: (allow-none): a %GCancellable or %NULL
2316 * @error: #GError for error reporting, or %NULL to ignore.
2318 * Connect the socket to the specified remote address.
2320 * For connection oriented socket this generally means we attempt to make
2321 * a connection to the @address. For a connection-less socket it sets
2322 * the default address for g_socket_send() and discards all incoming datagrams
2323 * from other sources.
2325 * Generally connection oriented sockets can only connect once, but
2326 * connection-less sockets can connect multiple times to change the
2329 * If the connect call needs to do network I/O it will block, unless
2330 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2331 * and the user can be notified of the connection finishing by waiting
2332 * for the G_IO_OUT condition. The result of the connection must then be
2333 * checked with g_socket_check_connect_result().
2335 * Returns: %TRUE if connected, %FALSE on error.
2340 g_socket_connect (GSocket *socket,
2341 GSocketAddress *address,
2342 GCancellable *cancellable,
2345 struct sockaddr_storage buffer;
2347 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2349 if (!check_socket (socket, error))
2352 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2355 if (socket->priv->remote_address)
2356 g_object_unref (socket->priv->remote_address);
2357 socket->priv->remote_address = g_object_ref (address);
2361 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2362 g_socket_address_get_native_size (address)) < 0)
2364 int errsv = get_socket_errno ();
2370 if (errsv == EINPROGRESS)
2372 if (errsv == WSAEWOULDBLOCK)
2375 if (socket->priv->blocking)
2377 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2379 if (g_socket_check_connect_result (socket, error))
2385 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2386 _("Connection in progress"));
2387 socket->priv->connect_pending = TRUE;
2391 g_set_error_literal (error, G_IO_ERROR,
2392 socket_io_error_from_errno (errsv),
2393 socket_strerror (errsv));
2400 win32_unset_event_mask (socket, FD_CONNECT);
2402 socket->priv->connected = TRUE;
2408 * g_socket_check_connect_result:
2409 * @socket: a #GSocket
2410 * @error: #GError for error reporting, or %NULL to ignore.
2412 * Checks and resets the pending connect error for the socket.
2413 * This is used to check for errors when g_socket_connect() is
2414 * used in non-blocking mode.
2416 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2421 g_socket_check_connect_result (GSocket *socket,
2426 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2428 if (!check_socket (socket, error))
2431 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
2433 g_prefix_error (error, _("Unable to get pending error: "));
2439 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2440 socket_strerror (value));
2441 if (socket->priv->remote_address)
2443 g_object_unref (socket->priv->remote_address);
2444 socket->priv->remote_address = NULL;
2449 socket->priv->connected = TRUE;
2454 * g_socket_get_available_bytes:
2455 * @socket: a #GSocket
2457 * Get the amount of data pending in the OS input buffer.
2459 * If @socket is a UDP or SCTP socket, this will return the size of
2460 * just the next packet, even if additional packets are buffered after
2463 * Note that on Windows, this function is rather inefficient in the
2464 * UDP case, and so if you know any plausible upper bound on the size
2465 * of the incoming packet, it is better to just do a
2466 * g_socket_receive() with a buffer of that size, rather than calling
2467 * g_socket_get_available_bytes() first and then doing a receive of
2468 * exactly the right size.
2470 * Returns: the number of bytes that can be read from the socket
2471 * without blocking or truncating, or -1 on error.
2476 g_socket_get_available_bytes (GSocket *socket)
2479 const gint bufsize = 64 * 1024;
2480 static guchar *buf = NULL;
2484 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2486 #if defined (SO_NREAD)
2487 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
2489 #elif !defined (G_OS_WIN32)
2490 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2493 if (G_UNLIKELY (g_once_init_enter (&buf)))
2494 g_once_init_leave (&buf, g_malloc (bufsize));
2496 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
2504 * @socket: a #GSocket
2505 * @buffer: (array length=size) (element-type guint8): a buffer to
2506 * read data into (which should be at least @size bytes long).
2507 * @size: the number of bytes you want to read from the socket
2508 * @cancellable: (allow-none): a %GCancellable or %NULL
2509 * @error: #GError for error reporting, or %NULL to ignore.
2511 * Receive data (up to @size bytes) from a socket. This is mainly used by
2512 * connection-oriented sockets; it is identical to g_socket_receive_from()
2513 * with @address set to %NULL.
2515 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2516 * g_socket_receive() will always read either 0 or 1 complete messages from
2517 * the socket. If the received message is too large to fit in @buffer, then
2518 * the data beyond @size bytes will be discarded, without any explicit
2519 * indication that this has occurred.
2521 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2522 * number of bytes, up to @size. If more than @size bytes have been
2523 * received, the additional data will be returned in future calls to
2524 * g_socket_receive().
2526 * If the socket is in blocking mode the call will block until there
2527 * is some data to receive, the connection is closed, or there is an
2528 * error. If there is no data available and the socket is in
2529 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2530 * returned. To be notified when data is available, wait for the
2531 * %G_IO_IN condition.
2533 * On error -1 is returned and @error is set accordingly.
2535 * Returns: Number of bytes read, or 0 if the connection was closed by
2536 * the peer, or -1 on error
2541 g_socket_receive (GSocket *socket,
2544 GCancellable *cancellable,
2547 return g_socket_receive_with_blocking (socket, buffer, size,
2548 socket->priv->blocking,
2549 cancellable, error);
2553 * g_socket_receive_with_blocking:
2554 * @socket: a #GSocket
2555 * @buffer: (array length=size) (element-type guint8): a buffer to
2556 * read data into (which should be at least @size bytes long).
2557 * @size: the number of bytes you want to read from the socket
2558 * @blocking: whether to do blocking or non-blocking I/O
2559 * @cancellable: (allow-none): a %GCancellable or %NULL
2560 * @error: #GError for error reporting, or %NULL to ignore.
2562 * This behaves exactly the same as g_socket_receive(), except that
2563 * the choice of blocking or non-blocking behavior is determined by
2564 * the @blocking argument rather than by @socket's properties.
2566 * Returns: Number of bytes read, or 0 if the connection was closed by
2567 * the peer, or -1 on error
2572 g_socket_receive_with_blocking (GSocket *socket,
2576 GCancellable *cancellable,
2581 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2583 if (!check_socket (socket, error))
2586 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2592 !g_socket_condition_wait (socket,
2593 G_IO_IN, cancellable, error))
2596 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2598 int errsv = get_socket_errno ();
2605 #ifdef WSAEWOULDBLOCK
2606 if (errsv == WSAEWOULDBLOCK)
2609 if (errsv == EWOULDBLOCK ||
2615 win32_unset_event_mask (socket, FD_READ);
2617 g_set_error (error, G_IO_ERROR,
2618 socket_io_error_from_errno (errsv),
2619 _("Error receiving data: %s"), socket_strerror (errsv));
2623 win32_unset_event_mask (socket, FD_READ);
2632 * g_socket_receive_from:
2633 * @socket: a #GSocket
2634 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2636 * @buffer: (array length=size) (element-type guint8): a buffer to
2637 * read data into (which should be at least @size bytes long).
2638 * @size: the number of bytes you want to read from the socket
2639 * @cancellable: (allow-none): a %GCancellable or %NULL
2640 * @error: #GError for error reporting, or %NULL to ignore.
2642 * Receive data (up to @size bytes) from a socket.
2644 * If @address is non-%NULL then @address will be set equal to the
2645 * source address of the received packet.
2646 * @address is owned by the caller.
2648 * See g_socket_receive() for additional information.
2650 * Returns: Number of bytes read, or 0 if the connection was closed by
2651 * the peer, or -1 on error
2656 g_socket_receive_from (GSocket *socket,
2657 GSocketAddress **address,
2660 GCancellable *cancellable,
2668 return g_socket_receive_message (socket,
2676 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2677 * one, which can be confusing and annoying. So if possible, we want
2678 * to suppress the signal entirely.
2681 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2683 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2688 * @socket: a #GSocket
2689 * @buffer: (array length=size) (element-type guint8): the buffer
2690 * containing the data to send.
2691 * @size: the number of bytes to send
2692 * @cancellable: (allow-none): a %GCancellable or %NULL
2693 * @error: #GError for error reporting, or %NULL to ignore.
2695 * Tries to send @size bytes from @buffer on the socket. This is
2696 * mainly used by connection-oriented sockets; it is identical to
2697 * g_socket_send_to() with @address set to %NULL.
2699 * If the socket is in blocking mode the call will block until there is
2700 * space for the data in the socket queue. If there is no space available
2701 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2702 * will be returned. To be notified when space is available, wait for the
2703 * %G_IO_OUT condition. Note though that you may still receive
2704 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2705 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2706 * very common due to the way the underlying APIs work.)
2708 * On error -1 is returned and @error is set accordingly.
2710 * Returns: Number of bytes written (which may be less than @size), or -1
2716 g_socket_send (GSocket *socket,
2717 const gchar *buffer,
2719 GCancellable *cancellable,
2722 return g_socket_send_with_blocking (socket, buffer, size,
2723 socket->priv->blocking,
2724 cancellable, error);
2728 * g_socket_send_with_blocking:
2729 * @socket: a #GSocket
2730 * @buffer: (array length=size) (element-type guint8): the buffer
2731 * containing the data to send.
2732 * @size: the number of bytes to send
2733 * @blocking: whether to do blocking or non-blocking I/O
2734 * @cancellable: (allow-none): a %GCancellable or %NULL
2735 * @error: #GError for error reporting, or %NULL to ignore.
2737 * This behaves exactly the same as g_socket_send(), except that
2738 * the choice of blocking or non-blocking behavior is determined by
2739 * the @blocking argument rather than by @socket's properties.
2741 * Returns: Number of bytes written (which may be less than @size), or -1
2747 g_socket_send_with_blocking (GSocket *socket,
2748 const gchar *buffer,
2751 GCancellable *cancellable,
2756 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2758 if (!check_socket (socket, error))
2761 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2767 !g_socket_condition_wait (socket,
2768 G_IO_OUT, cancellable, error))
2771 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2773 int errsv = get_socket_errno ();
2778 #ifdef WSAEWOULDBLOCK
2779 if (errsv == WSAEWOULDBLOCK)
2780 win32_unset_event_mask (socket, FD_WRITE);
2785 #ifdef WSAEWOULDBLOCK
2786 if (errsv == WSAEWOULDBLOCK)
2789 if (errsv == EWOULDBLOCK ||
2795 g_set_error (error, G_IO_ERROR,
2796 socket_io_error_from_errno (errsv),
2797 _("Error sending data: %s"), socket_strerror (errsv));
2808 * @socket: a #GSocket
2809 * @address: (allow-none): a #GSocketAddress, or %NULL
2810 * @buffer: (array length=size) (element-type guint8): the buffer
2811 * containing the data to send.
2812 * @size: the number of bytes to send
2813 * @cancellable: (allow-none): a %GCancellable or %NULL
2814 * @error: #GError for error reporting, or %NULL to ignore.
2816 * Tries to send @size bytes from @buffer to @address. If @address is
2817 * %NULL then the message is sent to the default receiver (set by
2818 * g_socket_connect()).
2820 * See g_socket_send() for additional information.
2822 * Returns: Number of bytes written (which may be less than @size), or -1
2828 g_socket_send_to (GSocket *socket,
2829 GSocketAddress *address,
2830 const gchar *buffer,
2832 GCancellable *cancellable,
2840 return g_socket_send_message (socket,
2850 * g_socket_shutdown:
2851 * @socket: a #GSocket
2852 * @shutdown_read: whether to shut down the read side
2853 * @shutdown_write: whether to shut down the write side
2854 * @error: #GError for error reporting, or %NULL to ignore.
2856 * Shut down part of a full-duplex connection.
2858 * If @shutdown_read is %TRUE then the receiving side of the connection
2859 * is shut down, and further reading is disallowed.
2861 * If @shutdown_write is %TRUE then the sending side of the connection
2862 * is shut down, and further writing is disallowed.
2864 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2866 * One example where this is used is graceful disconnect for TCP connections
2867 * where you close the sending side, then wait for the other side to close
2868 * the connection, thus ensuring that the other side saw all sent data.
2870 * Returns: %TRUE on success, %FALSE on error
2875 g_socket_shutdown (GSocket *socket,
2876 gboolean shutdown_read,
2877 gboolean shutdown_write,
2882 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2884 if (!check_socket (socket, error))
2888 if (!shutdown_read && !shutdown_write)
2892 if (shutdown_read && shutdown_write)
2894 else if (shutdown_read)
2899 if (shutdown_read && shutdown_write)
2901 else if (shutdown_read)
2907 if (shutdown (socket->priv->fd, how) != 0)
2909 int errsv = get_socket_errno ();
2910 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2911 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2915 if (shutdown_read && shutdown_write)
2916 socket->priv->connected = FALSE;
2923 * @socket: a #GSocket
2924 * @error: #GError for error reporting, or %NULL to ignore.
2926 * Closes the socket, shutting down any active connection.
2928 * Closing a socket does not wait for all outstanding I/O operations
2929 * to finish, so the caller should not rely on them to be guaranteed
2930 * to complete even if the close returns with no error.
2932 * Once the socket is closed, all other operations will return
2933 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2936 * Sockets will be automatically closed when the last reference
2937 * is dropped, but you might want to call this function to make sure
2938 * resources are released as early as possible.
2940 * Beware that due to the way that TCP works, it is possible for
2941 * recently-sent data to be lost if either you close a socket while the
2942 * %G_IO_IN condition is set, or else if the remote connection tries to
2943 * send something to you after you close the socket but before it has
2944 * finished reading all of the data you sent. There is no easy generic
2945 * way to avoid this problem; the easiest fix is to design the network
2946 * protocol such that the client will never send data "out of turn".
2947 * Another solution is for the server to half-close the connection by
2948 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2949 * and then wait for the client to notice this and close its side of the
2950 * connection, after which the server can safely call g_socket_close().
2951 * (This is what #GTcpConnection does if you call
2952 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2953 * only works if the client will close its connection after the server
2956 * Returns: %TRUE on success, %FALSE on error
2961 g_socket_close (GSocket *socket,
2966 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2968 if (socket->priv->closed)
2969 return TRUE; /* Multiple close not an error */
2971 if (!check_socket (socket, error))
2977 res = closesocket (socket->priv->fd);
2979 res = close (socket->priv->fd);
2983 int errsv = get_socket_errno ();
2988 g_set_error (error, G_IO_ERROR,
2989 socket_io_error_from_errno (errsv),
2990 _("Error closing socket: %s"),
2991 socket_strerror (errsv));
2997 socket->priv->connected = FALSE;
2998 socket->priv->closed = TRUE;
2999 if (socket->priv->remote_address)
3001 g_object_unref (socket->priv->remote_address);
3002 socket->priv->remote_address = NULL;
3009 * g_socket_is_closed:
3010 * @socket: a #GSocket
3012 * Checks whether a socket is closed.
3014 * Returns: %TRUE if socket is closed, %FALSE otherwise
3019 g_socket_is_closed (GSocket *socket)
3021 return socket->priv->closed;
3025 /* Broken source, used on errors */
3027 broken_dispatch (GSource *source,
3028 GSourceFunc callback,
3034 static GSourceFuncs broken_funcs =
3043 network_events_for_condition (GIOCondition condition)
3047 if (condition & G_IO_IN)
3048 event_mask |= (FD_READ | FD_ACCEPT);
3049 if (condition & G_IO_OUT)
3050 event_mask |= (FD_WRITE | FD_CONNECT);
3051 event_mask |= FD_CLOSE;
3057 ensure_event (GSocket *socket)
3059 if (socket->priv->event == WSA_INVALID_EVENT)
3060 socket->priv->event = WSACreateEvent();
3064 update_select_events (GSocket *socket)
3071 ensure_event (socket);
3074 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3077 event_mask |= network_events_for_condition (*ptr);
3080 if (event_mask != socket->priv->selected_events)
3082 /* If no events selected, disable event so we can unset
3085 if (event_mask == 0)
3088 event = socket->priv->event;
3090 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3091 socket->priv->selected_events = event_mask;
3096 add_condition_watch (GSocket *socket,
3097 GIOCondition *condition)
3099 g_mutex_lock (&socket->priv->win32_source_lock);
3100 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3102 socket->priv->requested_conditions =
3103 g_list_prepend (socket->priv->requested_conditions, condition);
3105 update_select_events (socket);
3106 g_mutex_unlock (&socket->priv->win32_source_lock);
3110 remove_condition_watch (GSocket *socket,
3111 GIOCondition *condition)
3113 g_mutex_lock (&socket->priv->win32_source_lock);
3114 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3116 socket->priv->requested_conditions =
3117 g_list_remove (socket->priv->requested_conditions, condition);
3119 update_select_events (socket);
3120 g_mutex_unlock (&socket->priv->win32_source_lock);
3124 update_condition (GSocket *socket)
3126 WSANETWORKEVENTS events;
3127 GIOCondition condition;
3129 if (WSAEnumNetworkEvents (socket->priv->fd,
3130 socket->priv->event,
3133 socket->priv->current_events |= events.lNetworkEvents;
3134 if (events.lNetworkEvents & FD_WRITE &&
3135 events.iErrorCode[FD_WRITE_BIT] != 0)
3136 socket->priv->current_errors |= FD_WRITE;
3137 if (events.lNetworkEvents & FD_CONNECT &&
3138 events.iErrorCode[FD_CONNECT_BIT] != 0)
3139 socket->priv->current_errors |= FD_CONNECT;
3143 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3144 condition |= G_IO_IN;
3146 if (socket->priv->current_events & FD_CLOSE)
3148 int r, errsv, buffer;
3150 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3152 errsv = get_socket_errno ();
3155 (r < 0 && errsv == WSAENOTCONN))
3156 condition |= G_IO_IN;
3158 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3159 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3160 condition |= G_IO_HUP;
3162 condition |= G_IO_ERR;
3165 if (socket->priv->closed)
3166 condition |= G_IO_HUP;
3168 /* Never report both G_IO_OUT and HUP, these are
3169 mutually exclusive (can't write to a closed socket) */
3170 if ((condition & G_IO_HUP) == 0 &&
3171 socket->priv->current_events & FD_WRITE)
3173 if (socket->priv->current_errors & FD_WRITE)
3174 condition |= G_IO_ERR;
3176 condition |= G_IO_OUT;
3180 if (socket->priv->current_events & FD_CONNECT)
3182 if (socket->priv->current_errors & FD_CONNECT)
3183 condition |= (G_IO_HUP | G_IO_ERR);
3185 condition |= G_IO_OUT;
3197 GIOCondition condition;
3198 GCancellable *cancellable;
3199 GPollFD cancel_pollfd;
3200 gint64 timeout_time;
3204 socket_source_prepare (GSource *source,
3207 GSocketSource *socket_source = (GSocketSource *)source;
3209 if (g_cancellable_is_cancelled (socket_source->cancellable))
3212 if (socket_source->timeout_time)
3216 now = g_source_get_time (source);
3217 /* Round up to ensure that we don't try again too early */
3218 *timeout = (socket_source->timeout_time - now + 999) / 1000;
3221 socket_source->socket->priv->timed_out = TRUE;
3230 socket_source->pollfd.revents = update_condition (socket_source->socket);
3233 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
3240 socket_source_check (GSource *source)
3244 return socket_source_prepare (source, &timeout);
3248 socket_source_dispatch (GSource *source,
3249 GSourceFunc callback,
3252 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3253 GSocketSource *socket_source = (GSocketSource *)source;
3254 GSocket *socket = socket_source->socket;
3258 socket_source->pollfd.revents = update_condition (socket_source->socket);
3260 if (socket_source->socket->priv->timed_out)
3261 socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
3263 ret = (*func) (socket,
3264 socket_source->pollfd.revents & socket_source->condition,
3267 if (socket->priv->timeout)
3268 socket_source->timeout_time = g_get_monotonic_time () +
3269 socket->priv->timeout * 1000000;
3272 socket_source->timeout_time = 0;
3278 socket_source_finalize (GSource *source)
3280 GSocketSource *socket_source = (GSocketSource *)source;
3283 socket = socket_source->socket;
3286 remove_condition_watch (socket, &socket_source->condition);
3289 g_object_unref (socket);
3291 if (socket_source->cancellable)
3293 g_cancellable_release_fd (socket_source->cancellable);
3294 g_object_unref (socket_source->cancellable);
3299 socket_source_closure_callback (GSocket *socket,
3300 GIOCondition condition,
3303 GClosure *closure = data;
3305 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3306 GValue result_value = G_VALUE_INIT;
3309 g_value_init (&result_value, G_TYPE_BOOLEAN);
3311 g_value_init (¶ms[0], G_TYPE_SOCKET);
3312 g_value_set_object (¶ms[0], socket);
3313 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
3314 g_value_set_flags (¶ms[1], condition);
3316 g_closure_invoke (closure, &result_value, 2, params, NULL);
3318 result = g_value_get_boolean (&result_value);
3319 g_value_unset (&result_value);
3320 g_value_unset (¶ms[0]);
3321 g_value_unset (¶ms[1]);
3326 static GSourceFuncs socket_source_funcs =
3328 socket_source_prepare,
3329 socket_source_check,
3330 socket_source_dispatch,
3331 socket_source_finalize,
3332 (GSourceFunc)socket_source_closure_callback,
3336 socket_source_new (GSocket *socket,
3337 GIOCondition condition,
3338 GCancellable *cancellable)
3341 GSocketSource *socket_source;
3344 ensure_event (socket);
3346 if (socket->priv->event == WSA_INVALID_EVENT)
3348 g_warning ("Failed to create WSAEvent");
3349 return g_source_new (&broken_funcs, sizeof (GSource));
3353 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
3355 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3356 g_source_set_name (source, "GSocket");
3357 socket_source = (GSocketSource *)source;
3359 socket_source->socket = g_object_ref (socket);
3360 socket_source->condition = condition;
3362 if (g_cancellable_make_pollfd (cancellable,
3363 &socket_source->cancel_pollfd))
3365 socket_source->cancellable = g_object_ref (cancellable);
3366 g_source_add_poll (source, &socket_source->cancel_pollfd);
3370 add_condition_watch (socket, &socket_source->condition);
3371 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3373 socket_source->pollfd.fd = socket->priv->fd;
3376 socket_source->pollfd.events = condition;
3377 socket_source->pollfd.revents = 0;
3378 g_source_add_poll (source, &socket_source->pollfd);
3380 if (socket->priv->timeout)
3381 socket_source->timeout_time = g_get_monotonic_time () +
3382 socket->priv->timeout * 1000000;
3385 socket_source->timeout_time = 0;
3391 * g_socket_create_source: (skip)
3392 * @socket: a #GSocket
3393 * @condition: a #GIOCondition mask to monitor
3394 * @cancellable: (allow-none): a %GCancellable or %NULL
3396 * Creates a %GSource that can be attached to a %GMainContext to monitor
3397 * for the availibility of the specified @condition on the socket.
3399 * The callback on the source is of the #GSocketSourceFunc type.
3401 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3402 * these conditions will always be reported output if they are true.
3404 * @cancellable if not %NULL can be used to cancel the source, which will
3405 * cause the source to trigger, reporting the current condition (which
3406 * is likely 0 unless cancellation happened at the same time as a
3407 * condition change). You can check for this in the callback using
3408 * g_cancellable_is_cancelled().
3410 * If @socket has a timeout set, and it is reached before @condition
3411 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3412 * %G_IO_OUT depending on @condition. However, @socket will have been
3413 * marked as having had a timeout, and so the next #GSocket I/O method
3414 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3416 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3421 g_socket_create_source (GSocket *socket,
3422 GIOCondition condition,
3423 GCancellable *cancellable)
3425 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3427 return socket_source_new (socket, condition, cancellable);
3431 * g_socket_condition_check:
3432 * @socket: a #GSocket
3433 * @condition: a #GIOCondition mask to check
3435 * Checks on the readiness of @socket to perform operations.
3436 * The operations specified in @condition are checked for and masked
3437 * against the currently-satisfied conditions on @socket. The result
3440 * Note that on Windows, it is possible for an operation to return
3441 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3442 * g_socket_condition_check() has claimed that the socket is ready for
3443 * writing. Rather than calling g_socket_condition_check() and then
3444 * writing to the socket if it succeeds, it is generally better to
3445 * simply try writing to the socket right away, and try again later if
3446 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3448 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3449 * these conditions will always be set in the output if they are true.
3451 * This call never blocks.
3453 * Returns: the @GIOCondition mask of the current state
3458 g_socket_condition_check (GSocket *socket,
3459 GIOCondition condition)
3461 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3463 if (!check_socket (socket, NULL))
3468 GIOCondition current_condition;
3470 condition |= G_IO_ERR | G_IO_HUP;
3472 add_condition_watch (socket, &condition);
3473 current_condition = update_condition (socket);
3474 remove_condition_watch (socket, &condition);
3475 return condition & current_condition;
3481 poll_fd.fd = socket->priv->fd;
3482 poll_fd.events = condition;
3483 poll_fd.revents = 0;
3486 result = g_poll (&poll_fd, 1, 0);
3487 while (result == -1 && get_socket_errno () == EINTR);
3489 return poll_fd.revents;
3495 * g_socket_condition_wait:
3496 * @socket: a #GSocket
3497 * @condition: a #GIOCondition mask to wait for
3498 * @cancellable: (allow-none): a #GCancellable, or %NULL
3499 * @error: a #GError pointer, or %NULL
3501 * Waits for @condition to become true on @socket. When the condition
3502 * is met, %TRUE is returned.
3504 * If @cancellable is cancelled before the condition is met, or if the
3505 * socket has a timeout set and it is reached before the condition is
3506 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3507 * the appropriate value (%G_IO_ERROR_CANCELLED or
3508 * %G_IO_ERROR_TIMED_OUT).
3510 * See also g_socket_condition_timed_wait().
3512 * Returns: %TRUE if the condition was met, %FALSE otherwise
3517 g_socket_condition_wait (GSocket *socket,
3518 GIOCondition condition,
3519 GCancellable *cancellable,
3522 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3524 return g_socket_condition_timed_wait (socket, condition, -1,
3525 cancellable, error);
3529 * g_socket_condition_timed_wait:
3530 * @socket: a #GSocket
3531 * @condition: a #GIOCondition mask to wait for
3532 * @timeout: the maximum time (in microseconds) to wait, or -1
3533 * @cancellable: (allow-none): a #GCancellable, or %NULL
3534 * @error: a #GError pointer, or %NULL
3536 * Waits for up to @timeout microseconds for @condition to become true
3537 * on @socket. If the condition is met, %TRUE is returned.
3539 * If @cancellable is cancelled before the condition is met, or if
3540 * @timeout (or the socket's #GSocket:timeout) is reached before the
3541 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3542 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3543 * %G_IO_ERROR_TIMED_OUT).
3545 * If you don't want a timeout, use g_socket_condition_wait().
3546 * (Alternatively, you can pass -1 for @timeout.)
3548 * Note that although @timeout is in microseconds for consistency with
3549 * other GLib APIs, this function actually only has millisecond
3550 * resolution, and the behavior is undefined if @timeout is not an
3551 * exact number of milliseconds.
3553 * Returns: %TRUE if the condition was met, %FALSE otherwise
3558 g_socket_condition_timed_wait (GSocket *socket,
3559 GIOCondition condition,
3561 GCancellable *cancellable,
3566 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3568 if (!check_socket (socket, error))
3571 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3574 if (socket->priv->timeout &&
3575 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3576 timeout = socket->priv->timeout * 1000;
3577 else if (timeout != -1)
3578 timeout = timeout / 1000;
3580 start_time = g_get_monotonic_time ();
3584 GIOCondition current_condition;
3590 /* Always check these */
3591 condition |= G_IO_ERR | G_IO_HUP;
3593 add_condition_watch (socket, &condition);
3596 events[num_events++] = socket->priv->event;
3598 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3599 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3602 timeout = WSA_INFINITE;
3604 current_condition = update_condition (socket);
3605 while ((condition & current_condition) == 0)
3607 res = WSAWaitForMultipleEvents (num_events, events,
3608 FALSE, timeout, FALSE);
3609 if (res == WSA_WAIT_FAILED)
3611 int errsv = get_socket_errno ();
3613 g_set_error (error, G_IO_ERROR,
3614 socket_io_error_from_errno (errsv),
3615 _("Waiting for socket condition: %s"),
3616 socket_strerror (errsv));
3619 else if (res == WSA_WAIT_TIMEOUT)
3621 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3622 _("Socket I/O timed out"));
3626 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3629 current_condition = update_condition (socket);
3631 if (timeout != WSA_INFINITE)
3633 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3638 remove_condition_watch (socket, &condition);
3640 g_cancellable_release_fd (cancellable);
3642 return (condition & current_condition) != 0;
3650 poll_fd[0].fd = socket->priv->fd;
3651 poll_fd[0].events = condition;
3654 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3659 result = g_poll (poll_fd, num, timeout);
3660 if (result != -1 || errno != EINTR)
3665 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3672 g_cancellable_release_fd (cancellable);
3676 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3677 _("Socket I/O timed out"));
3681 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3687 * g_socket_send_message:
3688 * @socket: a #GSocket
3689 * @address: (allow-none): a #GSocketAddress, or %NULL
3690 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3691 * @num_vectors: the number of elements in @vectors, or -1
3692 * @messages: (array length=num_messages) (allow-none): a pointer to an
3693 * array of #GSocketControlMessages, or %NULL.
3694 * @num_messages: number of elements in @messages, or -1.
3695 * @flags: an int containing #GSocketMsgFlags flags
3696 * @cancellable: (allow-none): a %GCancellable or %NULL
3697 * @error: #GError for error reporting, or %NULL to ignore.
3699 * Send data to @address on @socket. This is the most complicated and
3700 * fully-featured version of this call. For easier use, see
3701 * g_socket_send() and g_socket_send_to().
3703 * If @address is %NULL then the message is sent to the default receiver
3704 * (set by g_socket_connect()).
3706 * @vectors must point to an array of #GOutputVector structs and
3707 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3708 * then @vectors is assumed to be terminated by a #GOutputVector with a
3709 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3710 * that the sent data will be gathered from. Using multiple
3711 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3712 * data from multiple sources into a single buffer, and more
3713 * network-efficient than making multiple calls to g_socket_send().
3715 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3716 * #GSocketControlMessage instances. These correspond to the control
3717 * messages to be sent on the socket.
3718 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3721 * @flags modify how the message is sent. The commonly available arguments
3722 * for this are available in the #GSocketMsgFlags enum, but the
3723 * values there are the same as the system values, and the flags
3724 * are passed in as-is, so you can pass in system-specific flags too.
3726 * If the socket is in blocking mode the call will block until there is
3727 * space for the data in the socket queue. If there is no space available
3728 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3729 * will be returned. To be notified when space is available, wait for the
3730 * %G_IO_OUT condition. Note though that you may still receive
3731 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3732 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3733 * very common due to the way the underlying APIs work.)
3735 * On error -1 is returned and @error is set accordingly.
3737 * Returns: Number of bytes written (which may be less than @size), or -1
3743 g_socket_send_message (GSocket *socket,
3744 GSocketAddress *address,
3745 GOutputVector *vectors,
3747 GSocketControlMessage **messages,
3750 GCancellable *cancellable,
3753 GOutputVector one_vector;
3756 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3758 if (!check_socket (socket, error))
3761 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3764 if (num_vectors == -1)
3766 for (num_vectors = 0;
3767 vectors[num_vectors].buffer != NULL;
3772 if (num_messages == -1)
3774 for (num_messages = 0;
3775 messages != NULL && messages[num_messages] != NULL;
3780 if (num_vectors == 0)
3784 one_vector.buffer = &zero;
3785 one_vector.size = 1;
3787 vectors = &one_vector;
3800 msg.msg_namelen = g_socket_address_get_native_size (address);
3801 msg.msg_name = g_alloca (msg.msg_namelen);
3802 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3807 msg.msg_name = NULL;
3808 msg.msg_namelen = 0;
3813 /* this entire expression will be evaluated at compile time */
3814 if (sizeof *msg.msg_iov == sizeof *vectors &&
3815 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3816 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3817 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3818 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3819 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3820 G_STRUCT_OFFSET (GOutputVector, size))
3821 /* ABI is compatible */
3823 msg.msg_iov = (struct iovec *) vectors;
3824 msg.msg_iovlen = num_vectors;
3827 /* ABI is incompatible */
3831 msg.msg_iov = g_newa (struct iovec, num_vectors);
3832 for (i = 0; i < num_vectors; i++)
3834 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3835 msg.msg_iov[i].iov_len = vectors[i].size;
3837 msg.msg_iovlen = num_vectors;
3843 struct cmsghdr *cmsg;
3846 msg.msg_controllen = 0;
3847 for (i = 0; i < num_messages; i++)
3848 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3850 if (msg.msg_controllen == 0)
3851 msg.msg_control = NULL;
3854 msg.msg_control = g_alloca (msg.msg_controllen);
3855 memset (msg.msg_control, '\0', msg.msg_controllen);
3858 cmsg = CMSG_FIRSTHDR (&msg);
3859 for (i = 0; i < num_messages; i++)
3861 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3862 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3863 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3864 g_socket_control_message_serialize (messages[i],
3866 cmsg = CMSG_NXTHDR (&msg, cmsg);
3868 g_assert (cmsg == NULL);
3873 if (socket->priv->blocking &&
3874 !g_socket_condition_wait (socket,
3875 G_IO_OUT, cancellable, error))
3878 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3881 int errsv = get_socket_errno ();
3886 if (socket->priv->blocking &&
3887 (errsv == EWOULDBLOCK ||
3891 g_set_error (error, G_IO_ERROR,
3892 socket_io_error_from_errno (errsv),
3893 _("Error sending message: %s"), socket_strerror (errsv));
3904 struct sockaddr_storage addr;
3911 /* Win32 doesn't support control messages.
3912 Actually this is possible for raw and datagram sockets
3913 via WSASendMessage on Vista or later, but that doesn't
3915 if (num_messages != 0)
3917 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3918 _("GSocketControlMessage not supported on Windows"));
3923 bufs = g_newa (WSABUF, num_vectors);
3924 for (i = 0; i < num_vectors; i++)
3926 bufs[i].buf = (char *)vectors[i].buffer;
3927 bufs[i].len = (gulong)vectors[i].size;
3931 addrlen = 0; /* Avoid warning */
3934 addrlen = g_socket_address_get_native_size (address);
3935 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3941 if (socket->priv->blocking &&
3942 !g_socket_condition_wait (socket,
3943 G_IO_OUT, cancellable, error))
3947 result = WSASendTo (socket->priv->fd,
3950 (const struct sockaddr *)&addr, addrlen,
3953 result = WSASend (socket->priv->fd,
3960 int errsv = get_socket_errno ();
3962 if (errsv == WSAEINTR)
3965 if (errsv == WSAEWOULDBLOCK)
3966 win32_unset_event_mask (socket, FD_WRITE);
3968 if (socket->priv->blocking &&
3969 errsv == WSAEWOULDBLOCK)
3972 g_set_error (error, G_IO_ERROR,
3973 socket_io_error_from_errno (errsv),
3974 _("Error sending message: %s"), socket_strerror (errsv));
3986 static GSocketAddress *
3987 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
3989 GSocketAddress *saddr;
3991 guint64 oldest_time = G_MAXUINT64;
3992 gint oldest_index = 0;
3994 if (native_len <= 0)
3998 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
4000 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
4001 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
4002 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
4007 if (tmp_native_len != native_len)
4010 if (memcmp (tmp_native, native, native_len) == 0)
4012 saddr = g_object_ref (tmp);
4013 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
4017 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
4019 oldest_time = socket->priv->recv_addr_cache[i].last_used;
4024 saddr = g_socket_address_new_from_native (native, native_len);
4026 if (socket->priv->recv_addr_cache[oldest_index].addr)
4028 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
4029 g_free (socket->priv->recv_addr_cache[oldest_index].native);
4032 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
4033 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
4034 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
4035 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
4041 * g_socket_receive_message:
4042 * @socket: a #GSocket
4043 * @address: (out) (allow-none): a pointer to a #GSocketAddress
4045 * @vectors: (array length=num_vectors): an array of #GInputVector structs
4046 * @num_vectors: the number of elements in @vectors, or -1
4047 * @messages: (array length=num_messages) (allow-none): a pointer which
4048 * may be filled with an array of #GSocketControlMessages, or %NULL
4049 * @num_messages: a pointer which will be filled with the number of
4050 * elements in @messages, or %NULL
4051 * @flags: a pointer to an int containing #GSocketMsgFlags flags
4052 * @cancellable: (allow-none): a %GCancellable or %NULL
4053 * @error: a #GError pointer, or %NULL
4055 * Receive data from a socket. This is the most complicated and
4056 * fully-featured version of this call. For easier use, see
4057 * g_socket_receive() and g_socket_receive_from().
4059 * If @address is non-%NULL then @address will be set equal to the
4060 * source address of the received packet.
4061 * @address is owned by the caller.
4063 * @vector must point to an array of #GInputVector structs and
4064 * @num_vectors must be the length of this array. These structs
4065 * describe the buffers that received data will be scattered into.
4066 * If @num_vectors is -1, then @vectors is assumed to be terminated
4067 * by a #GInputVector with a %NULL buffer pointer.
4069 * As a special case, if @num_vectors is 0 (in which case, @vectors
4070 * may of course be %NULL), then a single byte is received and
4071 * discarded. This is to facilitate the common practice of sending a
4072 * single '\0' byte for the purposes of transferring ancillary data.
4074 * @messages, if non-%NULL, will be set to point to a newly-allocated
4075 * array of #GSocketControlMessage instances or %NULL if no such
4076 * messages was received. These correspond to the control messages
4077 * received from the kernel, one #GSocketControlMessage per message
4078 * from the kernel. This array is %NULL-terminated and must be freed
4079 * by the caller using g_free() after calling g_object_unref() on each
4080 * element. If @messages is %NULL, any control messages received will
4083 * @num_messages, if non-%NULL, will be set to the number of control
4084 * messages received.
4086 * If both @messages and @num_messages are non-%NULL, then
4087 * @num_messages gives the number of #GSocketControlMessage instances
4088 * in @messages (ie: not including the %NULL terminator).
4090 * @flags is an in/out parameter. The commonly available arguments
4091 * for this are available in the #GSocketMsgFlags enum, but the
4092 * values there are the same as the system values, and the flags
4093 * are passed in as-is, so you can pass in system-specific flags too
4094 * (and g_socket_receive_message() may pass system-specific flags out).
4096 * As with g_socket_receive(), data may be discarded if @socket is
4097 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
4098 * provide enough buffer space to read a complete message. You can pass
4099 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
4100 * removing it from the receive queue, but there is no portable way to find
4101 * out the length of the message other than by reading it into a
4102 * sufficiently-large buffer.
4104 * If the socket is in blocking mode the call will block until there
4105 * is some data to receive, the connection is closed, or there is an
4106 * error. If there is no data available and the socket is in
4107 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
4108 * returned. To be notified when data is available, wait for the
4109 * %G_IO_IN condition.
4111 * On error -1 is returned and @error is set accordingly.
4113 * Returns: Number of bytes read, or 0 if the connection was closed by
4114 * the peer, or -1 on error
4119 g_socket_receive_message (GSocket *socket,
4120 GSocketAddress **address,
4121 GInputVector *vectors,
4123 GSocketControlMessage ***messages,
4126 GCancellable *cancellable,
4129 GInputVector one_vector;
4132 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4134 if (!check_socket (socket, error))
4137 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4140 if (num_vectors == -1)
4142 for (num_vectors = 0;
4143 vectors[num_vectors].buffer != NULL;
4148 if (num_vectors == 0)
4150 one_vector.buffer = &one_byte;
4151 one_vector.size = 1;
4153 vectors = &one_vector;
4160 struct sockaddr_storage one_sockaddr;
4165 msg.msg_name = &one_sockaddr;
4166 msg.msg_namelen = sizeof (struct sockaddr_storage);
4170 msg.msg_name = NULL;
4171 msg.msg_namelen = 0;
4175 /* this entire expression will be evaluated at compile time */
4176 if (sizeof *msg.msg_iov == sizeof *vectors &&
4177 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4178 G_STRUCT_OFFSET (struct iovec, iov_base) ==
4179 G_STRUCT_OFFSET (GInputVector, buffer) &&
4180 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4181 G_STRUCT_OFFSET (struct iovec, iov_len) ==
4182 G_STRUCT_OFFSET (GInputVector, size))
4183 /* ABI is compatible */
4185 msg.msg_iov = (struct iovec *) vectors;
4186 msg.msg_iovlen = num_vectors;
4189 /* ABI is incompatible */
4193 msg.msg_iov = g_newa (struct iovec, num_vectors);
4194 for (i = 0; i < num_vectors; i++)
4196 msg.msg_iov[i].iov_base = vectors[i].buffer;
4197 msg.msg_iov[i].iov_len = vectors[i].size;
4199 msg.msg_iovlen = num_vectors;
4203 msg.msg_control = g_alloca (2048);
4204 msg.msg_controllen = 2048;
4208 msg.msg_flags = *flags;
4212 /* We always set the close-on-exec flag so we don't leak file
4213 * descriptors into child processes. Note that gunixfdmessage.c
4214 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4216 #ifdef MSG_CMSG_CLOEXEC
4217 msg.msg_flags |= MSG_CMSG_CLOEXEC;
4223 if (socket->priv->blocking &&
4224 !g_socket_condition_wait (socket,
4225 G_IO_IN, cancellable, error))
4228 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4229 #ifdef MSG_CMSG_CLOEXEC
4230 if (result < 0 && get_socket_errno () == EINVAL)
4232 /* We must be running on an old kernel. Call without the flag. */
4233 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4234 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4240 int errsv = get_socket_errno ();
4245 if (socket->priv->blocking &&
4246 (errsv == EWOULDBLOCK ||
4250 g_set_error (error, G_IO_ERROR,
4251 socket_io_error_from_errno (errsv),
4252 _("Error receiving message: %s"), socket_strerror (errsv));
4259 /* decode address */
4260 if (address != NULL)
4262 *address = cache_recv_address (socket, msg.msg_name, msg.msg_namelen);
4265 /* decode control messages */
4267 GPtrArray *my_messages = NULL;
4268 struct cmsghdr *cmsg;
4270 if (msg.msg_controllen >= sizeof (struct cmsghdr))
4272 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4274 GSocketControlMessage *message;
4276 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4278 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4280 if (message == NULL)
4281 /* We've already spewed about the problem in the
4282 deserialization code, so just continue */
4285 if (messages == NULL)
4287 /* we have to do it this way if the user ignores the
4288 * messages so that we will close any received fds.
4290 g_object_unref (message);
4294 if (my_messages == NULL)
4295 my_messages = g_ptr_array_new ();
4296 g_ptr_array_add (my_messages, message);
4302 *num_messages = my_messages != NULL ? my_messages->len : 0;
4306 if (my_messages == NULL)
4312 g_ptr_array_add (my_messages, NULL);
4313 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4318 g_assert (my_messages == NULL);
4322 /* capture the flags */
4324 *flags = msg.msg_flags;
4330 struct sockaddr_storage addr;
4332 DWORD bytes_received;
4339 bufs = g_newa (WSABUF, num_vectors);
4340 for (i = 0; i < num_vectors; i++)
4342 bufs[i].buf = (char *)vectors[i].buffer;
4343 bufs[i].len = (gulong)vectors[i].size;
4355 if (socket->priv->blocking &&
4356 !g_socket_condition_wait (socket,
4357 G_IO_IN, cancellable, error))
4360 addrlen = sizeof addr;
4362 result = WSARecvFrom (socket->priv->fd,
4364 &bytes_received, &win_flags,
4365 (struct sockaddr *)&addr, &addrlen,
4368 result = WSARecv (socket->priv->fd,
4370 &bytes_received, &win_flags,
4374 int errsv = get_socket_errno ();
4376 if (errsv == WSAEINTR)
4379 win32_unset_event_mask (socket, FD_READ);
4381 if (socket->priv->blocking &&
4382 errsv == WSAEWOULDBLOCK)
4385 g_set_error (error, G_IO_ERROR,
4386 socket_io_error_from_errno (errsv),
4387 _("Error receiving message: %s"), socket_strerror (errsv));
4391 win32_unset_event_mask (socket, FD_READ);
4395 /* decode address */
4396 if (address != NULL)
4398 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
4401 /* capture the flags */
4405 if (messages != NULL)
4407 if (num_messages != NULL)
4410 return bytes_received;
4416 * g_socket_get_credentials:
4417 * @socket: a #GSocket.
4418 * @error: #GError for error reporting, or %NULL to ignore.
4420 * Returns the credentials of the foreign process connected to this
4421 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4424 * If this operation isn't supported on the OS, the method fails with
4425 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4426 * by reading the %SO_PEERCRED option on the underlying socket.
4428 * Other ways to obtain credentials from a foreign peer includes the
4429 * #GUnixCredentialsMessage type and
4430 * g_unix_connection_send_credentials() /
4431 * g_unix_connection_receive_credentials() functions.
4433 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4434 * that must be freed with g_object_unref().
4439 g_socket_get_credentials (GSocket *socket,
4444 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4445 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4449 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
4453 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
4454 socklen_t optlen = sizeof (native_creds_buf);
4456 if (getsockopt (socket->priv->fd,
4462 ret = g_credentials_new ();
4463 g_credentials_set_native (ret,
4464 G_CREDENTIALS_NATIVE_TYPE,
4468 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
4470 ucred_t *ucred = NULL;
4472 if (getpeerucred (socket->priv->fd, &ucred) == 0)
4474 ret = g_credentials_new ();
4475 g_credentials_set_native (ret,
4476 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
4482 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
4487 int errsv = get_socket_errno ();
4491 socket_io_error_from_errno (errsv),
4492 _("Unable to read socket credentials: %s"),
4493 socket_strerror (errsv));
4498 g_set_error_literal (error,
4500 G_IO_ERROR_NOT_SUPPORTED,
4501 _("g_socket_get_credentials not implemented for this OS"));
4508 * g_socket_get_option:
4509 * @socket: a #GSocket
4510 * @level: the "API level" of the option (eg, <literal>SOL_SOCKET</literal>)
4511 * @optname: the "name" of the option (eg, <literal>SO_BROADCAST</literal>)
4512 * @value: (out): return location for the option value
4513 * @error: #GError for error reporting, or %NULL to ignore.
4515 * Gets the value of an integer-valued option on @socket, as with
4516 * <literal>getsockopt ()</literal>. (If you need to fetch a
4517 * non-integer-valued option, you will need to call
4518 * <literal>getsockopt ()</literal> directly.)
4520 * The <link linkend="gio-gnetworking.h"><literal><gio/gnetworking.h></literal></link>
4521 * header pulls in system headers that will define most of the
4522 * standard/portable socket options. For unusual socket protocols or
4523 * platform-dependent options, you may need to include additional
4526 * Note that even for socket options that are a single byte in size,
4527 * @value is still a pointer to a #gint variable, not a #guchar;
4528 * g_socket_get_option() will handle the conversion internally.
4530 * Returns: success or failure. On failure, @error will be set, and
4531 * the system error value (<literal>errno</literal> or
4532 * <literal>WSAGetLastError ()</literal>) will still be set to the
4533 * result of the <literal>getsockopt ()</literal> call.
4538 g_socket_get_option (GSocket *socket,
4546 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4549 size = sizeof (gint);
4550 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
4552 int errsv = get_socket_errno ();
4554 g_set_error_literal (error,
4556 socket_io_error_from_errno (errsv),
4557 socket_strerror (errsv));
4559 /* Reset errno in case the caller wants to look at it */
4565 #if G_BYTE_ORDER == G_BIG_ENDIAN
4566 /* If the returned value is smaller than an int then we need to
4567 * slide it over into the low-order bytes of *value.
4569 if (size != sizeof (gint))
4570 *value = *value >> (8 * (sizeof (gint) - size));
4577 * g_socket_set_option:
4578 * @socket: a #GSocket
4579 * @level: the "API level" of the option (eg, <literal>SOL_SOCKET</literal>)
4580 * @optname: the "name" of the option (eg, <literal>SO_BROADCAST</literal>)
4581 * @value: the value to set the option to
4582 * @error: #GError for error reporting, or %NULL to ignore.
4584 * Sets the value of an integer-valued option on @socket, as with
4585 * <literal>setsockopt ()</literal>. (If you need to set a
4586 * non-integer-valued option, you will need to call
4587 * <literal>setsockopt ()</literal> directly.)
4589 * The <link linkend="gio-gnetworking.h"><literal><gio/gnetworking.h></literal></link>
4590 * header pulls in system headers that will define most of the
4591 * standard/portable socket options. For unusual socket protocols or
4592 * platform-dependent options, you may need to include additional
4595 * Returns: success or failure. On failure, @error will be set, and
4596 * the system error value (<literal>errno</literal> or
4597 * <literal>WSAGetLastError ()</literal>) will still be set to the
4598 * result of the <literal>setsockopt ()</literal> call.
4603 g_socket_set_option (GSocket *socket,
4611 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4613 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
4616 #if !defined (__linux__) && !defined (G_OS_WIN32)
4617 /* Linux and Windows let you set a single-byte value from an int,
4618 * but most other platforms don't.
4620 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
4622 #if G_BYTE_ORDER == G_BIG_ENDIAN
4623 value = value << (8 * (sizeof (gint) - 1));
4625 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
4630 errsv = get_socket_errno ();
4632 g_set_error_literal (error,
4634 socket_io_error_from_errno (errsv),
4635 socket_strerror (errsv));