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"
50 #include "gcancellable.h"
51 #include "gioenumtypes.h"
52 #include "ginetaddress.h"
53 #include "ginitable.h"
57 #include "gnetworkingprivate.h"
58 #include "gsocketaddress.h"
59 #include "gsocketcontrolmessage.h"
60 #include "gcredentials.h"
65 * @short_description: Low-level socket object
67 * @see_also: #GInitable
69 * A #GSocket is a low-level networking primitive. It is a more or less
70 * direct mapping of the BSD socket API in a portable GObject based API.
71 * It supports both the UNIX socket implementations and winsock2 on Windows.
73 * #GSocket is the platform independent base upon which the higher level
74 * network primitives are based. Applications are not typically meant to
75 * use it directly, but rather through classes like #GSocketClient,
76 * #GSocketService and #GSocketConnection. However there may be cases where
77 * direct use of #GSocket is useful.
79 * #GSocket implements the #GInitable interface, so if it is manually constructed
80 * by e.g. g_object_new() you must call g_initable_init() and check the
81 * results before using the object. This is done automatically in
82 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
85 * Sockets operate in two general modes, blocking or non-blocking. When
86 * in blocking mode all operations block until the requested operation
87 * is finished or there is an error. In non-blocking mode all calls that
88 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
89 * To know when a call would successfully run you can call g_socket_condition_check(),
90 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
91 * attach it to a #GMainContext to get callbacks when I/O is possible.
92 * Note that all sockets are always set to non blocking mode in the system, and
93 * blocking mode is emulated in GSocket.
95 * When working in non-blocking mode applications should always be able to
96 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
97 * function said that I/O was possible. This can easily happen in case
98 * of a race condition in the application, but it can also happen for other
99 * reasons. For instance, on Windows a socket is always seen as writable
100 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
102 * #GSocket<!-- -->s can be either connection oriented or datagram based.
103 * For connection oriented types you must first establish a connection by
104 * either connecting to an address or accepting a connection from another
105 * address. For connectionless socket types the target/source address is
106 * specified or received in each I/O operation.
108 * All socket file descriptors are set to be close-on-exec.
110 * Note that creating a #GSocket causes the signal %SIGPIPE to be
111 * ignored for the remainder of the program. If you are writing a
112 * command-line utility that uses #GSocket, you may need to take into
113 * account the fact that your program will not automatically be killed
114 * if it tries to write to %stdout after it has been closed.
119 static void g_socket_initable_iface_init (GInitableIface *iface);
120 static gboolean g_socket_initable_init (GInitable *initable,
121 GCancellable *cancellable,
124 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
125 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
126 g_socket_initable_iface_init));
141 PROP_MULTICAST_LOOPBACK,
145 struct _GSocketPrivate
147 GSocketFamily family;
149 GSocketProtocol protocol;
153 GError *construct_error;
154 GSocketAddress *remote_address;
162 guint connect_pending : 1;
168 GList *requested_conditions; /* list of requested GIOCondition * */
173 get_socket_errno (void)
178 return WSAGetLastError ();
183 socket_io_error_from_errno (int err)
186 return g_io_error_from_errno (err);
191 return G_IO_ERROR_ADDRESS_IN_USE;
193 return G_IO_ERROR_WOULD_BLOCK;
195 return G_IO_ERROR_PERMISSION_DENIED;
196 case WSA_INVALID_HANDLE:
197 case WSA_INVALID_PARAMETER:
200 return G_IO_ERROR_INVALID_ARGUMENT;
201 case WSAEPROTONOSUPPORT:
202 return G_IO_ERROR_NOT_SUPPORTED;
204 return G_IO_ERROR_CANCELLED;
205 case WSAESOCKTNOSUPPORT:
207 case WSAEPFNOSUPPORT:
208 case WSAEAFNOSUPPORT:
209 return G_IO_ERROR_NOT_SUPPORTED;
211 return G_IO_ERROR_FAILED;
217 socket_strerror (int err)
220 return g_strerror (err);
225 msg = g_win32_error_message (err);
227 msg_ret = g_intern_string (msg);
235 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
237 _win32_unset_event_mask (GSocket *socket, int mask)
239 socket->priv->current_events &= ~mask;
240 socket->priv->current_errors &= ~mask;
243 #define win32_unset_event_mask(_socket, _mask)
247 set_fd_nonblocking (int fd)
250 GError *error = NULL;
256 if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
258 g_warning ("Error setting socket nonblocking: %s", error->message);
259 g_clear_error (&error);
264 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
266 int errsv = get_socket_errno ();
267 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
273 check_socket (GSocket *socket,
276 if (!socket->priv->inited)
278 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
279 _("Invalid socket, not initialized"));
283 if (socket->priv->construct_error)
285 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
286 _("Invalid socket, initialization failed due to: %s"),
287 socket->priv->construct_error->message);
291 if (socket->priv->closed)
293 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
294 _("Socket is already closed"));
298 if (socket->priv->timed_out)
300 socket->priv->timed_out = FALSE;
301 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
302 _("Socket I/O timed out"));
310 g_socket_details_from_fd (GSocket *socket)
312 struct sockaddr_storage address;
319 /* See bug #611756 */
320 BOOL bool_val = FALSE;
325 fd = socket->priv->fd;
326 optlen = sizeof value;
327 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
329 errsv = get_socket_errno ();
340 /* programmer error */
341 g_error ("creating GSocket from fd %d: %s\n",
342 fd, socket_strerror (errsv));
350 g_assert (optlen == sizeof value);
354 socket->priv->type = G_SOCKET_TYPE_STREAM;
358 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
362 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
366 socket->priv->type = G_SOCKET_TYPE_INVALID;
370 addrlen = sizeof address;
371 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
373 errsv = get_socket_errno ();
379 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
380 sizeof address.ss_family <= addrlen);
381 family = address.ss_family;
385 /* On Solaris, this happens if the socket is not yet connected.
386 * But we can use SO_DOMAIN as a workaround there.
389 optlen = sizeof family;
390 if (getsockopt (fd, SOL_SOCKET, SO_DOMAIN, (void *)&family, &optlen) != 0)
392 errsv = get_socket_errno ();
396 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
404 case G_SOCKET_FAMILY_IPV4:
405 case G_SOCKET_FAMILY_IPV6:
406 socket->priv->family = address.ss_family;
407 switch (socket->priv->type)
409 case G_SOCKET_TYPE_STREAM:
410 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
413 case G_SOCKET_TYPE_DATAGRAM:
414 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
417 case G_SOCKET_TYPE_SEQPACKET:
418 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
426 case G_SOCKET_FAMILY_UNIX:
427 socket->priv->family = G_SOCKET_FAMILY_UNIX;
428 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
432 socket->priv->family = G_SOCKET_FAMILY_INVALID;
436 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
438 addrlen = sizeof address;
439 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
440 socket->priv->connected = TRUE;
443 optlen = sizeof bool_val;
444 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
445 (void *)&bool_val, &optlen) == 0)
448 /* Experimentation indicates that the SO_KEEPALIVE value is
449 * actually a char on Windows, even if documentation claims it
450 * to be a BOOL which is a typedef for int. So this g_assert()
451 * fails. See bug #611756.
453 g_assert (optlen == sizeof bool_val);
455 socket->priv->keepalive = !!bool_val;
459 /* Can't read, maybe not supported, assume FALSE */
460 socket->priv->keepalive = FALSE;
466 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
467 socket_io_error_from_errno (errsv),
468 _("creating GSocket from fd: %s"),
469 socket_strerror (errsv));
473 g_socket_create_socket (GSocketFamily family,
483 case G_SOCKET_TYPE_STREAM:
484 native_type = SOCK_STREAM;
487 case G_SOCKET_TYPE_DATAGRAM:
488 native_type = SOCK_DGRAM;
491 case G_SOCKET_TYPE_SEQPACKET:
492 native_type = SOCK_SEQPACKET;
496 g_assert_not_reached ();
501 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
502 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
507 fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
508 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
509 if (fd < 0 && errno == EINVAL)
511 fd = socket (family, native_type, protocol);
515 int errsv = get_socket_errno ();
517 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
518 _("Unable to create socket: %s"), socket_strerror (errsv));
525 /* We always want to set close-on-exec to protect users. If you
526 need to so some weird inheritance to exec you can re-enable this
527 using lower level hacks with g_socket_get_fd(). */
528 flags = fcntl (fd, F_GETFD, 0);
530 (flags & FD_CLOEXEC) == 0)
533 fcntl (fd, F_SETFD, flags);
542 g_socket_constructed (GObject *object)
544 GSocket *socket = G_SOCKET (object);
546 if (socket->priv->fd >= 0)
547 /* create socket->priv info from the fd */
548 g_socket_details_from_fd (socket);
551 /* create the fd from socket->priv info */
552 socket->priv->fd = g_socket_create_socket (socket->priv->family,
554 socket->priv->protocol,
555 &socket->priv->construct_error);
557 /* Always use native nonblocking sockets, as
558 windows sets sockets to nonblocking automatically
559 in certain operations. This way we make things work
560 the same on all platforms */
561 if (socket->priv->fd != -1)
562 set_fd_nonblocking (socket->priv->fd);
566 g_socket_get_property (GObject *object,
571 GSocket *socket = G_SOCKET (object);
572 GSocketAddress *address;
577 g_value_set_enum (value, socket->priv->family);
581 g_value_set_enum (value, socket->priv->type);
585 g_value_set_enum (value, socket->priv->protocol);
589 g_value_set_int (value, socket->priv->fd);
593 g_value_set_boolean (value, socket->priv->blocking);
596 case PROP_LISTEN_BACKLOG:
597 g_value_set_int (value, socket->priv->listen_backlog);
601 g_value_set_boolean (value, socket->priv->keepalive);
604 case PROP_LOCAL_ADDRESS:
605 address = g_socket_get_local_address (socket, NULL);
606 g_value_take_object (value, address);
609 case PROP_REMOTE_ADDRESS:
610 address = g_socket_get_remote_address (socket, NULL);
611 g_value_take_object (value, address);
615 g_value_set_uint (value, socket->priv->timeout);
618 case PROP_MULTICAST_LOOPBACK:
619 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
622 case PROP_MULTICAST_TTL:
623 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
627 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
632 g_socket_set_property (GObject *object,
637 GSocket *socket = G_SOCKET (object);
642 socket->priv->family = g_value_get_enum (value);
646 socket->priv->type = g_value_get_enum (value);
650 socket->priv->protocol = g_value_get_enum (value);
654 socket->priv->fd = g_value_get_int (value);
658 g_socket_set_blocking (socket, g_value_get_boolean (value));
661 case PROP_LISTEN_BACKLOG:
662 g_socket_set_listen_backlog (socket, g_value_get_int (value));
666 g_socket_set_keepalive (socket, g_value_get_boolean (value));
670 g_socket_set_timeout (socket, g_value_get_uint (value));
673 case PROP_MULTICAST_LOOPBACK:
674 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
677 case PROP_MULTICAST_TTL:
678 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
682 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
687 g_socket_finalize (GObject *object)
689 GSocket *socket = G_SOCKET (object);
691 g_clear_error (&socket->priv->construct_error);
693 if (socket->priv->fd != -1 &&
694 !socket->priv->closed)
695 g_socket_close (socket, NULL);
697 if (socket->priv->remote_address)
698 g_object_unref (socket->priv->remote_address);
701 if (socket->priv->event != WSA_INVALID_EVENT)
703 WSACloseEvent (socket->priv->event);
704 socket->priv->event = WSA_INVALID_EVENT;
707 g_assert (socket->priv->requested_conditions == NULL);
710 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
711 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
715 g_socket_class_init (GSocketClass *klass)
717 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
720 /* Make sure winsock has been initialized */
721 type = g_inet_address_get_type ();
722 (type); /* To avoid -Wunused-but-set-variable */
725 /* There is no portable, thread-safe way to avoid having the process
726 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
727 * forced to simply ignore the signal process-wide.
729 signal (SIGPIPE, SIG_IGN);
732 g_type_class_add_private (klass, sizeof (GSocketPrivate));
734 gobject_class->finalize = g_socket_finalize;
735 gobject_class->constructed = g_socket_constructed;
736 gobject_class->set_property = g_socket_set_property;
737 gobject_class->get_property = g_socket_get_property;
739 g_object_class_install_property (gobject_class, PROP_FAMILY,
740 g_param_spec_enum ("family",
742 P_("The sockets address family"),
743 G_TYPE_SOCKET_FAMILY,
744 G_SOCKET_FAMILY_INVALID,
745 G_PARAM_CONSTRUCT_ONLY |
747 G_PARAM_STATIC_STRINGS));
749 g_object_class_install_property (gobject_class, PROP_TYPE,
750 g_param_spec_enum ("type",
752 P_("The sockets type"),
754 G_SOCKET_TYPE_STREAM,
755 G_PARAM_CONSTRUCT_ONLY |
757 G_PARAM_STATIC_STRINGS));
759 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
760 g_param_spec_enum ("protocol",
761 P_("Socket protocol"),
762 P_("The id of the protocol to use, or -1 for unknown"),
763 G_TYPE_SOCKET_PROTOCOL,
764 G_SOCKET_PROTOCOL_UNKNOWN,
765 G_PARAM_CONSTRUCT_ONLY |
767 G_PARAM_STATIC_STRINGS));
769 g_object_class_install_property (gobject_class, PROP_FD,
770 g_param_spec_int ("fd",
771 P_("File descriptor"),
772 P_("The sockets file descriptor"),
776 G_PARAM_CONSTRUCT_ONLY |
778 G_PARAM_STATIC_STRINGS));
780 g_object_class_install_property (gobject_class, PROP_BLOCKING,
781 g_param_spec_boolean ("blocking",
783 P_("Whether or not I/O on this socket is blocking"),
786 G_PARAM_STATIC_STRINGS));
788 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
789 g_param_spec_int ("listen-backlog",
790 P_("Listen backlog"),
791 P_("Outstanding connections in the listen queue"),
796 G_PARAM_STATIC_STRINGS));
798 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
799 g_param_spec_boolean ("keepalive",
800 P_("Keep connection alive"),
801 P_("Keep connection alive by sending periodic pings"),
804 G_PARAM_STATIC_STRINGS));
806 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
807 g_param_spec_object ("local-address",
809 P_("The local address the socket is bound to"),
810 G_TYPE_SOCKET_ADDRESS,
812 G_PARAM_STATIC_STRINGS));
814 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
815 g_param_spec_object ("remote-address",
816 P_("Remote address"),
817 P_("The remote address the socket is connected to"),
818 G_TYPE_SOCKET_ADDRESS,
820 G_PARAM_STATIC_STRINGS));
825 * The timeout in seconds on socket I/O
829 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
830 g_param_spec_uint ("timeout",
832 P_("The timeout in seconds on socket I/O"),
837 G_PARAM_STATIC_STRINGS));
840 * GSocket:multicast-loopback:
842 * Whether outgoing multicast packets loop back to the local host.
846 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
847 g_param_spec_boolean ("multicast-loopback",
848 P_("Multicast loopback"),
849 P_("Whether outgoing multicast packets loop back to the local host"),
852 G_PARAM_STATIC_STRINGS));
855 * GSocket:multicast-ttl:
857 * Time-to-live out outgoing multicast packets
861 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
862 g_param_spec_uint ("multicast-ttl",
864 P_("Time-to-live of outgoing multicast packets"),
867 G_PARAM_STATIC_STRINGS));
871 g_socket_initable_iface_init (GInitableIface *iface)
873 iface->init = g_socket_initable_init;
877 g_socket_init (GSocket *socket)
879 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
881 socket->priv->fd = -1;
882 socket->priv->blocking = TRUE;
883 socket->priv->listen_backlog = 10;
884 socket->priv->construct_error = NULL;
886 socket->priv->event = WSA_INVALID_EVENT;
891 g_socket_initable_init (GInitable *initable,
892 GCancellable *cancellable,
897 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
899 socket = G_SOCKET (initable);
901 if (cancellable != NULL)
903 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
904 _("Cancellable initialization not supported"));
908 socket->priv->inited = TRUE;
910 if (socket->priv->construct_error)
913 *error = g_error_copy (socket->priv->construct_error);
923 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
924 * @type: the socket type to use.
925 * @protocol: the id of the protocol to use, or 0 for default.
926 * @error: #GError for error reporting, or %NULL to ignore.
928 * Creates a new #GSocket with the defined family, type and protocol.
929 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
930 * for the family and type is used.
932 * The @protocol is a family and type specific int that specifies what
933 * kind of protocol to use. #GSocketProtocol lists several common ones.
934 * Many families only support one protocol, and use 0 for this, others
935 * support several and using 0 means to use the default protocol for
936 * the family and type.
938 * The protocol id is passed directly to the operating
939 * system, so you can use protocols not listed in #GSocketProtocol if you
940 * know the protocol number used for it.
942 * Returns: a #GSocket or %NULL on error.
943 * Free the returned object with g_object_unref().
948 g_socket_new (GSocketFamily family,
950 GSocketProtocol protocol,
953 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
957 "protocol", protocol,
962 * g_socket_new_from_fd:
963 * @fd: a native socket file descriptor.
964 * @error: #GError for error reporting, or %NULL to ignore.
966 * Creates a new #GSocket from a native file descriptor
967 * or winsock SOCKET handle.
969 * This reads all the settings from the file descriptor so that
970 * all properties should work. Note that the file descriptor
971 * will be set to non-blocking mode, independent on the blocking
972 * mode of the #GSocket.
974 * Returns: a #GSocket or %NULL on error.
975 * Free the returned object with g_object_unref().
980 g_socket_new_from_fd (gint fd,
983 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
990 * g_socket_set_blocking:
991 * @socket: a #GSocket.
992 * @blocking: Whether to use blocking I/O or not.
994 * Sets the blocking mode of the socket. In blocking mode
995 * all operations block until they succeed or there is an error. In
996 * non-blocking mode all functions return results immediately or
997 * with a %G_IO_ERROR_WOULD_BLOCK error.
999 * All sockets are created in blocking mode. However, note that the
1000 * platform level socket is always non-blocking, and blocking mode
1001 * is a GSocket level feature.
1006 g_socket_set_blocking (GSocket *socket,
1009 g_return_if_fail (G_IS_SOCKET (socket));
1011 blocking = !!blocking;
1013 if (socket->priv->blocking == blocking)
1016 socket->priv->blocking = blocking;
1017 g_object_notify (G_OBJECT (socket), "blocking");
1021 * g_socket_get_blocking:
1022 * @socket: a #GSocket.
1024 * Gets the blocking mode of the socket. For details on blocking I/O,
1025 * see g_socket_set_blocking().
1027 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1032 g_socket_get_blocking (GSocket *socket)
1034 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1036 return socket->priv->blocking;
1040 * g_socket_set_keepalive:
1041 * @socket: a #GSocket.
1042 * @keepalive: Value for the keepalive flag
1044 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1045 * this flag is set on a socket, the system will attempt to verify that the
1046 * remote socket endpoint is still present if a sufficiently long period of
1047 * time passes with no data being exchanged. If the system is unable to
1048 * verify the presence of the remote endpoint, it will automatically close
1051 * This option is only functional on certain kinds of sockets. (Notably,
1052 * %G_SOCKET_PROTOCOL_TCP sockets.)
1054 * The exact time between pings is system- and protocol-dependent, but will
1055 * normally be at least two hours. Most commonly, you would set this flag
1056 * on a server socket if you want to allow clients to remain idle for long
1057 * periods of time, but also want to ensure that connections are eventually
1058 * garbage-collected if clients crash or become unreachable.
1063 g_socket_set_keepalive (GSocket *socket,
1068 g_return_if_fail (G_IS_SOCKET (socket));
1070 keepalive = !!keepalive;
1071 if (socket->priv->keepalive == keepalive)
1074 value = (gint) keepalive;
1075 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1076 (gpointer) &value, sizeof (value)) < 0)
1078 int errsv = get_socket_errno ();
1079 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1083 socket->priv->keepalive = keepalive;
1084 g_object_notify (G_OBJECT (socket), "keepalive");
1088 * g_socket_get_keepalive:
1089 * @socket: a #GSocket.
1091 * Gets the keepalive mode of the socket. For details on this,
1092 * see g_socket_set_keepalive().
1094 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1099 g_socket_get_keepalive (GSocket *socket)
1101 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1103 return socket->priv->keepalive;
1107 * g_socket_get_listen_backlog:
1108 * @socket: a #GSocket.
1110 * Gets the listen backlog setting of the socket. For details on this,
1111 * see g_socket_set_listen_backlog().
1113 * Returns: the maximum number of pending connections.
1118 g_socket_get_listen_backlog (GSocket *socket)
1120 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1122 return socket->priv->listen_backlog;
1126 * g_socket_set_listen_backlog:
1127 * @socket: a #GSocket.
1128 * @backlog: the maximum number of pending connections.
1130 * Sets the maximum number of outstanding connections allowed
1131 * when listening on this socket. If more clients than this are
1132 * connecting to the socket and the application is not handling them
1133 * on time then the new connections will be refused.
1135 * Note that this must be called before g_socket_listen() and has no
1136 * effect if called after that.
1141 g_socket_set_listen_backlog (GSocket *socket,
1144 g_return_if_fail (G_IS_SOCKET (socket));
1145 g_return_if_fail (!socket->priv->listening);
1147 if (backlog != socket->priv->listen_backlog)
1149 socket->priv->listen_backlog = backlog;
1150 g_object_notify (G_OBJECT (socket), "listen-backlog");
1155 * g_socket_get_timeout:
1156 * @socket: a #GSocket.
1158 * Gets the timeout setting of the socket. For details on this, see
1159 * g_socket_set_timeout().
1161 * Returns: the timeout in seconds
1166 g_socket_get_timeout (GSocket *socket)
1168 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1170 return socket->priv->timeout;
1174 * g_socket_set_timeout:
1175 * @socket: a #GSocket.
1176 * @timeout: the timeout for @socket, in seconds, or 0 for none
1178 * Sets the time in seconds after which I/O operations on @socket will
1179 * time out if they have not yet completed.
1181 * On a blocking socket, this means that any blocking #GSocket
1182 * operation will time out after @timeout seconds of inactivity,
1183 * returning %G_IO_ERROR_TIMED_OUT.
1185 * On a non-blocking socket, calls to g_socket_condition_wait() will
1186 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1187 * created with g_socket_create_source() will trigger after
1188 * @timeout seconds of inactivity, with the requested condition
1189 * set, at which point calling g_socket_receive(), g_socket_send(),
1190 * g_socket_check_connect_result(), etc, will fail with
1191 * %G_IO_ERROR_TIMED_OUT.
1193 * If @timeout is 0 (the default), operations will never time out
1196 * Note that if an I/O operation is interrupted by a signal, this may
1197 * cause the timeout to be reset.
1202 g_socket_set_timeout (GSocket *socket,
1205 g_return_if_fail (G_IS_SOCKET (socket));
1207 if (timeout != socket->priv->timeout)
1209 socket->priv->timeout = timeout;
1210 g_object_notify (G_OBJECT (socket), "timeout");
1215 * g_socket_get_multicast_loopback:
1216 * @socket: a #GSocket.
1218 * Gets the multicast loopback setting on @socket; if %TRUE (the
1219 * default), outgoing multicast packets will be looped back to
1220 * multicast listeners on the same host.
1222 * Returns: the multicast loopback setting on @socket
1227 g_socket_get_multicast_loopback (GSocket *socket)
1230 guint value = 0, optlen;
1232 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1234 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1236 optlen = sizeof (guchar);
1237 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1240 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1242 optlen = sizeof (guint);
1243 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1247 g_return_val_if_reached (FALSE);
1251 int errsv = get_socket_errno ();
1252 g_warning ("error getting multicast loopback: %s", socket_strerror (errsv));
1260 * g_socket_set_multicast_loopback:
1261 * @socket: a #GSocket.
1262 * @loopback: whether @socket should receive messages sent to its
1263 * multicast groups from the local host
1265 * Sets whether outgoing multicast packets will be received by sockets
1266 * listening on that multicast address on the same host. This is %TRUE
1272 g_socket_set_multicast_loopback (GSocket *socket,
1277 g_return_if_fail (G_IS_SOCKET (socket));
1279 loopback = !!loopback;
1281 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1283 guchar value = (guchar)loopback;
1285 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1286 &value, sizeof (value));
1288 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1290 guint value = (guint)loopback;
1292 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1293 &value, sizeof (value));
1296 g_return_if_reached ();
1300 int errsv = get_socket_errno ();
1301 g_warning ("error setting multicast loopback: %s", socket_strerror (errsv));
1305 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1309 * g_socket_get_multicast_ttl:
1310 * @socket: a #GSocket.
1312 * Gets the multicast time-to-live setting on @socket; see
1313 * g_socket_set_multicast_ttl() for more details.
1315 * Returns: the multicast time-to-live setting on @socket
1320 g_socket_get_multicast_ttl (GSocket *socket)
1323 guint value, optlen;
1325 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1327 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1331 optlen = sizeof (optval);
1332 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1336 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1338 optlen = sizeof (value);
1339 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1343 g_return_val_if_reached (FALSE);
1347 int errsv = get_socket_errno ();
1348 g_warning ("error getting multicast ttl: %s", socket_strerror (errsv));
1356 * g_socket_set_multicast_ttl:
1357 * @socket: a #GSocket.
1358 * @ttl: the time-to-live value for all multicast datagrams on @socket
1360 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1361 * By default, this is 1, meaning that multicast packets will not leave
1362 * the local network.
1367 g_socket_set_multicast_ttl (GSocket *socket,
1372 g_return_if_fail (G_IS_SOCKET (socket));
1374 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1376 guchar optval = (guchar)ttl;
1378 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1379 &optval, sizeof (optval));
1381 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1383 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1384 &ttl, sizeof (ttl));
1387 g_return_if_reached ();
1391 int errsv = get_socket_errno ();
1392 g_warning ("error setting multicast ttl: %s", socket_strerror (errsv));
1396 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1400 * g_socket_get_family:
1401 * @socket: a #GSocket.
1403 * Gets the socket family of the socket.
1405 * Returns: a #GSocketFamily
1410 g_socket_get_family (GSocket *socket)
1412 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1414 return socket->priv->family;
1418 * g_socket_get_socket_type:
1419 * @socket: a #GSocket.
1421 * Gets the socket type of the socket.
1423 * Returns: a #GSocketType
1428 g_socket_get_socket_type (GSocket *socket)
1430 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1432 return socket->priv->type;
1436 * g_socket_get_protocol:
1437 * @socket: a #GSocket.
1439 * Gets the socket protocol id the socket was created with.
1440 * In case the protocol is unknown, -1 is returned.
1442 * Returns: a protocol id, or -1 if unknown
1447 g_socket_get_protocol (GSocket *socket)
1449 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1451 return socket->priv->protocol;
1456 * @socket: a #GSocket.
1458 * Returns the underlying OS socket object. On unix this
1459 * is a socket file descriptor, and on windows this is
1460 * a Winsock2 SOCKET handle. This may be useful for
1461 * doing platform specific or otherwise unusual operations
1464 * Returns: the file descriptor of the socket.
1469 g_socket_get_fd (GSocket *socket)
1471 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1473 return socket->priv->fd;
1477 * g_socket_get_local_address:
1478 * @socket: a #GSocket.
1479 * @error: #GError for error reporting, or %NULL to ignore.
1481 * Try to get the local address of a bound socket. This is only
1482 * useful if the socket has been bound to a local address,
1483 * either explicitly or implicitly when connecting.
1485 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1486 * Free the returned object with g_object_unref().
1491 g_socket_get_local_address (GSocket *socket,
1494 struct sockaddr_storage buffer;
1495 guint32 len = sizeof (buffer);
1497 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1499 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1501 int errsv = get_socket_errno ();
1502 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1503 _("could not get local address: %s"), socket_strerror (errsv));
1507 return g_socket_address_new_from_native (&buffer, len);
1511 * g_socket_get_remote_address:
1512 * @socket: a #GSocket.
1513 * @error: #GError for error reporting, or %NULL to ignore.
1515 * Try to get the remove address of a connected socket. This is only
1516 * useful for connection oriented sockets that have been connected.
1518 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1519 * Free the returned object with g_object_unref().
1524 g_socket_get_remote_address (GSocket *socket,
1527 struct sockaddr_storage buffer;
1528 guint32 len = sizeof (buffer);
1530 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1532 if (socket->priv->connect_pending)
1534 if (!g_socket_check_connect_result (socket, error))
1537 socket->priv->connect_pending = FALSE;
1540 if (!socket->priv->remote_address)
1542 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1544 int errsv = get_socket_errno ();
1545 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1546 _("could not get remote address: %s"), socket_strerror (errsv));
1550 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1553 return g_object_ref (socket->priv->remote_address);
1557 * g_socket_is_connected:
1558 * @socket: a #GSocket.
1560 * Check whether the socket is connected. This is only useful for
1561 * connection-oriented sockets.
1563 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1568 g_socket_is_connected (GSocket *socket)
1570 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1572 return socket->priv->connected;
1577 * @socket: a #GSocket.
1578 * @error: #GError for error reporting, or %NULL to ignore.
1580 * Marks the socket as a server socket, i.e. a socket that is used
1581 * to accept incoming requests using g_socket_accept().
1583 * Before calling this the socket must be bound to a local address using
1586 * To set the maximum amount of outstanding clients, use
1587 * g_socket_set_listen_backlog().
1589 * Returns: %TRUE on success, %FALSE on error.
1594 g_socket_listen (GSocket *socket,
1597 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1599 if (!check_socket (socket, error))
1602 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1604 int errsv = get_socket_errno ();
1606 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1607 _("could not listen: %s"), socket_strerror (errsv));
1611 socket->priv->listening = TRUE;
1618 * @socket: a #GSocket.
1619 * @address: a #GSocketAddress specifying the local address.
1620 * @allow_reuse: whether to allow reusing this address
1621 * @error: #GError for error reporting, or %NULL to ignore.
1623 * When a socket is created it is attached to an address family, but it
1624 * doesn't have an address in this family. g_socket_bind() assigns the
1625 * address (sometimes called name) of the socket.
1627 * It is generally required to bind to a local address before you can
1628 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1629 * In certain situations, you may also want to bind a socket that will be
1630 * used to initiate connections, though this is not normally required.
1632 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1633 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1634 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1635 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1636 * that address was previously used by another socket that has not yet been
1637 * fully cleaned-up by the kernel. Failing to set this flag on a server
1638 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1639 * the server program is stopped and then immediately restarted.)
1641 * Returns: %TRUE on success, %FALSE on error.
1646 g_socket_bind (GSocket *socket,
1647 GSocketAddress *address,
1648 gboolean reuse_address,
1651 struct sockaddr_storage addr;
1653 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1655 if (!check_socket (socket, error))
1658 /* SO_REUSEADDR on windows means something else and is not what we want.
1659 It always allows the unix variant of SO_REUSEADDR anyway */
1664 value = (int) !!reuse_address;
1665 /* Ignore errors here, the only likely error is "not supported", and
1666 this is a "best effort" thing mainly */
1667 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1668 (gpointer) &value, sizeof (value));
1672 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1675 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1676 g_socket_address_get_native_size (address)) < 0)
1678 int errsv = get_socket_errno ();
1680 G_IO_ERROR, socket_io_error_from_errno (errsv),
1681 _("Error binding to address: %s"), socket_strerror (errsv));
1689 g_socket_multicast_group_operation (GSocket *socket,
1690 GInetAddress *group,
1691 gboolean join_group,
1694 const guint8 *native_addr;
1695 gint optname, result;
1697 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1698 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
1699 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
1700 g_return_val_if_fail (g_inet_address_get_family (group) == socket->priv->family, FALSE);
1702 if (!check_socket (socket, error))
1705 native_addr = g_inet_address_to_bytes (group);
1706 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1708 struct ip_mreq mc_req;
1710 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
1711 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
1713 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
1714 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
1715 &mc_req, sizeof (mc_req));
1717 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1719 struct ipv6_mreq mc_req_ipv6;
1721 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
1722 mc_req_ipv6.ipv6mr_interface = 0;
1724 optname = join_group ? IPV6_ADD_MEMBERSHIP : IPV6_DROP_MEMBERSHIP;
1725 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
1726 &mc_req_ipv6, sizeof (mc_req_ipv6));
1729 g_return_val_if_reached (FALSE);
1733 int errsv = get_socket_errno ();
1735 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1737 _("Error joining multicast group: %s") :
1738 _("Error leaving multicast group: %s"),
1739 socket_strerror (errsv));
1747 * g_socket_join_multicast_group:
1748 * @socket: a #GSocket.
1749 * @group: a #GInetAddress specifying the group address to join.
1750 * @error: #GError for error reporting, or %NULL to ignore.
1752 * Registers @socket to receive multicast messages sent to @group.
1753 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
1754 * been bound to an appropriate interface and port with
1757 * Returns: %TRUE on success, %FALSE on error.
1762 g_socket_join_multicast_group (GSocket *socket,
1763 GInetAddress *group,
1766 return g_socket_multicast_group_operation (socket, group, TRUE, error);
1770 * g_socket_leave_multicast_group:
1771 * @socket: a #GSocket.
1772 * @group: a #GInetAddress specifying the group address to leave.
1773 * @error: #GError for error reporting, or %NULL to ignore.
1775 * Removes @socket from the multicast group @group (while still
1776 * allowing it to receive unicast messages).
1778 * Returns: %TRUE on success, %FALSE on error.
1783 g_socket_leave_multicast_group (GSocket *socket,
1784 GInetAddress *group,
1787 return g_socket_multicast_group_operation (socket, group, FALSE, error);
1791 * g_socket_speaks_ipv4:
1792 * @socket: a #GSocket
1794 * Checks if a socket is capable of speaking IPv4.
1796 * IPv4 sockets are capable of speaking IPv4. On some operating systems
1797 * and under some combinations of circumstances IPv6 sockets are also
1798 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
1801 * No other types of sockets are currently considered as being capable
1804 * Returns: %TRUE if this socket can be used with IPv4.
1809 g_socket_speaks_ipv4 (GSocket *socket)
1811 switch (socket->priv->family)
1813 case G_SOCKET_FAMILY_IPV4:
1816 case G_SOCKET_FAMILY_IPV6:
1817 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1819 guint sizeof_int = sizeof (int);
1822 if (getsockopt (socket->priv->fd,
1823 IPPROTO_IPV6, IPV6_V6ONLY,
1824 &v6_only, &sizeof_int) != 0)
1840 * @socket: a #GSocket.
1841 * @cancellable: (allow-none): a %GCancellable or %NULL
1842 * @error: #GError for error reporting, or %NULL to ignore.
1844 * Accept incoming connections on a connection-based socket. This removes
1845 * the first outstanding connection request from the listening socket and
1846 * creates a #GSocket object for it.
1848 * The @socket must be bound to a local address with g_socket_bind() and
1849 * must be listening for incoming connections (g_socket_listen()).
1851 * If there are no outstanding connections then the operation will block
1852 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1853 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1855 * Returns: (transfer full): a new #GSocket, or %NULL on error.
1856 * Free the returned object with g_object_unref().
1861 g_socket_accept (GSocket *socket,
1862 GCancellable *cancellable,
1865 GSocket *new_socket;
1868 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1870 if (!check_socket (socket, error))
1875 if (socket->priv->blocking &&
1876 !g_socket_condition_wait (socket,
1877 G_IO_IN, cancellable, error))
1880 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1882 int errsv = get_socket_errno ();
1884 win32_unset_event_mask (socket, FD_ACCEPT);
1889 if (socket->priv->blocking)
1891 #ifdef WSAEWOULDBLOCK
1892 if (errsv == WSAEWOULDBLOCK)
1895 if (errsv == EWOULDBLOCK ||
1901 g_set_error (error, G_IO_ERROR,
1902 socket_io_error_from_errno (errsv),
1903 _("Error accepting connection: %s"), socket_strerror (errsv));
1909 win32_unset_event_mask (socket, FD_ACCEPT);
1913 /* The socket inherits the accepting sockets event mask and even object,
1914 we need to remove that */
1915 WSAEventSelect (ret, NULL, 0);
1921 /* We always want to set close-on-exec to protect users. If you
1922 need to so some weird inheritance to exec you can re-enable this
1923 using lower level hacks with g_socket_get_fd(). */
1924 flags = fcntl (ret, F_GETFD, 0);
1926 (flags & FD_CLOEXEC) == 0)
1928 flags |= FD_CLOEXEC;
1929 fcntl (ret, F_SETFD, flags);
1934 new_socket = g_socket_new_from_fd (ret, error);
1935 if (new_socket == NULL)
1944 new_socket->priv->protocol = socket->priv->protocol;
1951 * @socket: a #GSocket.
1952 * @address: a #GSocketAddress specifying the remote address.
1953 * @cancellable: (allow-none): a %GCancellable or %NULL
1954 * @error: #GError for error reporting, or %NULL to ignore.
1956 * Connect the socket to the specified remote address.
1958 * For connection oriented socket this generally means we attempt to make
1959 * a connection to the @address. For a connection-less socket it sets
1960 * the default address for g_socket_send() and discards all incoming datagrams
1961 * from other sources.
1963 * Generally connection oriented sockets can only connect once, but
1964 * connection-less sockets can connect multiple times to change the
1967 * If the connect call needs to do network I/O it will block, unless
1968 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1969 * and the user can be notified of the connection finishing by waiting
1970 * for the G_IO_OUT condition. The result of the connection must then be
1971 * checked with g_socket_check_connect_result().
1973 * Returns: %TRUE if connected, %FALSE on error.
1978 g_socket_connect (GSocket *socket,
1979 GSocketAddress *address,
1980 GCancellable *cancellable,
1983 struct sockaddr_storage buffer;
1985 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1987 if (!check_socket (socket, error))
1990 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1993 if (socket->priv->remote_address)
1994 g_object_unref (socket->priv->remote_address);
1995 socket->priv->remote_address = g_object_ref (address);
1999 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2000 g_socket_address_get_native_size (address)) < 0)
2002 int errsv = get_socket_errno ();
2008 if (errsv == EINPROGRESS)
2010 if (errsv == WSAEWOULDBLOCK)
2013 if (socket->priv->blocking)
2015 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2017 if (g_socket_check_connect_result (socket, error))
2023 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2024 _("Connection in progress"));
2025 socket->priv->connect_pending = TRUE;
2029 g_set_error_literal (error, G_IO_ERROR,
2030 socket_io_error_from_errno (errsv),
2031 socket_strerror (errsv));
2038 win32_unset_event_mask (socket, FD_CONNECT);
2040 socket->priv->connected = TRUE;
2046 * g_socket_check_connect_result:
2047 * @socket: a #GSocket
2048 * @error: #GError for error reporting, or %NULL to ignore.
2050 * Checks and resets the pending connect error for the socket.
2051 * This is used to check for errors when g_socket_connect() is
2052 * used in non-blocking mode.
2054 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2059 g_socket_check_connect_result (GSocket *socket,
2065 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2067 if (!check_socket (socket, error))
2070 optlen = sizeof (value);
2071 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
2073 int errsv = get_socket_errno ();
2075 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2076 _("Unable to get pending error: %s"), socket_strerror (errsv));
2082 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2083 socket_strerror (value));
2084 if (socket->priv->remote_address)
2086 g_object_unref (socket->priv->remote_address);
2087 socket->priv->remote_address = NULL;
2092 socket->priv->connected = TRUE;
2098 * @socket: a #GSocket
2099 * @buffer: a buffer to read data into (which should be at least @size
2101 * @size: the number of bytes you want to read from the socket
2102 * @cancellable: (allow-none): a %GCancellable or %NULL
2103 * @error: #GError for error reporting, or %NULL to ignore.
2105 * Receive data (up to @size bytes) from a socket. This is mainly used by
2106 * connection-oriented sockets; it is identical to g_socket_receive_from()
2107 * with @address set to %NULL.
2109 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2110 * g_socket_receive() will always read either 0 or 1 complete messages from
2111 * the socket. If the received message is too large to fit in @buffer, then
2112 * the data beyond @size bytes will be discarded, without any explicit
2113 * indication that this has occurred.
2115 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2116 * number of bytes, up to @size. If more than @size bytes have been
2117 * received, the additional data will be returned in future calls to
2118 * g_socket_receive().
2120 * If the socket is in blocking mode the call will block until there
2121 * is some data to receive, the connection is closed, or there is an
2122 * error. If there is no data available and the socket is in
2123 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2124 * returned. To be notified when data is available, wait for the
2125 * %G_IO_IN condition.
2127 * On error -1 is returned and @error is set accordingly.
2129 * Returns: Number of bytes read, or 0 if the connection was closed by
2130 * the peer, or -1 on error
2135 g_socket_receive (GSocket *socket,
2138 GCancellable *cancellable,
2141 return g_socket_receive_with_blocking (socket, buffer, size,
2142 socket->priv->blocking,
2143 cancellable, error);
2147 * g_socket_receive_with_blocking:
2148 * @socket: a #GSocket
2149 * @buffer: a buffer to read data into (which should be at least @size
2151 * @size: the number of bytes you want to read from the socket
2152 * @blocking: whether to do blocking or non-blocking I/O
2153 * @cancellable: (allow-none): a %GCancellable or %NULL
2154 * @error: #GError for error reporting, or %NULL to ignore.
2156 * This behaves exactly the same as g_socket_receive(), except that
2157 * the choice of blocking or non-blocking behavior is determined by
2158 * the @blocking argument rather than by @socket's properties.
2160 * Returns: Number of bytes read, or 0 if the connection was closed by
2161 * the peer, or -1 on error
2166 g_socket_receive_with_blocking (GSocket *socket,
2170 GCancellable *cancellable,
2175 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2177 if (!check_socket (socket, error))
2180 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2186 !g_socket_condition_wait (socket,
2187 G_IO_IN, cancellable, error))
2190 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2192 int errsv = get_socket_errno ();
2199 #ifdef WSAEWOULDBLOCK
2200 if (errsv == WSAEWOULDBLOCK)
2203 if (errsv == EWOULDBLOCK ||
2209 win32_unset_event_mask (socket, FD_READ);
2211 g_set_error (error, G_IO_ERROR,
2212 socket_io_error_from_errno (errsv),
2213 _("Error receiving data: %s"), socket_strerror (errsv));
2217 win32_unset_event_mask (socket, FD_READ);
2226 * g_socket_receive_from:
2227 * @socket: a #GSocket
2228 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2230 * @buffer: (array length=size) (element-type guint8): a buffer to
2231 * read data into (which should be at least @size bytes long).
2232 * @size: the number of bytes you want to read from the socket
2233 * @cancellable: (allow-none): a %GCancellable or %NULL
2234 * @error: #GError for error reporting, or %NULL to ignore.
2236 * Receive data (up to @size bytes) from a socket.
2238 * If @address is non-%NULL then @address will be set equal to the
2239 * source address of the received packet.
2240 * @address is owned by the caller.
2242 * See g_socket_receive() for additional information.
2244 * Returns: Number of bytes read, or 0 if the connection was closed by
2245 * the peer, or -1 on error
2250 g_socket_receive_from (GSocket *socket,
2251 GSocketAddress **address,
2254 GCancellable *cancellable,
2262 return g_socket_receive_message (socket,
2270 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2271 * one, which can be confusing and annoying. So if possible, we want
2272 * to suppress the signal entirely.
2275 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2277 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2282 * @socket: a #GSocket
2283 * @buffer: (array length=size) (element-type guint8): the buffer
2284 * containing the data to send.
2285 * @size: the number of bytes to send
2286 * @cancellable: (allow-none): a %GCancellable or %NULL
2287 * @error: #GError for error reporting, or %NULL to ignore.
2289 * Tries to send @size bytes from @buffer on the socket. This is
2290 * mainly used by connection-oriented sockets; it is identical to
2291 * g_socket_send_to() with @address set to %NULL.
2293 * If the socket is in blocking mode the call will block until there is
2294 * space for the data in the socket queue. If there is no space available
2295 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2296 * will be returned. To be notified when space is available, wait for the
2297 * %G_IO_OUT condition. Note though that you may still receive
2298 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2299 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2300 * very common due to the way the underlying APIs work.)
2302 * On error -1 is returned and @error is set accordingly.
2304 * Returns: Number of bytes written (which may be less than @size), or -1
2310 g_socket_send (GSocket *socket,
2311 const gchar *buffer,
2313 GCancellable *cancellable,
2316 return g_socket_send_with_blocking (socket, buffer, size,
2317 socket->priv->blocking,
2318 cancellable, error);
2322 * g_socket_send_with_blocking:
2323 * @socket: a #GSocket
2324 * @buffer: (array length=size) (element-type guint8): the buffer
2325 * containing the data to send.
2326 * @size: the number of bytes to send
2327 * @blocking: whether to do blocking or non-blocking I/O
2328 * @cancellable: (allow-none): a %GCancellable or %NULL
2329 * @error: #GError for error reporting, or %NULL to ignore.
2331 * This behaves exactly the same as g_socket_send(), except that
2332 * the choice of blocking or non-blocking behavior is determined by
2333 * the @blocking argument rather than by @socket's properties.
2335 * Returns: Number of bytes written (which may be less than @size), or -1
2341 g_socket_send_with_blocking (GSocket *socket,
2342 const gchar *buffer,
2345 GCancellable *cancellable,
2350 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2352 if (!check_socket (socket, error))
2355 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2361 !g_socket_condition_wait (socket,
2362 G_IO_OUT, cancellable, error))
2365 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2367 int errsv = get_socket_errno ();
2372 #ifdef WSAEWOULDBLOCK
2373 if (errsv == WSAEWOULDBLOCK)
2374 win32_unset_event_mask (socket, FD_WRITE);
2379 #ifdef WSAEWOULDBLOCK
2380 if (errsv == WSAEWOULDBLOCK)
2383 if (errsv == EWOULDBLOCK ||
2389 g_set_error (error, G_IO_ERROR,
2390 socket_io_error_from_errno (errsv),
2391 _("Error sending data: %s"), socket_strerror (errsv));
2402 * @socket: a #GSocket
2403 * @address: a #GSocketAddress, or %NULL
2404 * @buffer: (array length=size) (element-type guint8): the buffer
2405 * containing the data to send.
2406 * @size: the number of bytes to send
2407 * @cancellable: (allow-none): a %GCancellable or %NULL
2408 * @error: #GError for error reporting, or %NULL to ignore.
2410 * Tries to send @size bytes from @buffer to @address. If @address is
2411 * %NULL then the message is sent to the default receiver (set by
2412 * g_socket_connect()).
2414 * See g_socket_send() for additional information.
2416 * Returns: Number of bytes written (which may be less than @size), or -1
2422 g_socket_send_to (GSocket *socket,
2423 GSocketAddress *address,
2424 const gchar *buffer,
2426 GCancellable *cancellable,
2434 return g_socket_send_message (socket,
2444 * g_socket_shutdown:
2445 * @socket: a #GSocket
2446 * @shutdown_read: whether to shut down the read side
2447 * @shutdown_write: whether to shut down the write side
2448 * @error: #GError for error reporting, or %NULL to ignore.
2450 * Shut down part of a full-duplex connection.
2452 * If @shutdown_read is %TRUE then the receiving side of the connection
2453 * is shut down, and further reading is disallowed.
2455 * If @shutdown_write is %TRUE then the sending side of the connection
2456 * is shut down, and further writing is disallowed.
2458 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2460 * One example where this is used is graceful disconnect for TCP connections
2461 * where you close the sending side, then wait for the other side to close
2462 * the connection, thus ensuring that the other side saw all sent data.
2464 * Returns: %TRUE on success, %FALSE on error
2469 g_socket_shutdown (GSocket *socket,
2470 gboolean shutdown_read,
2471 gboolean shutdown_write,
2476 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2478 if (!check_socket (socket, error))
2482 if (!shutdown_read && !shutdown_write)
2486 if (shutdown_read && shutdown_write)
2488 else if (shutdown_read)
2493 if (shutdown_read && shutdown_write)
2495 else if (shutdown_read)
2501 if (shutdown (socket->priv->fd, how) != 0)
2503 int errsv = get_socket_errno ();
2504 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2505 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2509 if (shutdown_read && shutdown_write)
2510 socket->priv->connected = FALSE;
2517 * @socket: a #GSocket
2518 * @error: #GError for error reporting, or %NULL to ignore.
2520 * Closes the socket, shutting down any active connection.
2522 * Closing a socket does not wait for all outstanding I/O operations
2523 * to finish, so the caller should not rely on them to be guaranteed
2524 * to complete even if the close returns with no error.
2526 * Once the socket is closed, all other operations will return
2527 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2530 * Sockets will be automatically closed when the last reference
2531 * is dropped, but you might want to call this function to make sure
2532 * resources are released as early as possible.
2534 * Beware that due to the way that TCP works, it is possible for
2535 * recently-sent data to be lost if either you close a socket while the
2536 * %G_IO_IN condition is set, or else if the remote connection tries to
2537 * send something to you after you close the socket but before it has
2538 * finished reading all of the data you sent. There is no easy generic
2539 * way to avoid this problem; the easiest fix is to design the network
2540 * protocol such that the client will never send data "out of turn".
2541 * Another solution is for the server to half-close the connection by
2542 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2543 * and then wait for the client to notice this and close its side of the
2544 * connection, after which the server can safely call g_socket_close().
2545 * (This is what #GTcpConnection does if you call
2546 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2547 * only works if the client will close its connection after the server
2550 * Returns: %TRUE on success, %FALSE on error
2555 g_socket_close (GSocket *socket,
2560 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2562 if (socket->priv->closed)
2563 return TRUE; /* Multiple close not an error */
2565 if (!check_socket (socket, error))
2571 res = closesocket (socket->priv->fd);
2573 res = close (socket->priv->fd);
2577 int errsv = get_socket_errno ();
2582 g_set_error (error, G_IO_ERROR,
2583 socket_io_error_from_errno (errsv),
2584 _("Error closing socket: %s"),
2585 socket_strerror (errsv));
2591 socket->priv->connected = FALSE;
2592 socket->priv->closed = TRUE;
2593 if (socket->priv->remote_address)
2595 g_object_unref (socket->priv->remote_address);
2596 socket->priv->remote_address = NULL;
2603 * g_socket_is_closed:
2604 * @socket: a #GSocket
2606 * Checks whether a socket is closed.
2608 * Returns: %TRUE if socket is closed, %FALSE otherwise
2613 g_socket_is_closed (GSocket *socket)
2615 return socket->priv->closed;
2619 /* Broken source, used on errors */
2621 broken_prepare (GSource *source,
2628 broken_check (GSource *source)
2634 broken_dispatch (GSource *source,
2635 GSourceFunc callback,
2641 static GSourceFuncs broken_funcs =
2650 network_events_for_condition (GIOCondition condition)
2654 if (condition & G_IO_IN)
2655 event_mask |= (FD_READ | FD_ACCEPT);
2656 if (condition & G_IO_OUT)
2657 event_mask |= (FD_WRITE | FD_CONNECT);
2658 event_mask |= FD_CLOSE;
2664 ensure_event (GSocket *socket)
2666 if (socket->priv->event == WSA_INVALID_EVENT)
2667 socket->priv->event = WSACreateEvent();
2671 update_select_events (GSocket *socket)
2678 ensure_event (socket);
2681 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2684 event_mask |= network_events_for_condition (*ptr);
2687 if (event_mask != socket->priv->selected_events)
2689 /* If no events selected, disable event so we can unset
2692 if (event_mask == 0)
2695 event = socket->priv->event;
2697 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2698 socket->priv->selected_events = event_mask;
2703 add_condition_watch (GSocket *socket,
2704 GIOCondition *condition)
2706 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2708 socket->priv->requested_conditions =
2709 g_list_prepend (socket->priv->requested_conditions, condition);
2711 update_select_events (socket);
2715 remove_condition_watch (GSocket *socket,
2716 GIOCondition *condition)
2718 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2720 socket->priv->requested_conditions =
2721 g_list_remove (socket->priv->requested_conditions, condition);
2723 update_select_events (socket);
2727 update_condition (GSocket *socket)
2729 WSANETWORKEVENTS events;
2730 GIOCondition condition;
2732 if (WSAEnumNetworkEvents (socket->priv->fd,
2733 socket->priv->event,
2736 socket->priv->current_events |= events.lNetworkEvents;
2737 if (events.lNetworkEvents & FD_WRITE &&
2738 events.iErrorCode[FD_WRITE_BIT] != 0)
2739 socket->priv->current_errors |= FD_WRITE;
2740 if (events.lNetworkEvents & FD_CONNECT &&
2741 events.iErrorCode[FD_CONNECT_BIT] != 0)
2742 socket->priv->current_errors |= FD_CONNECT;
2746 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2747 condition |= G_IO_IN;
2749 if (socket->priv->current_events & FD_CLOSE ||
2750 socket->priv->closed)
2751 condition |= G_IO_HUP;
2753 /* Never report both G_IO_OUT and HUP, these are
2754 mutually exclusive (can't write to a closed socket) */
2755 if ((condition & G_IO_HUP) == 0 &&
2756 socket->priv->current_events & FD_WRITE)
2758 if (socket->priv->current_errors & FD_WRITE)
2759 condition |= G_IO_ERR;
2761 condition |= G_IO_OUT;
2765 if (socket->priv->current_events & FD_CONNECT)
2767 if (socket->priv->current_errors & FD_CONNECT)
2768 condition |= (G_IO_HUP | G_IO_ERR);
2770 condition |= G_IO_OUT;
2782 GIOCondition condition;
2783 GCancellable *cancellable;
2784 GPollFD cancel_pollfd;
2785 gint64 timeout_time;
2789 socket_source_prepare (GSource *source,
2792 GSocketSource *socket_source = (GSocketSource *)source;
2794 if (g_cancellable_is_cancelled (socket_source->cancellable))
2797 if (socket_source->timeout_time)
2801 now = g_source_get_time (source);
2802 /* Round up to ensure that we don't try again too early */
2803 *timeout = (socket_source->timeout_time - now + 999) / 1000;
2806 socket_source->socket->priv->timed_out = TRUE;
2815 socket_source->pollfd.revents = update_condition (socket_source->socket);
2818 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2825 socket_source_check (GSource *source)
2829 return socket_source_prepare (source, &timeout);
2833 socket_source_dispatch (GSource *source,
2834 GSourceFunc callback,
2837 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2838 GSocketSource *socket_source = (GSocketSource *)source;
2841 socket_source->pollfd.revents = update_condition (socket_source->socket);
2843 if (socket_source->socket->priv->timed_out)
2844 socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
2846 return (*func) (socket_source->socket,
2847 socket_source->pollfd.revents & socket_source->condition,
2852 socket_source_finalize (GSource *source)
2854 GSocketSource *socket_source = (GSocketSource *)source;
2857 socket = socket_source->socket;
2860 remove_condition_watch (socket, &socket_source->condition);
2863 g_object_unref (socket);
2865 if (socket_source->cancellable)
2867 g_cancellable_release_fd (socket_source->cancellable);
2868 g_object_unref (socket_source->cancellable);
2873 socket_source_closure_callback (GSocket *socket,
2874 GIOCondition condition,
2877 GClosure *closure = data;
2879 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
2880 GValue result_value = G_VALUE_INIT;
2883 g_value_init (&result_value, G_TYPE_BOOLEAN);
2885 g_value_init (¶ms[0], G_TYPE_SOCKET);
2886 g_value_set_object (¶ms[0], socket);
2887 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
2888 g_value_set_flags (¶ms[1], condition);
2890 g_closure_invoke (closure, &result_value, 2, params, NULL);
2892 result = g_value_get_boolean (&result_value);
2893 g_value_unset (&result_value);
2894 g_value_unset (¶ms[0]);
2895 g_value_unset (¶ms[1]);
2900 static GSourceFuncs socket_source_funcs =
2902 socket_source_prepare,
2903 socket_source_check,
2904 socket_source_dispatch,
2905 socket_source_finalize,
2906 (GSourceFunc)socket_source_closure_callback,
2907 (GSourceDummyMarshal)g_cclosure_marshal_generic,
2911 socket_source_new (GSocket *socket,
2912 GIOCondition condition,
2913 GCancellable *cancellable)
2916 GSocketSource *socket_source;
2919 ensure_event (socket);
2921 if (socket->priv->event == WSA_INVALID_EVENT)
2923 g_warning ("Failed to create WSAEvent");
2924 return g_source_new (&broken_funcs, sizeof (GSource));
2928 condition |= G_IO_HUP | G_IO_ERR;
2930 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2931 g_source_set_name (source, "GSocket");
2932 socket_source = (GSocketSource *)source;
2934 socket_source->socket = g_object_ref (socket);
2935 socket_source->condition = condition;
2937 if (g_cancellable_make_pollfd (cancellable,
2938 &socket_source->cancel_pollfd))
2940 socket_source->cancellable = g_object_ref (cancellable);
2941 g_source_add_poll (source, &socket_source->cancel_pollfd);
2945 add_condition_watch (socket, &socket_source->condition);
2946 socket_source->pollfd.fd = (gintptr) socket->priv->event;
2948 socket_source->pollfd.fd = socket->priv->fd;
2951 socket_source->pollfd.events = condition;
2952 socket_source->pollfd.revents = 0;
2953 g_source_add_poll (source, &socket_source->pollfd);
2955 if (socket->priv->timeout)
2956 socket_source->timeout_time = g_get_monotonic_time () +
2957 socket->priv->timeout * 1000000;
2960 socket_source->timeout_time = 0;
2966 * g_socket_create_source: (skip)
2967 * @socket: a #GSocket
2968 * @condition: a #GIOCondition mask to monitor
2969 * @cancellable: (allow-none): a %GCancellable or %NULL
2971 * Creates a %GSource that can be attached to a %GMainContext to monitor
2972 * for the availibility of the specified @condition on the socket.
2974 * The callback on the source is of the #GSocketSourceFunc type.
2976 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2977 * these conditions will always be reported output if they are true.
2979 * @cancellable if not %NULL can be used to cancel the source, which will
2980 * cause the source to trigger, reporting the current condition (which
2981 * is likely 0 unless cancellation happened at the same time as a
2982 * condition change). You can check for this in the callback using
2983 * g_cancellable_is_cancelled().
2985 * If @socket has a timeout set, and it is reached before @condition
2986 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2987 * %G_IO_OUT depending on @condition. However, @socket will have been
2988 * marked as having had a timeout, and so the next #GSocket I/O method
2989 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2991 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
2996 g_socket_create_source (GSocket *socket,
2997 GIOCondition condition,
2998 GCancellable *cancellable)
3000 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3002 return socket_source_new (socket, condition, cancellable);
3006 * g_socket_condition_check:
3007 * @socket: a #GSocket
3008 * @condition: a #GIOCondition mask to check
3010 * Checks on the readiness of @socket to perform operations.
3011 * The operations specified in @condition are checked for and masked
3012 * against the currently-satisfied conditions on @socket. The result
3015 * Note that on Windows, it is possible for an operation to return
3016 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3017 * g_socket_condition_check() has claimed that the socket is ready for
3018 * writing. Rather than calling g_socket_condition_check() and then
3019 * writing to the socket if it succeeds, it is generally better to
3020 * simply try writing to the socket right away, and try again later if
3021 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3023 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3024 * these conditions will always be set in the output if they are true.
3026 * This call never blocks.
3028 * Returns: the @GIOCondition mask of the current state
3033 g_socket_condition_check (GSocket *socket,
3034 GIOCondition condition)
3036 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3038 if (!check_socket (socket, NULL))
3043 GIOCondition current_condition;
3045 condition |= G_IO_ERR | G_IO_HUP;
3047 add_condition_watch (socket, &condition);
3048 current_condition = update_condition (socket);
3049 remove_condition_watch (socket, &condition);
3050 return condition & current_condition;
3056 poll_fd.fd = socket->priv->fd;
3057 poll_fd.events = condition;
3060 result = g_poll (&poll_fd, 1, 0);
3061 while (result == -1 && get_socket_errno () == EINTR);
3063 return poll_fd.revents;
3069 * g_socket_condition_wait:
3070 * @socket: a #GSocket
3071 * @condition: a #GIOCondition mask to wait for
3072 * @cancellable: (allow-none): a #GCancellable, or %NULL
3073 * @error: a #GError pointer, or %NULL
3075 * Waits for @condition to become true on @socket. When the condition
3076 * is met, %TRUE is returned.
3078 * If @cancellable is cancelled before the condition is met, or if the
3079 * socket has a timeout set and it is reached before the condition is
3080 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3081 * the appropriate value (%G_IO_ERROR_CANCELLED or
3082 * %G_IO_ERROR_TIMED_OUT).
3084 * Returns: %TRUE if the condition was met, %FALSE otherwise
3089 g_socket_condition_wait (GSocket *socket,
3090 GIOCondition condition,
3091 GCancellable *cancellable,
3094 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3096 if (!check_socket (socket, error))
3099 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3104 GIOCondition current_condition;
3110 /* Always check these */
3111 condition |= G_IO_ERR | G_IO_HUP;
3113 add_condition_watch (socket, &condition);
3116 events[num_events++] = socket->priv->event;
3118 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3119 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3121 if (socket->priv->timeout)
3122 timeout = socket->priv->timeout * 1000;
3124 timeout = WSA_INFINITE;
3126 current_condition = update_condition (socket);
3127 while ((condition & current_condition) == 0)
3129 res = WSAWaitForMultipleEvents(num_events, events,
3130 FALSE, timeout, FALSE);
3131 if (res == WSA_WAIT_FAILED)
3133 int errsv = get_socket_errno ();
3135 g_set_error (error, G_IO_ERROR,
3136 socket_io_error_from_errno (errsv),
3137 _("Waiting for socket condition: %s"),
3138 socket_strerror (errsv));
3141 else if (res == WSA_WAIT_TIMEOUT)
3143 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3144 _("Socket I/O timed out"));
3148 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3151 current_condition = update_condition (socket);
3153 remove_condition_watch (socket, &condition);
3155 g_cancellable_release_fd (cancellable);
3157 return (condition & current_condition) != 0;
3166 poll_fd[0].fd = socket->priv->fd;
3167 poll_fd[0].events = condition;
3170 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3173 if (socket->priv->timeout)
3174 timeout = socket->priv->timeout * 1000;
3179 result = g_poll (poll_fd, num, timeout);
3180 while (result == -1 && get_socket_errno () == EINTR);
3183 g_cancellable_release_fd (cancellable);
3187 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3188 _("Socket I/O timed out"));
3192 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3198 * g_socket_send_message:
3199 * @socket: a #GSocket
3200 * @address: a #GSocketAddress, or %NULL
3201 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3202 * @num_vectors: the number of elements in @vectors, or -1
3203 * @messages: (array length=num_messages) (allow-none): a pointer to an
3204 * array of #GSocketControlMessages, or %NULL.
3205 * @num_messages: number of elements in @messages, or -1.
3206 * @flags: an int containing #GSocketMsgFlags flags
3207 * @cancellable: (allow-none): a %GCancellable or %NULL
3208 * @error: #GError for error reporting, or %NULL to ignore.
3210 * Send data to @address on @socket. This is the most complicated and
3211 * fully-featured version of this call. For easier use, see
3212 * g_socket_send() and g_socket_send_to().
3214 * If @address is %NULL then the message is sent to the default receiver
3215 * (set by g_socket_connect()).
3217 * @vectors must point to an array of #GOutputVector structs and
3218 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3219 * then @vectors is assumed to be terminated by a #GOutputVector with a
3220 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3221 * that the sent data will be gathered from. Using multiple
3222 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3223 * data from multiple sources into a single buffer, and more
3224 * network-efficient than making multiple calls to g_socket_send().
3226 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3227 * #GSocketControlMessage instances. These correspond to the control
3228 * messages to be sent on the socket.
3229 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3232 * @flags modify how the message is sent. The commonly available arguments
3233 * for this are available in the #GSocketMsgFlags enum, but the
3234 * values there are the same as the system values, and the flags
3235 * are passed in as-is, so you can pass in system-specific flags too.
3237 * If the socket is in blocking mode the call will block until there is
3238 * space for the data in the socket queue. If there is no space available
3239 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3240 * will be returned. To be notified when space is available, wait for the
3241 * %G_IO_OUT condition. Note though that you may still receive
3242 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3243 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3244 * very common due to the way the underlying APIs work.)
3246 * On error -1 is returned and @error is set accordingly.
3248 * Returns: Number of bytes written (which may be less than @size), or -1
3254 g_socket_send_message (GSocket *socket,
3255 GSocketAddress *address,
3256 GOutputVector *vectors,
3258 GSocketControlMessage **messages,
3261 GCancellable *cancellable,
3264 GOutputVector one_vector;
3267 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3269 if (!check_socket (socket, error))
3272 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3275 if (num_vectors == -1)
3277 for (num_vectors = 0;
3278 vectors[num_vectors].buffer != NULL;
3283 if (num_messages == -1)
3285 for (num_messages = 0;
3286 messages != NULL && messages[num_messages] != NULL;
3291 if (num_vectors == 0)
3295 one_vector.buffer = &zero;
3296 one_vector.size = 1;
3298 vectors = &one_vector;
3311 msg.msg_namelen = g_socket_address_get_native_size (address);
3312 msg.msg_name = g_alloca (msg.msg_namelen);
3313 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3318 msg.msg_name = NULL;
3319 msg.msg_namelen = 0;
3324 /* this entire expression will be evaluated at compile time */
3325 if (sizeof *msg.msg_iov == sizeof *vectors &&
3326 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3327 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3328 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3329 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3330 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3331 G_STRUCT_OFFSET (GOutputVector, size))
3332 /* ABI is compatible */
3334 msg.msg_iov = (struct iovec *) vectors;
3335 msg.msg_iovlen = num_vectors;
3338 /* ABI is incompatible */
3342 msg.msg_iov = g_newa (struct iovec, num_vectors);
3343 for (i = 0; i < num_vectors; i++)
3345 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3346 msg.msg_iov[i].iov_len = vectors[i].size;
3348 msg.msg_iovlen = num_vectors;
3354 struct cmsghdr *cmsg;
3357 msg.msg_controllen = 0;
3358 for (i = 0; i < num_messages; i++)
3359 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3361 if (msg.msg_controllen == 0)
3362 msg.msg_control = NULL;
3365 msg.msg_control = g_alloca (msg.msg_controllen);
3366 memset (msg.msg_control, '\0', msg.msg_controllen);
3369 cmsg = CMSG_FIRSTHDR (&msg);
3370 for (i = 0; i < num_messages; i++)
3372 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3373 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3374 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3375 g_socket_control_message_serialize (messages[i],
3377 cmsg = CMSG_NXTHDR (&msg, cmsg);
3379 g_assert (cmsg == NULL);
3384 if (socket->priv->blocking &&
3385 !g_socket_condition_wait (socket,
3386 G_IO_OUT, cancellable, error))
3389 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3392 int errsv = get_socket_errno ();
3397 if (socket->priv->blocking &&
3398 (errsv == EWOULDBLOCK ||
3402 g_set_error (error, G_IO_ERROR,
3403 socket_io_error_from_errno (errsv),
3404 _("Error sending message: %s"), socket_strerror (errsv));
3415 struct sockaddr_storage addr;
3422 /* Win32 doesn't support control messages.
3423 Actually this is possible for raw and datagram sockets
3424 via WSASendMessage on Vista or later, but that doesn't
3426 if (num_messages != 0)
3428 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3429 _("GSocketControlMessage not supported on windows"));
3434 bufs = g_newa (WSABUF, num_vectors);
3435 for (i = 0; i < num_vectors; i++)
3437 bufs[i].buf = (char *)vectors[i].buffer;
3438 bufs[i].len = (gulong)vectors[i].size;
3442 addrlen = 0; /* Avoid warning */
3445 addrlen = g_socket_address_get_native_size (address);
3446 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3452 if (socket->priv->blocking &&
3453 !g_socket_condition_wait (socket,
3454 G_IO_OUT, cancellable, error))
3458 result = WSASendTo (socket->priv->fd,
3461 (const struct sockaddr *)&addr, addrlen,
3464 result = WSASend (socket->priv->fd,
3471 int errsv = get_socket_errno ();
3473 if (errsv == WSAEINTR)
3476 if (errsv == WSAEWOULDBLOCK)
3477 win32_unset_event_mask (socket, FD_WRITE);
3479 if (socket->priv->blocking &&
3480 errsv == WSAEWOULDBLOCK)
3483 g_set_error (error, G_IO_ERROR,
3484 socket_io_error_from_errno (errsv),
3485 _("Error sending message: %s"), socket_strerror (errsv));
3498 * g_socket_receive_message:
3499 * @socket: a #GSocket
3500 * @address: (out) (allow-none): a pointer to a #GSocketAddress
3502 * @vectors: (array length=num_vectors): an array of #GInputVector structs
3503 * @num_vectors: the number of elements in @vectors, or -1
3504 * @messages: (array length=num_messages) (allow-none): a pointer which
3505 * may be filled with an array of #GSocketControlMessages, or %NULL
3506 * @num_messages: a pointer which will be filled with the number of
3507 * elements in @messages, or %NULL
3508 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3509 * @cancellable: (allow-none): a %GCancellable or %NULL
3510 * @error: a #GError pointer, or %NULL
3512 * Receive data from a socket. This is the most complicated and
3513 * fully-featured version of this call. For easier use, see
3514 * g_socket_receive() and g_socket_receive_from().
3516 * If @address is non-%NULL then @address will be set equal to the
3517 * source address of the received packet.
3518 * @address is owned by the caller.
3520 * @vector must point to an array of #GInputVector structs and
3521 * @num_vectors must be the length of this array. These structs
3522 * describe the buffers that received data will be scattered into.
3523 * If @num_vectors is -1, then @vectors is assumed to be terminated
3524 * by a #GInputVector with a %NULL buffer pointer.
3526 * As a special case, if @num_vectors is 0 (in which case, @vectors
3527 * may of course be %NULL), then a single byte is received and
3528 * discarded. This is to facilitate the common practice of sending a
3529 * single '\0' byte for the purposes of transferring ancillary data.
3531 * @messages, if non-%NULL, will be set to point to a newly-allocated
3532 * array of #GSocketControlMessage instances or %NULL if no such
3533 * messages was received. These correspond to the control messages
3534 * received from the kernel, one #GSocketControlMessage per message
3535 * from the kernel. This array is %NULL-terminated and must be freed
3536 * by the caller using g_free() after calling g_object_unref() on each
3537 * element. If @messages is %NULL, any control messages received will
3540 * @num_messages, if non-%NULL, will be set to the number of control
3541 * messages received.
3543 * If both @messages and @num_messages are non-%NULL, then
3544 * @num_messages gives the number of #GSocketControlMessage instances
3545 * in @messages (ie: not including the %NULL terminator).
3547 * @flags is an in/out parameter. The commonly available arguments
3548 * for this are available in the #GSocketMsgFlags enum, but the
3549 * values there are the same as the system values, and the flags
3550 * are passed in as-is, so you can pass in system-specific flags too
3551 * (and g_socket_receive_message() may pass system-specific flags out).
3553 * As with g_socket_receive(), data may be discarded if @socket is
3554 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3555 * provide enough buffer space to read a complete message. You can pass
3556 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3557 * removing it from the receive queue, but there is no portable way to find
3558 * out the length of the message other than by reading it into a
3559 * sufficiently-large buffer.
3561 * If the socket is in blocking mode the call will block until there
3562 * is some data to receive, the connection is closed, or there is an
3563 * error. If there is no data available and the socket is in
3564 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3565 * returned. To be notified when data is available, wait for the
3566 * %G_IO_IN condition.
3568 * On error -1 is returned and @error is set accordingly.
3570 * Returns: Number of bytes read, or 0 if the connection was closed by
3571 * the peer, or -1 on error
3576 g_socket_receive_message (GSocket *socket,
3577 GSocketAddress **address,
3578 GInputVector *vectors,
3580 GSocketControlMessage ***messages,
3583 GCancellable *cancellable,
3586 GInputVector one_vector;
3589 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3591 if (!check_socket (socket, error))
3594 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3597 if (num_vectors == -1)
3599 for (num_vectors = 0;
3600 vectors[num_vectors].buffer != NULL;
3605 if (num_vectors == 0)
3607 one_vector.buffer = &one_byte;
3608 one_vector.size = 1;
3610 vectors = &one_vector;
3617 struct sockaddr_storage one_sockaddr;
3622 msg.msg_name = &one_sockaddr;
3623 msg.msg_namelen = sizeof (struct sockaddr_storage);
3627 msg.msg_name = NULL;
3628 msg.msg_namelen = 0;
3632 /* this entire expression will be evaluated at compile time */
3633 if (sizeof *msg.msg_iov == sizeof *vectors &&
3634 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3635 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3636 G_STRUCT_OFFSET (GInputVector, buffer) &&
3637 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3638 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3639 G_STRUCT_OFFSET (GInputVector, size))
3640 /* ABI is compatible */
3642 msg.msg_iov = (struct iovec *) vectors;
3643 msg.msg_iovlen = num_vectors;
3646 /* ABI is incompatible */
3650 msg.msg_iov = g_newa (struct iovec, num_vectors);
3651 for (i = 0; i < num_vectors; i++)
3653 msg.msg_iov[i].iov_base = vectors[i].buffer;
3654 msg.msg_iov[i].iov_len = vectors[i].size;
3656 msg.msg_iovlen = num_vectors;
3660 msg.msg_control = g_alloca (2048);
3661 msg.msg_controllen = 2048;
3665 msg.msg_flags = *flags;
3669 /* We always set the close-on-exec flag so we don't leak file
3670 * descriptors into child processes. Note that gunixfdmessage.c
3671 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
3673 #ifdef MSG_CMSG_CLOEXEC
3674 msg.msg_flags |= MSG_CMSG_CLOEXEC;
3680 if (socket->priv->blocking &&
3681 !g_socket_condition_wait (socket,
3682 G_IO_IN, cancellable, error))
3685 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3686 #ifdef MSG_CMSG_CLOEXEC
3687 if (result < 0 && get_socket_errno () == EINVAL)
3689 /* We must be running on an old kernel. Call without the flag. */
3690 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
3691 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3697 int errsv = get_socket_errno ();
3702 if (socket->priv->blocking &&
3703 (errsv == EWOULDBLOCK ||
3707 g_set_error (error, G_IO_ERROR,
3708 socket_io_error_from_errno (errsv),
3709 _("Error receiving message: %s"), socket_strerror (errsv));
3716 /* decode address */
3717 if (address != NULL)
3719 if (msg.msg_namelen > 0)
3720 *address = g_socket_address_new_from_native (msg.msg_name,
3726 /* decode control messages */
3728 GPtrArray *my_messages = NULL;
3729 struct cmsghdr *cmsg;
3731 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3733 GSocketControlMessage *message;
3735 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3737 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3739 if (message == NULL)
3740 /* We've already spewed about the problem in the
3741 deserialization code, so just continue */
3744 if (messages == NULL)
3746 /* we have to do it this way if the user ignores the
3747 * messages so that we will close any received fds.
3749 g_object_unref (message);
3753 if (my_messages == NULL)
3754 my_messages = g_ptr_array_new ();
3755 g_ptr_array_add (my_messages, message);
3760 *num_messages = my_messages != NULL ? my_messages->len : 0;
3764 if (my_messages == NULL)
3770 g_ptr_array_add (my_messages, NULL);
3771 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3776 g_assert (my_messages == NULL);
3780 /* capture the flags */
3782 *flags = msg.msg_flags;
3788 struct sockaddr_storage addr;
3790 DWORD bytes_received;
3797 bufs = g_newa (WSABUF, num_vectors);
3798 for (i = 0; i < num_vectors; i++)
3800 bufs[i].buf = (char *)vectors[i].buffer;
3801 bufs[i].len = (gulong)vectors[i].size;
3813 if (socket->priv->blocking &&
3814 !g_socket_condition_wait (socket,
3815 G_IO_IN, cancellable, error))
3818 addrlen = sizeof addr;
3820 result = WSARecvFrom (socket->priv->fd,
3822 &bytes_received, &win_flags,
3823 (struct sockaddr *)&addr, &addrlen,
3826 result = WSARecv (socket->priv->fd,
3828 &bytes_received, &win_flags,
3832 int errsv = get_socket_errno ();
3834 if (errsv == WSAEINTR)
3837 win32_unset_event_mask (socket, FD_READ);
3839 if (socket->priv->blocking &&
3840 errsv == WSAEWOULDBLOCK)
3843 g_set_error (error, G_IO_ERROR,
3844 socket_io_error_from_errno (errsv),
3845 _("Error receiving message: %s"), socket_strerror (errsv));
3849 win32_unset_event_mask (socket, FD_READ);
3853 /* decode address */
3854 if (address != NULL)
3857 *address = g_socket_address_new_from_native (&addr, addrlen);
3862 /* capture the flags */
3866 if (messages != NULL)
3868 if (num_messages != NULL)
3871 return bytes_received;
3877 * g_socket_get_credentials:
3878 * @socket: a #GSocket.
3879 * @error: #GError for error reporting, or %NULL to ignore.
3881 * Returns the credentials of the foreign process connected to this
3882 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
3885 * If this operation isn't supported on the OS, the method fails with
3886 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
3887 * by reading the %SO_PEERCRED option on the underlying socket.
3889 * Other ways to obtain credentials from a foreign peer includes the
3890 * #GUnixCredentialsMessage type and
3891 * g_unix_connection_send_credentials() /
3892 * g_unix_connection_receive_credentials() functions.
3894 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
3895 * that must be freed with g_object_unref().
3900 g_socket_get_credentials (GSocket *socket,
3905 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
3906 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3910 #if defined(__linux__) || defined(__OpenBSD__)
3913 #if defined(__linux__)
3914 struct ucred native_creds;
3915 optlen = sizeof (struct ucred);
3916 #elif defined(__OpenBSD__)
3917 struct sockpeercred native_creds;
3918 optlen = sizeof (struct sockpeercred);
3920 if (getsockopt (socket->priv->fd,
3923 (void *)&native_creds,
3926 int errsv = get_socket_errno ();
3929 socket_io_error_from_errno (errsv),
3930 _("Unable to get pending error: %s"),
3931 socket_strerror (errsv));
3935 ret = g_credentials_new ();
3936 g_credentials_set_native (ret,
3937 #if defined(__linux__)
3938 G_CREDENTIALS_TYPE_LINUX_UCRED,
3939 #elif defined(__OpenBSD__)
3940 G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
3946 g_set_error_literal (error,
3948 G_IO_ERROR_NOT_SUPPORTED,
3949 _("g_socket_get_credentials not implemented for this OS"));