1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2008 Christian Kellner, Samuel Cormier-Iijima
4 * Copyright © 2009 Codethink Limited
5 * Copyright © 2009 Red Hat, Inc
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General
18 * Public License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20 * Boston, MA 02111-1307, USA.
22 * Authors: Christian Kellner <gicmo@gnome.org>
23 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
24 * Ryan Lortie <desrt@desrt.ca>
25 * Alexander Larsson <alexl@redhat.com>
33 #include "glib-unix.h"
44 # include <sys/ioctl.h>
51 #include "gcancellable.h"
52 #include "gioenumtypes.h"
53 #include "ginetaddress.h"
54 #include "ginitable.h"
58 #include "gnetworkingprivate.h"
59 #include "gsocketaddress.h"
60 #include "gsocketcontrolmessage.h"
61 #include "gcredentials.h"
66 * @short_description: Low-level socket object
68 * @see_also: #GInitable
70 * A #GSocket is a low-level networking primitive. It is a more or less
71 * direct mapping of the BSD socket API in a portable GObject based API.
72 * It supports both the UNIX socket implementations and winsock2 on Windows.
74 * #GSocket is the platform independent base upon which the higher level
75 * network primitives are based. Applications are not typically meant to
76 * use it directly, but rather through classes like #GSocketClient,
77 * #GSocketService and #GSocketConnection. However there may be cases where
78 * direct use of #GSocket is useful.
80 * #GSocket implements the #GInitable interface, so if it is manually constructed
81 * by e.g. g_object_new() you must call g_initable_init() and check the
82 * results before using the object. This is done automatically in
83 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
86 * Sockets operate in two general modes, blocking or non-blocking. When
87 * in blocking mode all operations block until the requested operation
88 * is finished or there is an error. In non-blocking mode all calls that
89 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
90 * To know when a call would successfully run you can call g_socket_condition_check(),
91 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
92 * attach it to a #GMainContext to get callbacks when I/O is possible.
93 * Note that all sockets are always set to non blocking mode in the system, and
94 * blocking mode is emulated in GSocket.
96 * When working in non-blocking mode applications should always be able to
97 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
98 * function said that I/O was possible. This can easily happen in case
99 * of a race condition in the application, but it can also happen for other
100 * reasons. For instance, on Windows a socket is always seen as writable
101 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
103 * #GSocket<!-- -->s can be either connection oriented or datagram based.
104 * For connection oriented types you must first establish a connection by
105 * either connecting to an address or accepting a connection from another
106 * address. For connectionless socket types the target/source address is
107 * specified or received in each I/O operation.
109 * All socket file descriptors are set to be close-on-exec.
111 * Note that creating a #GSocket causes the signal %SIGPIPE to be
112 * ignored for the remainder of the program. If you are writing a
113 * command-line utility that uses #GSocket, you may need to take into
114 * account the fact that your program will not automatically be killed
115 * if it tries to write to %stdout after it has been closed.
120 static void g_socket_initable_iface_init (GInitableIface *iface);
121 static gboolean g_socket_initable_init (GInitable *initable,
122 GCancellable *cancellable,
125 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
126 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
127 g_socket_initable_iface_init));
144 PROP_MULTICAST_LOOPBACK,
148 struct _GSocketPrivate
150 GSocketFamily family;
152 GSocketProtocol protocol;
156 GError *construct_error;
157 GSocketAddress *remote_address;
165 guint connect_pending : 1;
171 GList *requested_conditions; /* list of requested GIOCondition * */
176 get_socket_errno (void)
181 return WSAGetLastError ();
186 socket_io_error_from_errno (int err)
189 return g_io_error_from_errno (err);
194 return G_IO_ERROR_ADDRESS_IN_USE;
196 return G_IO_ERROR_WOULD_BLOCK;
198 return G_IO_ERROR_PERMISSION_DENIED;
199 case WSA_INVALID_HANDLE:
200 case WSA_INVALID_PARAMETER:
203 return G_IO_ERROR_INVALID_ARGUMENT;
204 case WSAEPROTONOSUPPORT:
205 return G_IO_ERROR_NOT_SUPPORTED;
207 return G_IO_ERROR_CANCELLED;
208 case WSAESOCKTNOSUPPORT:
210 case WSAEPFNOSUPPORT:
211 case WSAEAFNOSUPPORT:
212 return G_IO_ERROR_NOT_SUPPORTED;
214 return G_IO_ERROR_FAILED;
220 socket_strerror (int err)
223 return g_strerror (err);
228 msg = g_win32_error_message (err);
230 msg_ret = g_intern_string (msg);
238 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
240 _win32_unset_event_mask (GSocket *socket, int mask)
242 socket->priv->current_events &= ~mask;
243 socket->priv->current_errors &= ~mask;
246 #define win32_unset_event_mask(_socket, _mask)
250 set_fd_nonblocking (int fd)
253 GError *error = NULL;
259 if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
261 g_warning ("Error setting socket nonblocking: %s", error->message);
262 g_clear_error (&error);
267 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
269 int errsv = get_socket_errno ();
270 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
276 check_socket (GSocket *socket,
279 if (!socket->priv->inited)
281 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
282 _("Invalid socket, not initialized"));
286 if (socket->priv->construct_error)
288 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
289 _("Invalid socket, initialization failed due to: %s"),
290 socket->priv->construct_error->message);
294 if (socket->priv->closed)
296 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
297 _("Socket is already closed"));
301 if (socket->priv->timed_out)
303 socket->priv->timed_out = FALSE;
304 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
305 _("Socket I/O timed out"));
313 g_socket_details_from_fd (GSocket *socket)
315 struct sockaddr_storage address;
322 /* See bug #611756 */
323 BOOL bool_val = FALSE;
328 fd = socket->priv->fd;
329 optlen = sizeof value;
330 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
332 errsv = get_socket_errno ();
344 /* programmer error */
345 g_error ("creating GSocket from fd %d: %s\n",
346 fd, socket_strerror (errsv));
354 g_assert (optlen == sizeof value);
358 socket->priv->type = G_SOCKET_TYPE_STREAM;
362 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
366 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
370 socket->priv->type = G_SOCKET_TYPE_INVALID;
374 addrlen = sizeof address;
375 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
377 errsv = get_socket_errno ();
383 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
384 sizeof address.ss_family <= addrlen);
385 family = address.ss_family;
389 /* On Solaris, this happens if the socket is not yet connected.
390 * But we can use SO_DOMAIN as a workaround there.
393 optlen = sizeof family;
394 if (getsockopt (fd, SOL_SOCKET, SO_DOMAIN, (void *)&family, &optlen) != 0)
396 errsv = get_socket_errno ();
400 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
408 case G_SOCKET_FAMILY_IPV4:
409 case G_SOCKET_FAMILY_IPV6:
410 socket->priv->family = address.ss_family;
411 switch (socket->priv->type)
413 case G_SOCKET_TYPE_STREAM:
414 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
417 case G_SOCKET_TYPE_DATAGRAM:
418 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
421 case G_SOCKET_TYPE_SEQPACKET:
422 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
430 case G_SOCKET_FAMILY_UNIX:
431 socket->priv->family = G_SOCKET_FAMILY_UNIX;
432 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
436 socket->priv->family = G_SOCKET_FAMILY_INVALID;
440 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
442 addrlen = sizeof address;
443 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
444 socket->priv->connected = TRUE;
447 optlen = sizeof bool_val;
448 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
449 (void *)&bool_val, &optlen) == 0)
452 /* Experimentation indicates that the SO_KEEPALIVE value is
453 * actually a char on Windows, even if documentation claims it
454 * to be a BOOL which is a typedef for int. So this g_assert()
455 * fails. See bug #611756.
457 g_assert (optlen == sizeof bool_val);
459 socket->priv->keepalive = !!bool_val;
463 /* Can't read, maybe not supported, assume FALSE */
464 socket->priv->keepalive = FALSE;
470 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
471 socket_io_error_from_errno (errsv),
472 _("creating GSocket from fd: %s"),
473 socket_strerror (errsv));
477 g_socket_create_socket (GSocketFamily family,
487 case G_SOCKET_TYPE_STREAM:
488 native_type = SOCK_STREAM;
491 case G_SOCKET_TYPE_DATAGRAM:
492 native_type = SOCK_DGRAM;
495 case G_SOCKET_TYPE_SEQPACKET:
496 native_type = SOCK_SEQPACKET;
500 g_assert_not_reached ();
505 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
506 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
511 fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
512 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
513 if (fd < 0 && errno == EINVAL)
515 fd = socket (family, native_type, protocol);
519 int errsv = get_socket_errno ();
521 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
522 _("Unable to create socket: %s"), socket_strerror (errsv));
529 /* We always want to set close-on-exec to protect users. If you
530 need to so some weird inheritance to exec you can re-enable this
531 using lower level hacks with g_socket_get_fd(). */
532 flags = fcntl (fd, F_GETFD, 0);
534 (flags & FD_CLOEXEC) == 0)
537 fcntl (fd, F_SETFD, flags);
546 g_socket_constructed (GObject *object)
548 GSocket *socket = G_SOCKET (object);
550 if (socket->priv->fd >= 0)
551 /* create socket->priv info from the fd */
552 g_socket_details_from_fd (socket);
555 /* create the fd from socket->priv info */
556 socket->priv->fd = g_socket_create_socket (socket->priv->family,
558 socket->priv->protocol,
559 &socket->priv->construct_error);
561 /* Always use native nonblocking sockets, as
562 windows sets sockets to nonblocking automatically
563 in certain operations. This way we make things work
564 the same on all platforms */
565 if (socket->priv->fd != -1)
566 set_fd_nonblocking (socket->priv->fd);
570 g_socket_get_property (GObject *object,
575 GSocket *socket = G_SOCKET (object);
576 GSocketAddress *address;
581 g_value_set_enum (value, socket->priv->family);
585 g_value_set_enum (value, socket->priv->type);
589 g_value_set_enum (value, socket->priv->protocol);
593 g_value_set_int (value, socket->priv->fd);
597 g_value_set_boolean (value, socket->priv->blocking);
600 case PROP_LISTEN_BACKLOG:
601 g_value_set_int (value, socket->priv->listen_backlog);
605 g_value_set_boolean (value, socket->priv->keepalive);
608 case PROP_LOCAL_ADDRESS:
609 address = g_socket_get_local_address (socket, NULL);
610 g_value_take_object (value, address);
613 case PROP_REMOTE_ADDRESS:
614 address = g_socket_get_remote_address (socket, NULL);
615 g_value_take_object (value, address);
619 g_value_set_uint (value, socket->priv->timeout);
623 g_value_set_uint (value, g_socket_get_ttl (socket));
627 g_value_set_boolean (value, g_socket_get_broadcast (socket));
630 case PROP_MULTICAST_LOOPBACK:
631 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
634 case PROP_MULTICAST_TTL:
635 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
639 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
644 g_socket_set_property (GObject *object,
649 GSocket *socket = G_SOCKET (object);
654 socket->priv->family = g_value_get_enum (value);
658 socket->priv->type = g_value_get_enum (value);
662 socket->priv->protocol = g_value_get_enum (value);
666 socket->priv->fd = g_value_get_int (value);
670 g_socket_set_blocking (socket, g_value_get_boolean (value));
673 case PROP_LISTEN_BACKLOG:
674 g_socket_set_listen_backlog (socket, g_value_get_int (value));
678 g_socket_set_keepalive (socket, g_value_get_boolean (value));
682 g_socket_set_timeout (socket, g_value_get_uint (value));
686 g_socket_set_ttl (socket, g_value_get_uint (value));
690 g_socket_set_broadcast (socket, g_value_get_boolean (value));
693 case PROP_MULTICAST_LOOPBACK:
694 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
697 case PROP_MULTICAST_TTL:
698 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
702 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
707 g_socket_finalize (GObject *object)
709 GSocket *socket = G_SOCKET (object);
711 g_clear_error (&socket->priv->construct_error);
713 if (socket->priv->fd != -1 &&
714 !socket->priv->closed)
715 g_socket_close (socket, NULL);
717 if (socket->priv->remote_address)
718 g_object_unref (socket->priv->remote_address);
721 if (socket->priv->event != WSA_INVALID_EVENT)
723 WSACloseEvent (socket->priv->event);
724 socket->priv->event = WSA_INVALID_EVENT;
727 g_assert (socket->priv->requested_conditions == NULL);
730 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
731 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
735 g_socket_class_init (GSocketClass *klass)
737 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
740 /* Make sure winsock has been initialized */
741 type = g_inet_address_get_type ();
742 (type); /* To avoid -Wunused-but-set-variable */
745 /* There is no portable, thread-safe way to avoid having the process
746 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
747 * forced to simply ignore the signal process-wide.
749 signal (SIGPIPE, SIG_IGN);
752 g_type_class_add_private (klass, sizeof (GSocketPrivate));
754 gobject_class->finalize = g_socket_finalize;
755 gobject_class->constructed = g_socket_constructed;
756 gobject_class->set_property = g_socket_set_property;
757 gobject_class->get_property = g_socket_get_property;
759 g_object_class_install_property (gobject_class, PROP_FAMILY,
760 g_param_spec_enum ("family",
762 P_("The sockets address family"),
763 G_TYPE_SOCKET_FAMILY,
764 G_SOCKET_FAMILY_INVALID,
765 G_PARAM_CONSTRUCT_ONLY |
767 G_PARAM_STATIC_STRINGS));
769 g_object_class_install_property (gobject_class, PROP_TYPE,
770 g_param_spec_enum ("type",
772 P_("The sockets type"),
774 G_SOCKET_TYPE_STREAM,
775 G_PARAM_CONSTRUCT_ONLY |
777 G_PARAM_STATIC_STRINGS));
779 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
780 g_param_spec_enum ("protocol",
781 P_("Socket protocol"),
782 P_("The id of the protocol to use, or -1 for unknown"),
783 G_TYPE_SOCKET_PROTOCOL,
784 G_SOCKET_PROTOCOL_UNKNOWN,
785 G_PARAM_CONSTRUCT_ONLY |
787 G_PARAM_STATIC_STRINGS));
789 g_object_class_install_property (gobject_class, PROP_FD,
790 g_param_spec_int ("fd",
791 P_("File descriptor"),
792 P_("The sockets file descriptor"),
796 G_PARAM_CONSTRUCT_ONLY |
798 G_PARAM_STATIC_STRINGS));
800 g_object_class_install_property (gobject_class, PROP_BLOCKING,
801 g_param_spec_boolean ("blocking",
803 P_("Whether or not I/O on this socket is blocking"),
806 G_PARAM_STATIC_STRINGS));
808 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
809 g_param_spec_int ("listen-backlog",
810 P_("Listen backlog"),
811 P_("Outstanding connections in the listen queue"),
816 G_PARAM_STATIC_STRINGS));
818 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
819 g_param_spec_boolean ("keepalive",
820 P_("Keep connection alive"),
821 P_("Keep connection alive by sending periodic pings"),
824 G_PARAM_STATIC_STRINGS));
826 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
827 g_param_spec_object ("local-address",
829 P_("The local address the socket is bound to"),
830 G_TYPE_SOCKET_ADDRESS,
832 G_PARAM_STATIC_STRINGS));
834 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
835 g_param_spec_object ("remote-address",
836 P_("Remote address"),
837 P_("The remote address the socket is connected to"),
838 G_TYPE_SOCKET_ADDRESS,
840 G_PARAM_STATIC_STRINGS));
845 * The timeout in seconds on socket I/O
849 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
850 g_param_spec_uint ("timeout",
852 P_("The timeout in seconds on socket I/O"),
857 G_PARAM_STATIC_STRINGS));
862 * Whether the socket should allow sending to and receiving from broadcast addresses.
866 g_object_class_install_property (gobject_class, PROP_BROADCAST,
867 g_param_spec_boolean ("broadcast",
869 P_("Whether to allow sending to and receiving from broadcast addresses"),
872 G_PARAM_STATIC_STRINGS));
877 * Time-to-live for outgoing unicast packets
881 g_object_class_install_property (gobject_class, PROP_TTL,
882 g_param_spec_uint ("ttl",
884 P_("Time-to-live of outgoing unicast packets"),
887 G_PARAM_STATIC_STRINGS));
890 * GSocket:multicast-loopback:
892 * Whether outgoing multicast packets loop back to the local host.
896 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
897 g_param_spec_boolean ("multicast-loopback",
898 P_("Multicast loopback"),
899 P_("Whether outgoing multicast packets loop back to the local host"),
902 G_PARAM_STATIC_STRINGS));
905 * GSocket:multicast-ttl:
907 * Time-to-live out outgoing multicast packets
911 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
912 g_param_spec_uint ("multicast-ttl",
914 P_("Time-to-live of outgoing multicast packets"),
917 G_PARAM_STATIC_STRINGS));
921 g_socket_initable_iface_init (GInitableIface *iface)
923 iface->init = g_socket_initable_init;
927 g_socket_init (GSocket *socket)
929 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
931 socket->priv->fd = -1;
932 socket->priv->blocking = TRUE;
933 socket->priv->listen_backlog = 10;
934 socket->priv->construct_error = NULL;
936 socket->priv->event = WSA_INVALID_EVENT;
941 g_socket_initable_init (GInitable *initable,
942 GCancellable *cancellable,
947 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
949 socket = G_SOCKET (initable);
951 if (cancellable != NULL)
953 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
954 _("Cancellable initialization not supported"));
958 socket->priv->inited = TRUE;
960 if (socket->priv->construct_error)
963 *error = g_error_copy (socket->priv->construct_error);
973 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
974 * @type: the socket type to use.
975 * @protocol: the id of the protocol to use, or 0 for default.
976 * @error: #GError for error reporting, or %NULL to ignore.
978 * Creates a new #GSocket with the defined family, type and protocol.
979 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
980 * for the family and type is used.
982 * The @protocol is a family and type specific int that specifies what
983 * kind of protocol to use. #GSocketProtocol lists several common ones.
984 * Many families only support one protocol, and use 0 for this, others
985 * support several and using 0 means to use the default protocol for
986 * the family and type.
988 * The protocol id is passed directly to the operating
989 * system, so you can use protocols not listed in #GSocketProtocol if you
990 * know the protocol number used for it.
992 * Returns: a #GSocket or %NULL on error.
993 * Free the returned object with g_object_unref().
998 g_socket_new (GSocketFamily family,
1000 GSocketProtocol protocol,
1003 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1007 "protocol", protocol,
1012 * g_socket_new_from_fd:
1013 * @fd: a native socket file descriptor.
1014 * @error: #GError for error reporting, or %NULL to ignore.
1016 * Creates a new #GSocket from a native file descriptor
1017 * or winsock SOCKET handle.
1019 * This reads all the settings from the file descriptor so that
1020 * all properties should work. Note that the file descriptor
1021 * will be set to non-blocking mode, independent on the blocking
1022 * mode of the #GSocket.
1024 * Returns: a #GSocket or %NULL on error.
1025 * Free the returned object with g_object_unref().
1030 g_socket_new_from_fd (gint fd,
1033 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1040 * g_socket_set_blocking:
1041 * @socket: a #GSocket.
1042 * @blocking: Whether to use blocking I/O or not.
1044 * Sets the blocking mode of the socket. In blocking mode
1045 * all operations block until they succeed or there is an error. In
1046 * non-blocking mode all functions return results immediately or
1047 * with a %G_IO_ERROR_WOULD_BLOCK error.
1049 * All sockets are created in blocking mode. However, note that the
1050 * platform level socket is always non-blocking, and blocking mode
1051 * is a GSocket level feature.
1056 g_socket_set_blocking (GSocket *socket,
1059 g_return_if_fail (G_IS_SOCKET (socket));
1061 blocking = !!blocking;
1063 if (socket->priv->blocking == blocking)
1066 socket->priv->blocking = blocking;
1067 g_object_notify (G_OBJECT (socket), "blocking");
1071 * g_socket_get_blocking:
1072 * @socket: a #GSocket.
1074 * Gets the blocking mode of the socket. For details on blocking I/O,
1075 * see g_socket_set_blocking().
1077 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1082 g_socket_get_blocking (GSocket *socket)
1084 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1086 return socket->priv->blocking;
1090 * g_socket_set_keepalive:
1091 * @socket: a #GSocket.
1092 * @keepalive: Value for the keepalive flag
1094 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1095 * this flag is set on a socket, the system will attempt to verify that the
1096 * remote socket endpoint is still present if a sufficiently long period of
1097 * time passes with no data being exchanged. If the system is unable to
1098 * verify the presence of the remote endpoint, it will automatically close
1101 * This option is only functional on certain kinds of sockets. (Notably,
1102 * %G_SOCKET_PROTOCOL_TCP sockets.)
1104 * The exact time between pings is system- and protocol-dependent, but will
1105 * normally be at least two hours. Most commonly, you would set this flag
1106 * on a server socket if you want to allow clients to remain idle for long
1107 * periods of time, but also want to ensure that connections are eventually
1108 * garbage-collected if clients crash or become unreachable.
1113 g_socket_set_keepalive (GSocket *socket,
1118 g_return_if_fail (G_IS_SOCKET (socket));
1120 keepalive = !!keepalive;
1121 if (socket->priv->keepalive == keepalive)
1124 value = (gint) keepalive;
1125 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1126 (gpointer) &value, sizeof (value)) < 0)
1128 int errsv = get_socket_errno ();
1129 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1133 socket->priv->keepalive = keepalive;
1134 g_object_notify (G_OBJECT (socket), "keepalive");
1138 * g_socket_get_keepalive:
1139 * @socket: a #GSocket.
1141 * Gets the keepalive mode of the socket. For details on this,
1142 * see g_socket_set_keepalive().
1144 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1149 g_socket_get_keepalive (GSocket *socket)
1151 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1153 return socket->priv->keepalive;
1157 * g_socket_get_listen_backlog:
1158 * @socket: a #GSocket.
1160 * Gets the listen backlog setting of the socket. For details on this,
1161 * see g_socket_set_listen_backlog().
1163 * Returns: the maximum number of pending connections.
1168 g_socket_get_listen_backlog (GSocket *socket)
1170 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1172 return socket->priv->listen_backlog;
1176 * g_socket_set_listen_backlog:
1177 * @socket: a #GSocket.
1178 * @backlog: the maximum number of pending connections.
1180 * Sets the maximum number of outstanding connections allowed
1181 * when listening on this socket. If more clients than this are
1182 * connecting to the socket and the application is not handling them
1183 * on time then the new connections will be refused.
1185 * Note that this must be called before g_socket_listen() and has no
1186 * effect if called after that.
1191 g_socket_set_listen_backlog (GSocket *socket,
1194 g_return_if_fail (G_IS_SOCKET (socket));
1195 g_return_if_fail (!socket->priv->listening);
1197 if (backlog != socket->priv->listen_backlog)
1199 socket->priv->listen_backlog = backlog;
1200 g_object_notify (G_OBJECT (socket), "listen-backlog");
1205 * g_socket_get_timeout:
1206 * @socket: a #GSocket.
1208 * Gets the timeout setting of the socket. For details on this, see
1209 * g_socket_set_timeout().
1211 * Returns: the timeout in seconds
1216 g_socket_get_timeout (GSocket *socket)
1218 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1220 return socket->priv->timeout;
1224 * g_socket_set_timeout:
1225 * @socket: a #GSocket.
1226 * @timeout: the timeout for @socket, in seconds, or 0 for none
1228 * Sets the time in seconds after which I/O operations on @socket will
1229 * time out if they have not yet completed.
1231 * On a blocking socket, this means that any blocking #GSocket
1232 * operation will time out after @timeout seconds of inactivity,
1233 * returning %G_IO_ERROR_TIMED_OUT.
1235 * On a non-blocking socket, calls to g_socket_condition_wait() will
1236 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1237 * created with g_socket_create_source() will trigger after
1238 * @timeout seconds of inactivity, with the requested condition
1239 * set, at which point calling g_socket_receive(), g_socket_send(),
1240 * g_socket_check_connect_result(), etc, will fail with
1241 * %G_IO_ERROR_TIMED_OUT.
1243 * If @timeout is 0 (the default), operations will never time out
1246 * Note that if an I/O operation is interrupted by a signal, this may
1247 * cause the timeout to be reset.
1252 g_socket_set_timeout (GSocket *socket,
1255 g_return_if_fail (G_IS_SOCKET (socket));
1257 if (timeout != socket->priv->timeout)
1259 socket->priv->timeout = timeout;
1260 g_object_notify (G_OBJECT (socket), "timeout");
1266 * @socket: a #GSocket.
1268 * Gets the unicast time-to-live setting on @socket; see
1269 * g_socket_set_ttl() for more details.
1271 * Returns: the time-to-live setting on @socket
1276 g_socket_get_ttl (GSocket *socket)
1279 guint value, optlen;
1281 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1283 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1287 optlen = sizeof (optval);
1288 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_TTL,
1292 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1294 optlen = sizeof (value);
1295 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1299 g_return_val_if_reached (FALSE);
1303 int errsv = get_socket_errno ();
1304 g_warning ("error getting unicast ttl: %s", socket_strerror (errsv));
1313 * @socket: a #GSocket.
1314 * @ttl: the time-to-live value for all unicast packets on @socket
1316 * Sets the time-to-live for outgoing unicast packets on @socket.
1317 * By default the platform-specific default value is used.
1322 g_socket_set_ttl (GSocket *socket,
1327 g_return_if_fail (G_IS_SOCKET (socket));
1329 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1331 guchar optval = (guchar)ttl;
1333 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_TTL,
1334 &optval, sizeof (optval));
1336 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1338 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1339 &ttl, sizeof (ttl));
1342 g_return_if_reached ();
1346 int errsv = get_socket_errno ();
1347 g_warning ("error setting unicast ttl: %s", socket_strerror (errsv));
1351 g_object_notify (G_OBJECT (socket), "ttl");
1355 * g_socket_get_broadcast:
1356 * @socket: a #GSocket.
1358 * Gets the broadcast setting on @socket; if %TRUE,
1359 * it is possible to send packets to broadcast
1360 * addresses or receive from broadcast addresses.
1362 * Returns: the broadcast setting on @socket
1367 g_socket_get_broadcast (GSocket *socket)
1370 guint value = 0, optlen;
1372 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1374 optlen = sizeof (guchar);
1375 result = getsockopt (socket->priv->fd, SOL_SOCKET, SO_BROADCAST,
1380 int errsv = get_socket_errno ();
1381 g_warning ("error getting broadcast: %s", socket_strerror (errsv));
1389 * g_socket_set_broadcast:
1390 * @socket: a #GSocket.
1391 * @broadcast: whether @socket should allow sending to and receiving
1392 * from broadcast addresses
1394 * Sets whether @socket should allow sending to and receiving from
1395 * broadcast addresses. This is %FALSE by default.
1400 g_socket_set_broadcast (GSocket *socket,
1406 g_return_if_fail (G_IS_SOCKET (socket));
1408 broadcast = !!broadcast;
1409 value = (guchar)broadcast;
1411 result = setsockopt (socket->priv->fd, SOL_SOCKET, SO_BROADCAST,
1412 &value, sizeof (value));
1416 int errsv = get_socket_errno ();
1417 g_warning ("error setting broadcast: %s", socket_strerror (errsv));
1421 g_object_notify (G_OBJECT (socket), "broadcast");
1425 * g_socket_get_multicast_loopback:
1426 * @socket: a #GSocket.
1428 * Gets the multicast loopback setting on @socket; if %TRUE (the
1429 * default), outgoing multicast packets will be looped back to
1430 * multicast listeners on the same host.
1432 * Returns: the multicast loopback setting on @socket
1437 g_socket_get_multicast_loopback (GSocket *socket)
1440 guint value = 0, optlen;
1442 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1444 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1446 optlen = sizeof (guchar);
1447 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1450 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1452 optlen = sizeof (guint);
1453 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1457 g_return_val_if_reached (FALSE);
1461 int errsv = get_socket_errno ();
1462 g_warning ("error getting multicast loopback: %s", socket_strerror (errsv));
1470 * g_socket_set_multicast_loopback:
1471 * @socket: a #GSocket.
1472 * @loopback: whether @socket should receive messages sent to its
1473 * multicast groups from the local host
1475 * Sets whether outgoing multicast packets will be received by sockets
1476 * listening on that multicast address on the same host. This is %TRUE
1482 g_socket_set_multicast_loopback (GSocket *socket,
1487 g_return_if_fail (G_IS_SOCKET (socket));
1489 loopback = !!loopback;
1491 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1493 guchar value = (guchar)loopback;
1495 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1496 &value, sizeof (value));
1498 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1500 guint value = (guint)loopback;
1502 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1503 &value, sizeof (value));
1506 g_return_if_reached ();
1510 int errsv = get_socket_errno ();
1511 g_warning ("error setting multicast loopback: %s", socket_strerror (errsv));
1515 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1519 * g_socket_get_multicast_ttl:
1520 * @socket: a #GSocket.
1522 * Gets the multicast time-to-live setting on @socket; see
1523 * g_socket_set_multicast_ttl() for more details.
1525 * Returns: the multicast time-to-live setting on @socket
1530 g_socket_get_multicast_ttl (GSocket *socket)
1533 guint value, optlen;
1535 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1537 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1541 optlen = sizeof (optval);
1542 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1546 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1548 optlen = sizeof (value);
1549 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1553 g_return_val_if_reached (FALSE);
1557 int errsv = get_socket_errno ();
1558 g_warning ("error getting multicast ttl: %s", socket_strerror (errsv));
1566 * g_socket_set_multicast_ttl:
1567 * @socket: a #GSocket.
1568 * @ttl: the time-to-live value for all multicast datagrams on @socket
1570 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1571 * By default, this is 1, meaning that multicast packets will not leave
1572 * the local network.
1577 g_socket_set_multicast_ttl (GSocket *socket,
1582 g_return_if_fail (G_IS_SOCKET (socket));
1584 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1586 guchar optval = (guchar)ttl;
1588 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1589 &optval, sizeof (optval));
1591 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1593 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1594 &ttl, sizeof (ttl));
1597 g_return_if_reached ();
1601 int errsv = get_socket_errno ();
1602 g_warning ("error setting multicast ttl: %s", socket_strerror (errsv));
1606 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1610 * g_socket_get_family:
1611 * @socket: a #GSocket.
1613 * Gets the socket family of the socket.
1615 * Returns: a #GSocketFamily
1620 g_socket_get_family (GSocket *socket)
1622 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1624 return socket->priv->family;
1628 * g_socket_get_socket_type:
1629 * @socket: a #GSocket.
1631 * Gets the socket type of the socket.
1633 * Returns: a #GSocketType
1638 g_socket_get_socket_type (GSocket *socket)
1640 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1642 return socket->priv->type;
1646 * g_socket_get_protocol:
1647 * @socket: a #GSocket.
1649 * Gets the socket protocol id the socket was created with.
1650 * In case the protocol is unknown, -1 is returned.
1652 * Returns: a protocol id, or -1 if unknown
1657 g_socket_get_protocol (GSocket *socket)
1659 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1661 return socket->priv->protocol;
1666 * @socket: a #GSocket.
1668 * Returns the underlying OS socket object. On unix this
1669 * is a socket file descriptor, and on windows this is
1670 * a Winsock2 SOCKET handle. This may be useful for
1671 * doing platform specific or otherwise unusual operations
1674 * Returns: the file descriptor of the socket.
1679 g_socket_get_fd (GSocket *socket)
1681 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1683 return socket->priv->fd;
1687 * g_socket_get_local_address:
1688 * @socket: a #GSocket.
1689 * @error: #GError for error reporting, or %NULL to ignore.
1691 * Try to get the local address of a bound socket. This is only
1692 * useful if the socket has been bound to a local address,
1693 * either explicitly or implicitly when connecting.
1695 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1696 * Free the returned object with g_object_unref().
1701 g_socket_get_local_address (GSocket *socket,
1704 struct sockaddr_storage buffer;
1705 guint32 len = sizeof (buffer);
1707 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1709 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1711 int errsv = get_socket_errno ();
1712 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1713 _("could not get local address: %s"), socket_strerror (errsv));
1717 return g_socket_address_new_from_native (&buffer, len);
1721 * g_socket_get_remote_address:
1722 * @socket: a #GSocket.
1723 * @error: #GError for error reporting, or %NULL to ignore.
1725 * Try to get the remove address of a connected socket. This is only
1726 * useful for connection oriented sockets that have been connected.
1728 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1729 * Free the returned object with g_object_unref().
1734 g_socket_get_remote_address (GSocket *socket,
1737 struct sockaddr_storage buffer;
1738 guint32 len = sizeof (buffer);
1740 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1742 if (socket->priv->connect_pending)
1744 if (!g_socket_check_connect_result (socket, error))
1747 socket->priv->connect_pending = FALSE;
1750 if (!socket->priv->remote_address)
1752 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1754 int errsv = get_socket_errno ();
1755 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1756 _("could not get remote address: %s"), socket_strerror (errsv));
1760 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1763 return g_object_ref (socket->priv->remote_address);
1767 * g_socket_is_connected:
1768 * @socket: a #GSocket.
1770 * Check whether the socket is connected. This is only useful for
1771 * connection-oriented sockets.
1773 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1778 g_socket_is_connected (GSocket *socket)
1780 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1782 return socket->priv->connected;
1787 * @socket: a #GSocket.
1788 * @error: #GError for error reporting, or %NULL to ignore.
1790 * Marks the socket as a server socket, i.e. a socket that is used
1791 * to accept incoming requests using g_socket_accept().
1793 * Before calling this the socket must be bound to a local address using
1796 * To set the maximum amount of outstanding clients, use
1797 * g_socket_set_listen_backlog().
1799 * Returns: %TRUE on success, %FALSE on error.
1804 g_socket_listen (GSocket *socket,
1807 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1809 if (!check_socket (socket, error))
1812 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1814 int errsv = get_socket_errno ();
1816 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1817 _("could not listen: %s"), socket_strerror (errsv));
1821 socket->priv->listening = TRUE;
1828 * @socket: a #GSocket.
1829 * @address: a #GSocketAddress specifying the local address.
1830 * @allow_reuse: whether to allow reusing this address
1831 * @error: #GError for error reporting, or %NULL to ignore.
1833 * When a socket is created it is attached to an address family, but it
1834 * doesn't have an address in this family. g_socket_bind() assigns the
1835 * address (sometimes called name) of the socket.
1837 * It is generally required to bind to a local address before you can
1838 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1839 * In certain situations, you may also want to bind a socket that will be
1840 * used to initiate connections, though this is not normally required.
1842 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1843 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1844 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1845 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1846 * that address was previously used by another socket that has not yet been
1847 * fully cleaned-up by the kernel. Failing to set this flag on a server
1848 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1849 * the server program is stopped and then immediately restarted.)
1851 * Returns: %TRUE on success, %FALSE on error.
1856 g_socket_bind (GSocket *socket,
1857 GSocketAddress *address,
1858 gboolean reuse_address,
1861 struct sockaddr_storage addr;
1863 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1865 if (!check_socket (socket, error))
1868 /* SO_REUSEADDR on windows means something else and is not what we want.
1869 It always allows the unix variant of SO_REUSEADDR anyway */
1874 value = (int) !!reuse_address;
1875 /* Ignore errors here, the only likely error is "not supported", and
1876 this is a "best effort" thing mainly */
1877 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1878 (gpointer) &value, sizeof (value));
1882 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1885 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1886 g_socket_address_get_native_size (address)) < 0)
1888 int errsv = get_socket_errno ();
1890 G_IO_ERROR, socket_io_error_from_errno (errsv),
1891 _("Error binding to address: %s"), socket_strerror (errsv));
1899 g_socket_multicast_group_operation (GSocket *socket,
1900 GInetAddress *group,
1901 gboolean source_specific,
1903 gboolean join_group,
1906 const guint8 *native_addr;
1907 gint optname, result;
1909 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1910 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
1911 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
1912 g_return_val_if_fail (g_inet_address_get_family (group) == socket->priv->family, FALSE);
1914 if (!check_socket (socket, error))
1917 native_addr = g_inet_address_to_bytes (group);
1918 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1920 #ifdef HAVE_IP_MREQN
1921 struct ip_mreqn mc_req;
1923 struct ip_mreq mc_req;
1926 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
1928 #ifdef HAVE_IP_MREQN
1930 mc_req.imr_ifindex = if_nametoindex (iface);
1932 mc_req.imr_ifindex = 0; /* Pick any. */
1934 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
1937 if (source_specific)
1939 #ifdef IP_ADD_SOURCE_MEMBERSHIP
1940 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
1942 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1944 _("Error joining multicast group: %s") :
1945 _("Error leaving multicast group: %s"),
1946 _("No support for source-specific multicast"));
1951 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
1952 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
1953 &mc_req, sizeof (mc_req));
1955 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1957 struct ipv6_mreq mc_req_ipv6;
1959 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
1960 #ifdef HAVE_IF_NAMETOINDEX
1962 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
1965 mc_req_ipv6.ipv6mr_interface = 0;
1967 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
1968 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
1969 &mc_req_ipv6, sizeof (mc_req_ipv6));
1972 g_return_val_if_reached (FALSE);
1976 int errsv = get_socket_errno ();
1978 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1980 _("Error joining multicast group: %s") :
1981 _("Error leaving multicast group: %s"),
1982 socket_strerror (errsv));
1990 * g_socket_join_multicast_group:
1991 * @socket: a #GSocket.
1992 * @group: a #GInetAddress specifying the group address to join.
1993 * @iface: (allow-none): Name of the interface to use, or %NULL
1994 * @source_specific: %TRUE if source-specific multicast should be used
1995 * @error: #GError for error reporting, or %NULL to ignore.
1997 * Registers @socket to receive multicast messages sent to @group.
1998 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
1999 * been bound to an appropriate interface and port with
2002 * If @iface is %NULL, the system will automatically pick an interface
2003 * to bind to based on @group.
2005 * If @source_specific is %TRUE, source-specific multicast as defined
2006 * in RFC 4604 is used. Note that on older platforms this may fail
2007 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2009 * Returns: %TRUE on success, %FALSE on error.
2014 g_socket_join_multicast_group (GSocket *socket,
2015 GInetAddress *group,
2016 gboolean source_specific,
2020 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2024 * g_socket_leave_multicast_group:
2025 * @socket: a #GSocket.
2026 * @group: a #GInetAddress specifying the group address to leave.
2027 * @iface: (allow-none): Interface used
2028 * @source_specific: %TRUE if source-specific multicast was used
2029 * @error: #GError for error reporting, or %NULL to ignore.
2031 * Removes @socket from the multicast group defined by @group, @iface,
2032 * and @source_specific (which must all have the same values they had
2033 * when you joined the group).
2035 * @socket remains bound to its address and port, and can still receive
2036 * unicast messages after calling this.
2038 * Returns: %TRUE on success, %FALSE on error.
2043 g_socket_leave_multicast_group (GSocket *socket,
2044 GInetAddress *group,
2045 gboolean source_specific,
2049 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2053 * g_socket_speaks_ipv4:
2054 * @socket: a #GSocket
2056 * Checks if a socket is capable of speaking IPv4.
2058 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2059 * and under some combinations of circumstances IPv6 sockets are also
2060 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2063 * No other types of sockets are currently considered as being capable
2066 * Returns: %TRUE if this socket can be used with IPv4.
2071 g_socket_speaks_ipv4 (GSocket *socket)
2073 switch (socket->priv->family)
2075 case G_SOCKET_FAMILY_IPV4:
2078 case G_SOCKET_FAMILY_IPV6:
2079 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2081 guint sizeof_int = sizeof (int);
2084 if (getsockopt (socket->priv->fd,
2085 IPPROTO_IPV6, IPV6_V6ONLY,
2086 &v6_only, &sizeof_int) != 0)
2102 * @socket: a #GSocket.
2103 * @cancellable: (allow-none): a %GCancellable or %NULL
2104 * @error: #GError for error reporting, or %NULL to ignore.
2106 * Accept incoming connections on a connection-based socket. This removes
2107 * the first outstanding connection request from the listening socket and
2108 * creates a #GSocket object for it.
2110 * The @socket must be bound to a local address with g_socket_bind() and
2111 * must be listening for incoming connections (g_socket_listen()).
2113 * If there are no outstanding connections then the operation will block
2114 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2115 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2117 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2118 * Free the returned object with g_object_unref().
2123 g_socket_accept (GSocket *socket,
2124 GCancellable *cancellable,
2127 GSocket *new_socket;
2130 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2132 if (!check_socket (socket, error))
2137 if (socket->priv->blocking &&
2138 !g_socket_condition_wait (socket,
2139 G_IO_IN, cancellable, error))
2142 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2144 int errsv = get_socket_errno ();
2146 win32_unset_event_mask (socket, FD_ACCEPT);
2151 if (socket->priv->blocking)
2153 #ifdef WSAEWOULDBLOCK
2154 if (errsv == WSAEWOULDBLOCK)
2157 if (errsv == EWOULDBLOCK ||
2163 g_set_error (error, G_IO_ERROR,
2164 socket_io_error_from_errno (errsv),
2165 _("Error accepting connection: %s"), socket_strerror (errsv));
2171 win32_unset_event_mask (socket, FD_ACCEPT);
2175 /* The socket inherits the accepting sockets event mask and even object,
2176 we need to remove that */
2177 WSAEventSelect (ret, NULL, 0);
2183 /* We always want to set close-on-exec to protect users. If you
2184 need to so some weird inheritance to exec you can re-enable this
2185 using lower level hacks with g_socket_get_fd(). */
2186 flags = fcntl (ret, F_GETFD, 0);
2188 (flags & FD_CLOEXEC) == 0)
2190 flags |= FD_CLOEXEC;
2191 fcntl (ret, F_SETFD, flags);
2196 new_socket = g_socket_new_from_fd (ret, error);
2197 if (new_socket == NULL)
2206 new_socket->priv->protocol = socket->priv->protocol;
2213 * @socket: a #GSocket.
2214 * @address: a #GSocketAddress specifying the remote address.
2215 * @cancellable: (allow-none): a %GCancellable or %NULL
2216 * @error: #GError for error reporting, or %NULL to ignore.
2218 * Connect the socket to the specified remote address.
2220 * For connection oriented socket this generally means we attempt to make
2221 * a connection to the @address. For a connection-less socket it sets
2222 * the default address for g_socket_send() and discards all incoming datagrams
2223 * from other sources.
2225 * Generally connection oriented sockets can only connect once, but
2226 * connection-less sockets can connect multiple times to change the
2229 * If the connect call needs to do network I/O it will block, unless
2230 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2231 * and the user can be notified of the connection finishing by waiting
2232 * for the G_IO_OUT condition. The result of the connection must then be
2233 * checked with g_socket_check_connect_result().
2235 * Returns: %TRUE if connected, %FALSE on error.
2240 g_socket_connect (GSocket *socket,
2241 GSocketAddress *address,
2242 GCancellable *cancellable,
2245 struct sockaddr_storage buffer;
2247 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2249 if (!check_socket (socket, error))
2252 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2255 if (socket->priv->remote_address)
2256 g_object_unref (socket->priv->remote_address);
2257 socket->priv->remote_address = g_object_ref (address);
2261 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2262 g_socket_address_get_native_size (address)) < 0)
2264 int errsv = get_socket_errno ();
2270 if (errsv == EINPROGRESS)
2272 if (errsv == WSAEWOULDBLOCK)
2275 if (socket->priv->blocking)
2277 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2279 if (g_socket_check_connect_result (socket, error))
2285 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2286 _("Connection in progress"));
2287 socket->priv->connect_pending = TRUE;
2291 g_set_error_literal (error, G_IO_ERROR,
2292 socket_io_error_from_errno (errsv),
2293 socket_strerror (errsv));
2300 win32_unset_event_mask (socket, FD_CONNECT);
2302 socket->priv->connected = TRUE;
2308 * g_socket_check_connect_result:
2309 * @socket: a #GSocket
2310 * @error: #GError for error reporting, or %NULL to ignore.
2312 * Checks and resets the pending connect error for the socket.
2313 * This is used to check for errors when g_socket_connect() is
2314 * used in non-blocking mode.
2316 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2321 g_socket_check_connect_result (GSocket *socket,
2327 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2329 if (!check_socket (socket, error))
2332 optlen = sizeof (value);
2333 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
2335 int errsv = get_socket_errno ();
2337 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2338 _("Unable to get pending error: %s"), socket_strerror (errsv));
2344 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2345 socket_strerror (value));
2346 if (socket->priv->remote_address)
2348 g_object_unref (socket->priv->remote_address);
2349 socket->priv->remote_address = NULL;
2354 socket->priv->connected = TRUE;
2359 * g_socket_get_available_bytes:
2360 * @socket: a #GSocket
2362 * Get the amount of data pending in the OS input buffer.
2364 * Returns: the number of bytes that can be read from the socket
2365 * without blocking or -1 on error.
2370 g_socket_get_available_bytes (GSocket *socket)
2378 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2381 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2384 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) == SOCKET_ERROR)
2393 * @socket: a #GSocket
2394 * @buffer: a buffer to read data into (which should be at least @size
2396 * @size: the number of bytes you want to read from the socket
2397 * @cancellable: (allow-none): a %GCancellable or %NULL
2398 * @error: #GError for error reporting, or %NULL to ignore.
2400 * Receive data (up to @size bytes) from a socket. This is mainly used by
2401 * connection-oriented sockets; it is identical to g_socket_receive_from()
2402 * with @address set to %NULL.
2404 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2405 * g_socket_receive() will always read either 0 or 1 complete messages from
2406 * the socket. If the received message is too large to fit in @buffer, then
2407 * the data beyond @size bytes will be discarded, without any explicit
2408 * indication that this has occurred.
2410 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2411 * number of bytes, up to @size. If more than @size bytes have been
2412 * received, the additional data will be returned in future calls to
2413 * g_socket_receive().
2415 * If the socket is in blocking mode the call will block until there
2416 * is some data to receive, the connection is closed, or there is an
2417 * error. If there is no data available and the socket is in
2418 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2419 * returned. To be notified when data is available, wait for the
2420 * %G_IO_IN condition.
2422 * On error -1 is returned and @error is set accordingly.
2424 * Returns: Number of bytes read, or 0 if the connection was closed by
2425 * the peer, or -1 on error
2430 g_socket_receive (GSocket *socket,
2433 GCancellable *cancellable,
2436 return g_socket_receive_with_blocking (socket, buffer, size,
2437 socket->priv->blocking,
2438 cancellable, error);
2442 * g_socket_receive_with_blocking:
2443 * @socket: a #GSocket
2444 * @buffer: a buffer to read data into (which should be at least @size
2446 * @size: the number of bytes you want to read from the socket
2447 * @blocking: whether to do blocking or non-blocking I/O
2448 * @cancellable: (allow-none): a %GCancellable or %NULL
2449 * @error: #GError for error reporting, or %NULL to ignore.
2451 * This behaves exactly the same as g_socket_receive(), except that
2452 * the choice of blocking or non-blocking behavior is determined by
2453 * the @blocking argument rather than by @socket's properties.
2455 * Returns: Number of bytes read, or 0 if the connection was closed by
2456 * the peer, or -1 on error
2461 g_socket_receive_with_blocking (GSocket *socket,
2465 GCancellable *cancellable,
2470 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2472 if (!check_socket (socket, error))
2475 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2481 !g_socket_condition_wait (socket,
2482 G_IO_IN, cancellable, error))
2485 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2487 int errsv = get_socket_errno ();
2494 #ifdef WSAEWOULDBLOCK
2495 if (errsv == WSAEWOULDBLOCK)
2498 if (errsv == EWOULDBLOCK ||
2504 win32_unset_event_mask (socket, FD_READ);
2506 g_set_error (error, G_IO_ERROR,
2507 socket_io_error_from_errno (errsv),
2508 _("Error receiving data: %s"), socket_strerror (errsv));
2512 win32_unset_event_mask (socket, FD_READ);
2521 * g_socket_receive_from:
2522 * @socket: a #GSocket
2523 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2525 * @buffer: (array length=size) (element-type guint8): a buffer to
2526 * read data into (which should be at least @size bytes long).
2527 * @size: the number of bytes you want to read from the socket
2528 * @cancellable: (allow-none): a %GCancellable or %NULL
2529 * @error: #GError for error reporting, or %NULL to ignore.
2531 * Receive data (up to @size bytes) from a socket.
2533 * If @address is non-%NULL then @address will be set equal to the
2534 * source address of the received packet.
2535 * @address is owned by the caller.
2537 * See g_socket_receive() for additional information.
2539 * Returns: Number of bytes read, or 0 if the connection was closed by
2540 * the peer, or -1 on error
2545 g_socket_receive_from (GSocket *socket,
2546 GSocketAddress **address,
2549 GCancellable *cancellable,
2557 return g_socket_receive_message (socket,
2565 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2566 * one, which can be confusing and annoying. So if possible, we want
2567 * to suppress the signal entirely.
2570 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2572 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2577 * @socket: a #GSocket
2578 * @buffer: (array length=size) (element-type guint8): the buffer
2579 * containing the data to send.
2580 * @size: the number of bytes to send
2581 * @cancellable: (allow-none): a %GCancellable or %NULL
2582 * @error: #GError for error reporting, or %NULL to ignore.
2584 * Tries to send @size bytes from @buffer on the socket. This is
2585 * mainly used by connection-oriented sockets; it is identical to
2586 * g_socket_send_to() with @address set to %NULL.
2588 * If the socket is in blocking mode the call will block until there is
2589 * space for the data in the socket queue. If there is no space available
2590 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2591 * will be returned. To be notified when space is available, wait for the
2592 * %G_IO_OUT condition. Note though that you may still receive
2593 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2594 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2595 * very common due to the way the underlying APIs work.)
2597 * On error -1 is returned and @error is set accordingly.
2599 * Returns: Number of bytes written (which may be less than @size), or -1
2605 g_socket_send (GSocket *socket,
2606 const gchar *buffer,
2608 GCancellable *cancellable,
2611 return g_socket_send_with_blocking (socket, buffer, size,
2612 socket->priv->blocking,
2613 cancellable, error);
2617 * g_socket_send_with_blocking:
2618 * @socket: a #GSocket
2619 * @buffer: (array length=size) (element-type guint8): the buffer
2620 * containing the data to send.
2621 * @size: the number of bytes to send
2622 * @blocking: whether to do blocking or non-blocking I/O
2623 * @cancellable: (allow-none): a %GCancellable or %NULL
2624 * @error: #GError for error reporting, or %NULL to ignore.
2626 * This behaves exactly the same as g_socket_send(), except that
2627 * the choice of blocking or non-blocking behavior is determined by
2628 * the @blocking argument rather than by @socket's properties.
2630 * Returns: Number of bytes written (which may be less than @size), or -1
2636 g_socket_send_with_blocking (GSocket *socket,
2637 const gchar *buffer,
2640 GCancellable *cancellable,
2645 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2647 if (!check_socket (socket, error))
2650 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2656 !g_socket_condition_wait (socket,
2657 G_IO_OUT, cancellable, error))
2660 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2662 int errsv = get_socket_errno ();
2667 #ifdef WSAEWOULDBLOCK
2668 if (errsv == WSAEWOULDBLOCK)
2669 win32_unset_event_mask (socket, FD_WRITE);
2674 #ifdef WSAEWOULDBLOCK
2675 if (errsv == WSAEWOULDBLOCK)
2678 if (errsv == EWOULDBLOCK ||
2684 g_set_error (error, G_IO_ERROR,
2685 socket_io_error_from_errno (errsv),
2686 _("Error sending data: %s"), socket_strerror (errsv));
2697 * @socket: a #GSocket
2698 * @address: a #GSocketAddress, or %NULL
2699 * @buffer: (array length=size) (element-type guint8): the buffer
2700 * containing the data to send.
2701 * @size: the number of bytes to send
2702 * @cancellable: (allow-none): a %GCancellable or %NULL
2703 * @error: #GError for error reporting, or %NULL to ignore.
2705 * Tries to send @size bytes from @buffer to @address. If @address is
2706 * %NULL then the message is sent to the default receiver (set by
2707 * g_socket_connect()).
2709 * See g_socket_send() for additional information.
2711 * Returns: Number of bytes written (which may be less than @size), or -1
2717 g_socket_send_to (GSocket *socket,
2718 GSocketAddress *address,
2719 const gchar *buffer,
2721 GCancellable *cancellable,
2729 return g_socket_send_message (socket,
2739 * g_socket_shutdown:
2740 * @socket: a #GSocket
2741 * @shutdown_read: whether to shut down the read side
2742 * @shutdown_write: whether to shut down the write side
2743 * @error: #GError for error reporting, or %NULL to ignore.
2745 * Shut down part of a full-duplex connection.
2747 * If @shutdown_read is %TRUE then the receiving side of the connection
2748 * is shut down, and further reading is disallowed.
2750 * If @shutdown_write is %TRUE then the sending side of the connection
2751 * is shut down, and further writing is disallowed.
2753 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2755 * One example where this is used is graceful disconnect for TCP connections
2756 * where you close the sending side, then wait for the other side to close
2757 * the connection, thus ensuring that the other side saw all sent data.
2759 * Returns: %TRUE on success, %FALSE on error
2764 g_socket_shutdown (GSocket *socket,
2765 gboolean shutdown_read,
2766 gboolean shutdown_write,
2771 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2773 if (!check_socket (socket, error))
2777 if (!shutdown_read && !shutdown_write)
2781 if (shutdown_read && shutdown_write)
2783 else if (shutdown_read)
2788 if (shutdown_read && shutdown_write)
2790 else if (shutdown_read)
2796 if (shutdown (socket->priv->fd, how) != 0)
2798 int errsv = get_socket_errno ();
2799 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2800 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2804 if (shutdown_read && shutdown_write)
2805 socket->priv->connected = FALSE;
2812 * @socket: a #GSocket
2813 * @error: #GError for error reporting, or %NULL to ignore.
2815 * Closes the socket, shutting down any active connection.
2817 * Closing a socket does not wait for all outstanding I/O operations
2818 * to finish, so the caller should not rely on them to be guaranteed
2819 * to complete even if the close returns with no error.
2821 * Once the socket is closed, all other operations will return
2822 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2825 * Sockets will be automatically closed when the last reference
2826 * is dropped, but you might want to call this function to make sure
2827 * resources are released as early as possible.
2829 * Beware that due to the way that TCP works, it is possible for
2830 * recently-sent data to be lost if either you close a socket while the
2831 * %G_IO_IN condition is set, or else if the remote connection tries to
2832 * send something to you after you close the socket but before it has
2833 * finished reading all of the data you sent. There is no easy generic
2834 * way to avoid this problem; the easiest fix is to design the network
2835 * protocol such that the client will never send data "out of turn".
2836 * Another solution is for the server to half-close the connection by
2837 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2838 * and then wait for the client to notice this and close its side of the
2839 * connection, after which the server can safely call g_socket_close().
2840 * (This is what #GTcpConnection does if you call
2841 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2842 * only works if the client will close its connection after the server
2845 * Returns: %TRUE on success, %FALSE on error
2850 g_socket_close (GSocket *socket,
2855 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2857 if (socket->priv->closed)
2858 return TRUE; /* Multiple close not an error */
2860 if (!check_socket (socket, error))
2866 res = closesocket (socket->priv->fd);
2868 res = close (socket->priv->fd);
2872 int errsv = get_socket_errno ();
2877 g_set_error (error, G_IO_ERROR,
2878 socket_io_error_from_errno (errsv),
2879 _("Error closing socket: %s"),
2880 socket_strerror (errsv));
2886 socket->priv->connected = FALSE;
2887 socket->priv->closed = TRUE;
2888 if (socket->priv->remote_address)
2890 g_object_unref (socket->priv->remote_address);
2891 socket->priv->remote_address = NULL;
2898 * g_socket_is_closed:
2899 * @socket: a #GSocket
2901 * Checks whether a socket is closed.
2903 * Returns: %TRUE if socket is closed, %FALSE otherwise
2908 g_socket_is_closed (GSocket *socket)
2910 return socket->priv->closed;
2914 /* Broken source, used on errors */
2916 broken_prepare (GSource *source,
2923 broken_check (GSource *source)
2929 broken_dispatch (GSource *source,
2930 GSourceFunc callback,
2936 static GSourceFuncs broken_funcs =
2945 network_events_for_condition (GIOCondition condition)
2949 if (condition & G_IO_IN)
2950 event_mask |= (FD_READ | FD_ACCEPT);
2951 if (condition & G_IO_OUT)
2952 event_mask |= (FD_WRITE | FD_CONNECT);
2953 event_mask |= FD_CLOSE;
2959 ensure_event (GSocket *socket)
2961 if (socket->priv->event == WSA_INVALID_EVENT)
2962 socket->priv->event = WSACreateEvent();
2966 update_select_events (GSocket *socket)
2973 ensure_event (socket);
2976 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2979 event_mask |= network_events_for_condition (*ptr);
2982 if (event_mask != socket->priv->selected_events)
2984 /* If no events selected, disable event so we can unset
2987 if (event_mask == 0)
2990 event = socket->priv->event;
2992 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2993 socket->priv->selected_events = event_mask;
2998 add_condition_watch (GSocket *socket,
2999 GIOCondition *condition)
3001 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3003 socket->priv->requested_conditions =
3004 g_list_prepend (socket->priv->requested_conditions, condition);
3006 update_select_events (socket);
3010 remove_condition_watch (GSocket *socket,
3011 GIOCondition *condition)
3013 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3015 socket->priv->requested_conditions =
3016 g_list_remove (socket->priv->requested_conditions, condition);
3018 update_select_events (socket);
3022 update_condition (GSocket *socket)
3024 WSANETWORKEVENTS events;
3025 GIOCondition condition;
3027 if (WSAEnumNetworkEvents (socket->priv->fd,
3028 socket->priv->event,
3031 socket->priv->current_events |= events.lNetworkEvents;
3032 if (events.lNetworkEvents & FD_WRITE &&
3033 events.iErrorCode[FD_WRITE_BIT] != 0)
3034 socket->priv->current_errors |= FD_WRITE;
3035 if (events.lNetworkEvents & FD_CONNECT &&
3036 events.iErrorCode[FD_CONNECT_BIT] != 0)
3037 socket->priv->current_errors |= FD_CONNECT;
3041 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3042 condition |= G_IO_IN;
3044 if (socket->priv->current_events & FD_CLOSE)
3046 int r, errsv, buffer;
3048 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3050 errsv = get_socket_errno ();
3053 (r < 0 && errsv == WSAENOTCONN))
3054 condition |= G_IO_IN;
3056 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3057 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3058 condition |= G_IO_HUP;
3060 condition |= G_IO_ERR;
3063 if (socket->priv->closed)
3064 condition |= G_IO_HUP;
3066 /* Never report both G_IO_OUT and HUP, these are
3067 mutually exclusive (can't write to a closed socket) */
3068 if ((condition & G_IO_HUP) == 0 &&
3069 socket->priv->current_events & FD_WRITE)
3071 if (socket->priv->current_errors & FD_WRITE)
3072 condition |= G_IO_ERR;
3074 condition |= G_IO_OUT;
3078 if (socket->priv->current_events & FD_CONNECT)
3080 if (socket->priv->current_errors & FD_CONNECT)
3081 condition |= (G_IO_HUP | G_IO_ERR);
3083 condition |= G_IO_OUT;
3095 GIOCondition condition;
3096 GCancellable *cancellable;
3097 GPollFD cancel_pollfd;
3098 gint64 timeout_time;
3102 socket_source_prepare (GSource *source,
3105 GSocketSource *socket_source = (GSocketSource *)source;
3107 if (g_cancellable_is_cancelled (socket_source->cancellable))
3110 if (socket_source->timeout_time)
3114 now = g_source_get_time (source);
3115 /* Round up to ensure that we don't try again too early */
3116 *timeout = (socket_source->timeout_time - now + 999) / 1000;
3119 socket_source->socket->priv->timed_out = TRUE;
3128 socket_source->pollfd.revents = update_condition (socket_source->socket);
3131 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
3138 socket_source_check (GSource *source)
3142 return socket_source_prepare (source, &timeout);
3146 socket_source_dispatch (GSource *source,
3147 GSourceFunc callback,
3150 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3151 GSocketSource *socket_source = (GSocketSource *)source;
3152 GSocket *socket = socket_source->socket;
3156 socket_source->pollfd.revents = update_condition (socket_source->socket);
3158 if (socket_source->socket->priv->timed_out)
3159 socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
3161 ret = (*func) (socket,
3162 socket_source->pollfd.revents & socket_source->condition,
3165 if (socket->priv->timeout)
3166 socket_source->timeout_time = g_get_monotonic_time () +
3167 socket->priv->timeout * 1000000;
3170 socket_source->timeout_time = 0;
3176 socket_source_finalize (GSource *source)
3178 GSocketSource *socket_source = (GSocketSource *)source;
3181 socket = socket_source->socket;
3184 remove_condition_watch (socket, &socket_source->condition);
3187 g_object_unref (socket);
3189 if (socket_source->cancellable)
3191 g_cancellable_release_fd (socket_source->cancellable);
3192 g_object_unref (socket_source->cancellable);
3197 socket_source_closure_callback (GSocket *socket,
3198 GIOCondition condition,
3201 GClosure *closure = data;
3203 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3204 GValue result_value = G_VALUE_INIT;
3207 g_value_init (&result_value, G_TYPE_BOOLEAN);
3209 g_value_init (¶ms[0], G_TYPE_SOCKET);
3210 g_value_set_object (¶ms[0], socket);
3211 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
3212 g_value_set_flags (¶ms[1], condition);
3214 g_closure_invoke (closure, &result_value, 2, params, NULL);
3216 result = g_value_get_boolean (&result_value);
3217 g_value_unset (&result_value);
3218 g_value_unset (¶ms[0]);
3219 g_value_unset (¶ms[1]);
3224 static GSourceFuncs socket_source_funcs =
3226 socket_source_prepare,
3227 socket_source_check,
3228 socket_source_dispatch,
3229 socket_source_finalize,
3230 (GSourceFunc)socket_source_closure_callback,
3231 (GSourceDummyMarshal)g_cclosure_marshal_generic,
3235 socket_source_new (GSocket *socket,
3236 GIOCondition condition,
3237 GCancellable *cancellable)
3240 GSocketSource *socket_source;
3243 ensure_event (socket);
3245 if (socket->priv->event == WSA_INVALID_EVENT)
3247 g_warning ("Failed to create WSAEvent");
3248 return g_source_new (&broken_funcs, sizeof (GSource));
3252 condition |= G_IO_HUP | G_IO_ERR;
3254 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3255 g_source_set_name (source, "GSocket");
3256 socket_source = (GSocketSource *)source;
3258 socket_source->socket = g_object_ref (socket);
3259 socket_source->condition = condition;
3261 if (g_cancellable_make_pollfd (cancellable,
3262 &socket_source->cancel_pollfd))
3264 socket_source->cancellable = g_object_ref (cancellable);
3265 g_source_add_poll (source, &socket_source->cancel_pollfd);
3269 add_condition_watch (socket, &socket_source->condition);
3270 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3272 socket_source->pollfd.fd = socket->priv->fd;
3275 socket_source->pollfd.events = condition;
3276 socket_source->pollfd.revents = 0;
3277 g_source_add_poll (source, &socket_source->pollfd);
3279 if (socket->priv->timeout)
3280 socket_source->timeout_time = g_get_monotonic_time () +
3281 socket->priv->timeout * 1000000;
3284 socket_source->timeout_time = 0;
3290 * g_socket_create_source: (skip)
3291 * @socket: a #GSocket
3292 * @condition: a #GIOCondition mask to monitor
3293 * @cancellable: (allow-none): a %GCancellable or %NULL
3295 * Creates a %GSource that can be attached to a %GMainContext to monitor
3296 * for the availibility of the specified @condition on the socket.
3298 * The callback on the source is of the #GSocketSourceFunc type.
3300 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3301 * these conditions will always be reported output if they are true.
3303 * @cancellable if not %NULL can be used to cancel the source, which will
3304 * cause the source to trigger, reporting the current condition (which
3305 * is likely 0 unless cancellation happened at the same time as a
3306 * condition change). You can check for this in the callback using
3307 * g_cancellable_is_cancelled().
3309 * If @socket has a timeout set, and it is reached before @condition
3310 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3311 * %G_IO_OUT depending on @condition. However, @socket will have been
3312 * marked as having had a timeout, and so the next #GSocket I/O method
3313 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3315 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3320 g_socket_create_source (GSocket *socket,
3321 GIOCondition condition,
3322 GCancellable *cancellable)
3324 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3326 return socket_source_new (socket, condition, cancellable);
3330 * g_socket_condition_check:
3331 * @socket: a #GSocket
3332 * @condition: a #GIOCondition mask to check
3334 * Checks on the readiness of @socket to perform operations.
3335 * The operations specified in @condition are checked for and masked
3336 * against the currently-satisfied conditions on @socket. The result
3339 * Note that on Windows, it is possible for an operation to return
3340 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3341 * g_socket_condition_check() has claimed that the socket is ready for
3342 * writing. Rather than calling g_socket_condition_check() and then
3343 * writing to the socket if it succeeds, it is generally better to
3344 * simply try writing to the socket right away, and try again later if
3345 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3347 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3348 * these conditions will always be set in the output if they are true.
3350 * This call never blocks.
3352 * Returns: the @GIOCondition mask of the current state
3357 g_socket_condition_check (GSocket *socket,
3358 GIOCondition condition)
3360 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3362 if (!check_socket (socket, NULL))
3367 GIOCondition current_condition;
3369 condition |= G_IO_ERR | G_IO_HUP;
3371 add_condition_watch (socket, &condition);
3372 current_condition = update_condition (socket);
3373 remove_condition_watch (socket, &condition);
3374 return condition & current_condition;
3380 poll_fd.fd = socket->priv->fd;
3381 poll_fd.events = condition;
3384 result = g_poll (&poll_fd, 1, 0);
3385 while (result == -1 && get_socket_errno () == EINTR);
3387 return poll_fd.revents;
3393 * g_socket_condition_wait:
3394 * @socket: a #GSocket
3395 * @condition: a #GIOCondition mask to wait for
3396 * @cancellable: (allow-none): a #GCancellable, or %NULL
3397 * @error: a #GError pointer, or %NULL
3399 * Waits for @condition to become true on @socket. When the condition
3400 * is met, %TRUE is returned.
3402 * If @cancellable is cancelled before the condition is met, or if the
3403 * socket has a timeout set and it is reached before the condition is
3404 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3405 * the appropriate value (%G_IO_ERROR_CANCELLED or
3406 * %G_IO_ERROR_TIMED_OUT).
3408 * See also g_socket_condition_timed_wait().
3410 * Returns: %TRUE if the condition was met, %FALSE otherwise
3415 g_socket_condition_wait (GSocket *socket,
3416 GIOCondition condition,
3417 GCancellable *cancellable,
3420 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3422 return g_socket_condition_timed_wait (socket, condition, -1,
3423 cancellable, error);
3427 * g_socket_condition_timed_wait:
3428 * @socket: a #GSocket
3429 * @condition: a #GIOCondition mask to wait for
3430 * @timeout: the maximum time (in microseconds) to wait, or -1
3431 * @cancellable: (allow-none): a #GCancellable, or %NULL
3432 * @error: a #GError pointer, or %NULL
3434 * Waits for up to @timeout microseconds for @condition to become true
3435 * on @socket. If the condition is met, %TRUE is returned.
3437 * If @cancellable is cancelled before the condition is met, or if
3438 * @timeout (or the socket's #GSocket:timeout) is reached before the
3439 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3440 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3441 * %G_IO_ERROR_TIMED_OUT).
3443 * If you don't want a timeout, use g_socket_condition_wait().
3444 * (Alternatively, you can pass -1 for @timeout.)
3446 * Note that although @timeout is in microseconds for consistency with
3447 * other GLib APIs, this function actually only has millisecond
3448 * resolution, and the behavior is undefined if @timeout is not an
3449 * exact number of milliseconds.
3451 * Returns: %TRUE if the condition was met, %FALSE otherwise
3456 g_socket_condition_timed_wait (GSocket *socket,
3457 GIOCondition condition,
3459 GCancellable *cancellable,
3464 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3466 if (!check_socket (socket, error))
3469 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3472 if (socket->priv->timeout &&
3473 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3474 timeout = socket->priv->timeout * 1000;
3475 else if (timeout != -1)
3476 timeout = timeout / 1000;
3478 start_time = g_get_monotonic_time ();
3482 GIOCondition current_condition;
3488 /* Always check these */
3489 condition |= G_IO_ERR | G_IO_HUP;
3491 add_condition_watch (socket, &condition);
3494 events[num_events++] = socket->priv->event;
3496 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3497 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3500 timeout = WSA_INFINITE;
3502 current_condition = update_condition (socket);
3503 while ((condition & current_condition) == 0)
3505 res = WSAWaitForMultipleEvents (num_events, events,
3506 FALSE, timeout, FALSE);
3507 if (res == WSA_WAIT_FAILED)
3509 int errsv = get_socket_errno ();
3511 g_set_error (error, G_IO_ERROR,
3512 socket_io_error_from_errno (errsv),
3513 _("Waiting for socket condition: %s"),
3514 socket_strerror (errsv));
3517 else if (res == WSA_WAIT_TIMEOUT)
3519 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3520 _("Socket I/O timed out"));
3524 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3527 current_condition = update_condition (socket);
3529 if (timeout != WSA_INFINITE)
3531 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3536 remove_condition_watch (socket, &condition);
3538 g_cancellable_release_fd (cancellable);
3540 return (condition & current_condition) != 0;
3548 poll_fd[0].fd = socket->priv->fd;
3549 poll_fd[0].events = condition;
3552 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3557 result = g_poll (poll_fd, num, timeout);
3558 if (result != -1 || errno != EINTR)
3563 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3570 g_cancellable_release_fd (cancellable);
3574 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3575 _("Socket I/O timed out"));
3579 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3585 * g_socket_send_message:
3586 * @socket: a #GSocket
3587 * @address: a #GSocketAddress, or %NULL
3588 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3589 * @num_vectors: the number of elements in @vectors, or -1
3590 * @messages: (array length=num_messages) (allow-none): a pointer to an
3591 * array of #GSocketControlMessages, or %NULL.
3592 * @num_messages: number of elements in @messages, or -1.
3593 * @flags: an int containing #GSocketMsgFlags flags
3594 * @cancellable: (allow-none): a %GCancellable or %NULL
3595 * @error: #GError for error reporting, or %NULL to ignore.
3597 * Send data to @address on @socket. This is the most complicated and
3598 * fully-featured version of this call. For easier use, see
3599 * g_socket_send() and g_socket_send_to().
3601 * If @address is %NULL then the message is sent to the default receiver
3602 * (set by g_socket_connect()).
3604 * @vectors must point to an array of #GOutputVector structs and
3605 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3606 * then @vectors is assumed to be terminated by a #GOutputVector with a
3607 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3608 * that the sent data will be gathered from. Using multiple
3609 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3610 * data from multiple sources into a single buffer, and more
3611 * network-efficient than making multiple calls to g_socket_send().
3613 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3614 * #GSocketControlMessage instances. These correspond to the control
3615 * messages to be sent on the socket.
3616 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3619 * @flags modify how the message is sent. The commonly available arguments
3620 * for this are available in the #GSocketMsgFlags enum, but the
3621 * values there are the same as the system values, and the flags
3622 * are passed in as-is, so you can pass in system-specific flags too.
3624 * If the socket is in blocking mode the call will block until there is
3625 * space for the data in the socket queue. If there is no space available
3626 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3627 * will be returned. To be notified when space is available, wait for the
3628 * %G_IO_OUT condition. Note though that you may still receive
3629 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3630 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3631 * very common due to the way the underlying APIs work.)
3633 * On error -1 is returned and @error is set accordingly.
3635 * Returns: Number of bytes written (which may be less than @size), or -1
3641 g_socket_send_message (GSocket *socket,
3642 GSocketAddress *address,
3643 GOutputVector *vectors,
3645 GSocketControlMessage **messages,
3648 GCancellable *cancellable,
3651 GOutputVector one_vector;
3654 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3656 if (!check_socket (socket, error))
3659 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3662 if (num_vectors == -1)
3664 for (num_vectors = 0;
3665 vectors[num_vectors].buffer != NULL;
3670 if (num_messages == -1)
3672 for (num_messages = 0;
3673 messages != NULL && messages[num_messages] != NULL;
3678 if (num_vectors == 0)
3682 one_vector.buffer = &zero;
3683 one_vector.size = 1;
3685 vectors = &one_vector;
3698 msg.msg_namelen = g_socket_address_get_native_size (address);
3699 msg.msg_name = g_alloca (msg.msg_namelen);
3700 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3705 msg.msg_name = NULL;
3706 msg.msg_namelen = 0;
3711 /* this entire expression will be evaluated at compile time */
3712 if (sizeof *msg.msg_iov == sizeof *vectors &&
3713 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3714 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3715 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3716 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3717 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3718 G_STRUCT_OFFSET (GOutputVector, size))
3719 /* ABI is compatible */
3721 msg.msg_iov = (struct iovec *) vectors;
3722 msg.msg_iovlen = num_vectors;
3725 /* ABI is incompatible */
3729 msg.msg_iov = g_newa (struct iovec, num_vectors);
3730 for (i = 0; i < num_vectors; i++)
3732 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3733 msg.msg_iov[i].iov_len = vectors[i].size;
3735 msg.msg_iovlen = num_vectors;
3741 struct cmsghdr *cmsg;
3744 msg.msg_controllen = 0;
3745 for (i = 0; i < num_messages; i++)
3746 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3748 if (msg.msg_controllen == 0)
3749 msg.msg_control = NULL;
3752 msg.msg_control = g_alloca (msg.msg_controllen);
3753 memset (msg.msg_control, '\0', msg.msg_controllen);
3756 cmsg = CMSG_FIRSTHDR (&msg);
3757 for (i = 0; i < num_messages; i++)
3759 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3760 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3761 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3762 g_socket_control_message_serialize (messages[i],
3764 cmsg = CMSG_NXTHDR (&msg, cmsg);
3766 g_assert (cmsg == NULL);
3771 if (socket->priv->blocking &&
3772 !g_socket_condition_wait (socket,
3773 G_IO_OUT, cancellable, error))
3776 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3779 int errsv = get_socket_errno ();
3784 if (socket->priv->blocking &&
3785 (errsv == EWOULDBLOCK ||
3789 g_set_error (error, G_IO_ERROR,
3790 socket_io_error_from_errno (errsv),
3791 _("Error sending message: %s"), socket_strerror (errsv));
3802 struct sockaddr_storage addr;
3809 /* Win32 doesn't support control messages.
3810 Actually this is possible for raw and datagram sockets
3811 via WSASendMessage on Vista or later, but that doesn't
3813 if (num_messages != 0)
3815 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3816 _("GSocketControlMessage not supported on windows"));
3821 bufs = g_newa (WSABUF, num_vectors);
3822 for (i = 0; i < num_vectors; i++)
3824 bufs[i].buf = (char *)vectors[i].buffer;
3825 bufs[i].len = (gulong)vectors[i].size;
3829 addrlen = 0; /* Avoid warning */
3832 addrlen = g_socket_address_get_native_size (address);
3833 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3839 if (socket->priv->blocking &&
3840 !g_socket_condition_wait (socket,
3841 G_IO_OUT, cancellable, error))
3845 result = WSASendTo (socket->priv->fd,
3848 (const struct sockaddr *)&addr, addrlen,
3851 result = WSASend (socket->priv->fd,
3858 int errsv = get_socket_errno ();
3860 if (errsv == WSAEINTR)
3863 if (errsv == WSAEWOULDBLOCK)
3864 win32_unset_event_mask (socket, FD_WRITE);
3866 if (socket->priv->blocking &&
3867 errsv == WSAEWOULDBLOCK)
3870 g_set_error (error, G_IO_ERROR,
3871 socket_io_error_from_errno (errsv),
3872 _("Error sending message: %s"), socket_strerror (errsv));
3885 * g_socket_receive_message:
3886 * @socket: a #GSocket
3887 * @address: (out) (allow-none): a pointer to a #GSocketAddress
3889 * @vectors: (array length=num_vectors): an array of #GInputVector structs
3890 * @num_vectors: the number of elements in @vectors, or -1
3891 * @messages: (array length=num_messages) (allow-none): a pointer which
3892 * may be filled with an array of #GSocketControlMessages, or %NULL
3893 * @num_messages: a pointer which will be filled with the number of
3894 * elements in @messages, or %NULL
3895 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3896 * @cancellable: (allow-none): a %GCancellable or %NULL
3897 * @error: a #GError pointer, or %NULL
3899 * Receive data from a socket. This is the most complicated and
3900 * fully-featured version of this call. For easier use, see
3901 * g_socket_receive() and g_socket_receive_from().
3903 * If @address is non-%NULL then @address will be set equal to the
3904 * source address of the received packet.
3905 * @address is owned by the caller.
3907 * @vector must point to an array of #GInputVector structs and
3908 * @num_vectors must be the length of this array. These structs
3909 * describe the buffers that received data will be scattered into.
3910 * If @num_vectors is -1, then @vectors is assumed to be terminated
3911 * by a #GInputVector with a %NULL buffer pointer.
3913 * As a special case, if @num_vectors is 0 (in which case, @vectors
3914 * may of course be %NULL), then a single byte is received and
3915 * discarded. This is to facilitate the common practice of sending a
3916 * single '\0' byte for the purposes of transferring ancillary data.
3918 * @messages, if non-%NULL, will be set to point to a newly-allocated
3919 * array of #GSocketControlMessage instances or %NULL if no such
3920 * messages was received. These correspond to the control messages
3921 * received from the kernel, one #GSocketControlMessage per message
3922 * from the kernel. This array is %NULL-terminated and must be freed
3923 * by the caller using g_free() after calling g_object_unref() on each
3924 * element. If @messages is %NULL, any control messages received will
3927 * @num_messages, if non-%NULL, will be set to the number of control
3928 * messages received.
3930 * If both @messages and @num_messages are non-%NULL, then
3931 * @num_messages gives the number of #GSocketControlMessage instances
3932 * in @messages (ie: not including the %NULL terminator).
3934 * @flags is an in/out parameter. The commonly available arguments
3935 * for this are available in the #GSocketMsgFlags enum, but the
3936 * values there are the same as the system values, and the flags
3937 * are passed in as-is, so you can pass in system-specific flags too
3938 * (and g_socket_receive_message() may pass system-specific flags out).
3940 * As with g_socket_receive(), data may be discarded if @socket is
3941 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3942 * provide enough buffer space to read a complete message. You can pass
3943 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3944 * removing it from the receive queue, but there is no portable way to find
3945 * out the length of the message other than by reading it into a
3946 * sufficiently-large buffer.
3948 * If the socket is in blocking mode the call will block until there
3949 * is some data to receive, the connection is closed, or there is an
3950 * error. If there is no data available and the socket is in
3951 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3952 * returned. To be notified when data is available, wait for the
3953 * %G_IO_IN condition.
3955 * On error -1 is returned and @error is set accordingly.
3957 * Returns: Number of bytes read, or 0 if the connection was closed by
3958 * the peer, or -1 on error
3963 g_socket_receive_message (GSocket *socket,
3964 GSocketAddress **address,
3965 GInputVector *vectors,
3967 GSocketControlMessage ***messages,
3970 GCancellable *cancellable,
3973 GInputVector one_vector;
3976 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3978 if (!check_socket (socket, error))
3981 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3984 if (num_vectors == -1)
3986 for (num_vectors = 0;
3987 vectors[num_vectors].buffer != NULL;
3992 if (num_vectors == 0)
3994 one_vector.buffer = &one_byte;
3995 one_vector.size = 1;
3997 vectors = &one_vector;
4004 struct sockaddr_storage one_sockaddr;
4009 msg.msg_name = &one_sockaddr;
4010 msg.msg_namelen = sizeof (struct sockaddr_storage);
4014 msg.msg_name = NULL;
4015 msg.msg_namelen = 0;
4019 /* this entire expression will be evaluated at compile time */
4020 if (sizeof *msg.msg_iov == sizeof *vectors &&
4021 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4022 G_STRUCT_OFFSET (struct iovec, iov_base) ==
4023 G_STRUCT_OFFSET (GInputVector, buffer) &&
4024 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4025 G_STRUCT_OFFSET (struct iovec, iov_len) ==
4026 G_STRUCT_OFFSET (GInputVector, size))
4027 /* ABI is compatible */
4029 msg.msg_iov = (struct iovec *) vectors;
4030 msg.msg_iovlen = num_vectors;
4033 /* ABI is incompatible */
4037 msg.msg_iov = g_newa (struct iovec, num_vectors);
4038 for (i = 0; i < num_vectors; i++)
4040 msg.msg_iov[i].iov_base = vectors[i].buffer;
4041 msg.msg_iov[i].iov_len = vectors[i].size;
4043 msg.msg_iovlen = num_vectors;
4047 msg.msg_control = g_alloca (2048);
4048 msg.msg_controllen = 2048;
4052 msg.msg_flags = *flags;
4056 /* We always set the close-on-exec flag so we don't leak file
4057 * descriptors into child processes. Note that gunixfdmessage.c
4058 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4060 #ifdef MSG_CMSG_CLOEXEC
4061 msg.msg_flags |= MSG_CMSG_CLOEXEC;
4067 if (socket->priv->blocking &&
4068 !g_socket_condition_wait (socket,
4069 G_IO_IN, cancellable, error))
4072 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4073 #ifdef MSG_CMSG_CLOEXEC
4074 if (result < 0 && get_socket_errno () == EINVAL)
4076 /* We must be running on an old kernel. Call without the flag. */
4077 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4078 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4084 int errsv = get_socket_errno ();
4089 if (socket->priv->blocking &&
4090 (errsv == EWOULDBLOCK ||
4094 g_set_error (error, G_IO_ERROR,
4095 socket_io_error_from_errno (errsv),
4096 _("Error receiving message: %s"), socket_strerror (errsv));
4103 /* decode address */
4104 if (address != NULL)
4106 if (msg.msg_namelen > 0)
4107 *address = g_socket_address_new_from_native (msg.msg_name,
4113 /* decode control messages */
4115 GPtrArray *my_messages = NULL;
4116 struct cmsghdr *cmsg;
4118 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4120 GSocketControlMessage *message;
4122 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4124 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4126 if (message == NULL)
4127 /* We've already spewed about the problem in the
4128 deserialization code, so just continue */
4131 if (messages == NULL)
4133 /* we have to do it this way if the user ignores the
4134 * messages so that we will close any received fds.
4136 g_object_unref (message);
4140 if (my_messages == NULL)
4141 my_messages = g_ptr_array_new ();
4142 g_ptr_array_add (my_messages, message);
4147 *num_messages = my_messages != NULL ? my_messages->len : 0;
4151 if (my_messages == NULL)
4157 g_ptr_array_add (my_messages, NULL);
4158 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4163 g_assert (my_messages == NULL);
4167 /* capture the flags */
4169 *flags = msg.msg_flags;
4175 struct sockaddr_storage addr;
4177 DWORD bytes_received;
4184 bufs = g_newa (WSABUF, num_vectors);
4185 for (i = 0; i < num_vectors; i++)
4187 bufs[i].buf = (char *)vectors[i].buffer;
4188 bufs[i].len = (gulong)vectors[i].size;
4200 if (socket->priv->blocking &&
4201 !g_socket_condition_wait (socket,
4202 G_IO_IN, cancellable, error))
4205 addrlen = sizeof addr;
4207 result = WSARecvFrom (socket->priv->fd,
4209 &bytes_received, &win_flags,
4210 (struct sockaddr *)&addr, &addrlen,
4213 result = WSARecv (socket->priv->fd,
4215 &bytes_received, &win_flags,
4219 int errsv = get_socket_errno ();
4221 if (errsv == WSAEINTR)
4224 win32_unset_event_mask (socket, FD_READ);
4226 if (socket->priv->blocking &&
4227 errsv == WSAEWOULDBLOCK)
4230 g_set_error (error, G_IO_ERROR,
4231 socket_io_error_from_errno (errsv),
4232 _("Error receiving message: %s"), socket_strerror (errsv));
4236 win32_unset_event_mask (socket, FD_READ);
4240 /* decode address */
4241 if (address != NULL)
4244 *address = g_socket_address_new_from_native (&addr, addrlen);
4249 /* capture the flags */
4253 if (messages != NULL)
4255 if (num_messages != NULL)
4258 return bytes_received;
4264 * g_socket_get_credentials:
4265 * @socket: a #GSocket.
4266 * @error: #GError for error reporting, or %NULL to ignore.
4268 * Returns the credentials of the foreign process connected to this
4269 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4272 * If this operation isn't supported on the OS, the method fails with
4273 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4274 * by reading the %SO_PEERCRED option on the underlying socket.
4276 * Other ways to obtain credentials from a foreign peer includes the
4277 * #GUnixCredentialsMessage type and
4278 * g_unix_connection_send_credentials() /
4279 * g_unix_connection_receive_credentials() functions.
4281 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4282 * that must be freed with g_object_unref().
4287 g_socket_get_credentials (GSocket *socket,
4292 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4293 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4297 #if defined(__linux__) || defined(__OpenBSD__)
4300 #if defined(__linux__)
4301 struct ucred native_creds;
4302 optlen = sizeof (struct ucred);
4303 #elif defined(__OpenBSD__)
4304 struct sockpeercred native_creds;
4305 optlen = sizeof (struct sockpeercred);
4307 if (getsockopt (socket->priv->fd,
4310 (void *)&native_creds,
4313 int errsv = get_socket_errno ();
4316 socket_io_error_from_errno (errsv),
4317 _("Unable to get pending error: %s"),
4318 socket_strerror (errsv));
4322 ret = g_credentials_new ();
4323 g_credentials_set_native (ret,
4324 #if defined(__linux__)
4325 G_CREDENTIALS_TYPE_LINUX_UCRED,
4326 #elif defined(__OpenBSD__)
4327 G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
4333 g_set_error_literal (error,
4335 G_IO_ERROR_NOT_SUPPORTED,
4336 _("g_socket_get_credentials not implemented for this OS"));