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"
52 #include "gcancellable.h"
53 #include "gioenumtypes.h"
54 #include "ginetaddress.h"
55 #include "ginitable.h"
59 #include "gnetworkingprivate.h"
60 #include "gsocketaddress.h"
61 #include "gsocketcontrolmessage.h"
62 #include "gcredentials.h"
67 * @short_description: Low-level socket object
69 * @see_also: #GInitable
71 * A #GSocket is a low-level networking primitive. It is a more or less
72 * direct mapping of the BSD socket API in a portable GObject based API.
73 * It supports both the UNIX socket implementations and winsock2 on Windows.
75 * #GSocket is the platform independent base upon which the higher level
76 * network primitives are based. Applications are not typically meant to
77 * use it directly, but rather through classes like #GSocketClient,
78 * #GSocketService and #GSocketConnection. However there may be cases where
79 * direct use of #GSocket is useful.
81 * #GSocket implements the #GInitable interface, so if it is manually constructed
82 * by e.g. g_object_new() you must call g_initable_init() and check the
83 * results before using the object. This is done automatically in
84 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
87 * Sockets operate in two general modes, blocking or non-blocking. When
88 * in blocking mode all operations block until the requested operation
89 * is finished or there is an error. In non-blocking mode all calls that
90 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
91 * To know when a call would successfully run you can call g_socket_condition_check(),
92 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
93 * attach it to a #GMainContext to get callbacks when I/O is possible.
94 * Note that all sockets are always set to non blocking mode in the system, and
95 * blocking mode is emulated in GSocket.
97 * When working in non-blocking mode applications should always be able to
98 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
99 * function said that I/O was possible. This can easily happen in case
100 * of a race condition in the application, but it can also happen for other
101 * reasons. For instance, on Windows a socket is always seen as writable
102 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
104 * #GSocket<!-- -->s can be either connection oriented or datagram based.
105 * For connection oriented types you must first establish a connection by
106 * either connecting to an address or accepting a connection from another
107 * address. For connectionless socket types the target/source address is
108 * specified or received in each I/O operation.
110 * All socket file descriptors are set to be close-on-exec.
112 * Note that creating a #GSocket causes the signal %SIGPIPE to be
113 * ignored for the remainder of the program. If you are writing a
114 * command-line utility that uses #GSocket, you may need to take into
115 * account the fact that your program will not automatically be killed
116 * if it tries to write to %stdout after it has been closed.
121 static void g_socket_initable_iface_init (GInitableIface *iface);
122 static gboolean g_socket_initable_init (GInitable *initable,
123 GCancellable *cancellable,
126 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
127 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
128 g_socket_initable_iface_init));
143 PROP_MULTICAST_LOOPBACK,
147 struct _GSocketPrivate
149 GSocketFamily family;
151 GSocketProtocol protocol;
155 GError *construct_error;
156 GSocketAddress *remote_address;
164 guint connect_pending : 1;
170 GList *requested_conditions; /* list of requested GIOCondition * */
175 get_socket_errno (void)
180 return WSAGetLastError ();
185 socket_io_error_from_errno (int err)
188 return g_io_error_from_errno (err);
193 return G_IO_ERROR_ADDRESS_IN_USE;
195 return G_IO_ERROR_WOULD_BLOCK;
197 return G_IO_ERROR_PERMISSION_DENIED;
198 case WSA_INVALID_HANDLE:
199 case WSA_INVALID_PARAMETER:
202 return G_IO_ERROR_INVALID_ARGUMENT;
203 case WSAEPROTONOSUPPORT:
204 return G_IO_ERROR_NOT_SUPPORTED;
206 return G_IO_ERROR_CANCELLED;
207 case WSAESOCKTNOSUPPORT:
209 case WSAEPFNOSUPPORT:
210 case WSAEAFNOSUPPORT:
211 return G_IO_ERROR_NOT_SUPPORTED;
213 return G_IO_ERROR_FAILED;
219 socket_strerror (int err)
222 return g_strerror (err);
227 msg = g_win32_error_message (err);
229 msg_ret = g_intern_string (msg);
237 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
239 _win32_unset_event_mask (GSocket *socket, int mask)
241 socket->priv->current_events &= ~mask;
242 socket->priv->current_errors &= ~mask;
245 #define win32_unset_event_mask(_socket, _mask)
249 set_fd_nonblocking (int fd)
252 GError *error = NULL;
258 if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
260 g_warning ("Error setting socket nonblocking: %s", error->message);
261 g_clear_error (&error);
266 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
268 int errsv = get_socket_errno ();
269 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
275 check_socket (GSocket *socket,
278 if (!socket->priv->inited)
280 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
281 _("Invalid socket, not initialized"));
285 if (socket->priv->construct_error)
287 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
288 _("Invalid socket, initialization failed due to: %s"),
289 socket->priv->construct_error->message);
293 if (socket->priv->closed)
295 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
296 _("Socket is already closed"));
300 if (socket->priv->timed_out)
302 socket->priv->timed_out = FALSE;
303 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
304 _("Socket I/O timed out"));
312 g_socket_details_from_fd (GSocket *socket)
314 struct sockaddr_storage address;
321 /* See bug #611756 */
322 BOOL bool_val = FALSE;
327 fd = socket->priv->fd;
328 optlen = sizeof value;
329 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
331 errsv = get_socket_errno ();
342 /* programmer error */
343 g_error ("creating GSocket from fd %d: %s\n",
344 fd, socket_strerror (errsv));
352 g_assert (optlen == sizeof value);
356 socket->priv->type = G_SOCKET_TYPE_STREAM;
360 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
364 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
368 socket->priv->type = G_SOCKET_TYPE_INVALID;
372 addrlen = sizeof address;
373 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
375 errsv = get_socket_errno ();
381 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
382 sizeof address.ss_family <= addrlen);
383 family = address.ss_family;
387 /* On Solaris, this happens if the socket is not yet connected.
388 * But we can use SO_DOMAIN as a workaround there.
391 optlen = sizeof family;
392 if (getsockopt (fd, SOL_SOCKET, SO_DOMAIN, (void *)&family, &optlen) != 0)
394 errsv = get_socket_errno ();
398 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
406 case G_SOCKET_FAMILY_IPV4:
407 case G_SOCKET_FAMILY_IPV6:
408 socket->priv->family = address.ss_family;
409 switch (socket->priv->type)
411 case G_SOCKET_TYPE_STREAM:
412 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
415 case G_SOCKET_TYPE_DATAGRAM:
416 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
419 case G_SOCKET_TYPE_SEQPACKET:
420 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
428 case G_SOCKET_FAMILY_UNIX:
429 socket->priv->family = G_SOCKET_FAMILY_UNIX;
430 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
434 socket->priv->family = G_SOCKET_FAMILY_INVALID;
438 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
440 addrlen = sizeof address;
441 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
442 socket->priv->connected = TRUE;
445 optlen = sizeof bool_val;
446 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
447 (void *)&bool_val, &optlen) == 0)
450 /* Experimentation indicates that the SO_KEEPALIVE value is
451 * actually a char on Windows, even if documentation claims it
452 * to be a BOOL which is a typedef for int. So this g_assert()
453 * fails. See bug #611756.
455 g_assert (optlen == sizeof bool_val);
457 socket->priv->keepalive = !!bool_val;
461 /* Can't read, maybe not supported, assume FALSE */
462 socket->priv->keepalive = FALSE;
468 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
469 socket_io_error_from_errno (errsv),
470 _("creating GSocket from fd: %s"),
471 socket_strerror (errsv));
475 g_socket_create_socket (GSocketFamily family,
485 case G_SOCKET_TYPE_STREAM:
486 native_type = SOCK_STREAM;
489 case G_SOCKET_TYPE_DATAGRAM:
490 native_type = SOCK_DGRAM;
493 case G_SOCKET_TYPE_SEQPACKET:
494 native_type = SOCK_SEQPACKET;
498 g_assert_not_reached ();
503 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
504 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
509 fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
510 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
511 if (fd < 0 && errno == EINVAL)
513 fd = socket (family, native_type, protocol);
517 int errsv = get_socket_errno ();
519 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
520 _("Unable to create socket: %s"), socket_strerror (errsv));
527 /* We always want to set close-on-exec to protect users. If you
528 need to so some weird inheritance to exec you can re-enable this
529 using lower level hacks with g_socket_get_fd(). */
530 flags = fcntl (fd, F_GETFD, 0);
532 (flags & FD_CLOEXEC) == 0)
535 fcntl (fd, F_SETFD, flags);
544 g_socket_constructed (GObject *object)
546 GSocket *socket = G_SOCKET (object);
548 if (socket->priv->fd >= 0)
549 /* create socket->priv info from the fd */
550 g_socket_details_from_fd (socket);
553 /* create the fd from socket->priv info */
554 socket->priv->fd = g_socket_create_socket (socket->priv->family,
556 socket->priv->protocol,
557 &socket->priv->construct_error);
559 /* Always use native nonblocking sockets, as
560 windows sets sockets to nonblocking automatically
561 in certain operations. This way we make things work
562 the same on all platforms */
563 if (socket->priv->fd != -1)
564 set_fd_nonblocking (socket->priv->fd);
568 g_socket_get_property (GObject *object,
573 GSocket *socket = G_SOCKET (object);
574 GSocketAddress *address;
579 g_value_set_enum (value, socket->priv->family);
583 g_value_set_enum (value, socket->priv->type);
587 g_value_set_enum (value, socket->priv->protocol);
591 g_value_set_int (value, socket->priv->fd);
595 g_value_set_boolean (value, socket->priv->blocking);
598 case PROP_LISTEN_BACKLOG:
599 g_value_set_int (value, socket->priv->listen_backlog);
603 g_value_set_boolean (value, socket->priv->keepalive);
606 case PROP_LOCAL_ADDRESS:
607 address = g_socket_get_local_address (socket, NULL);
608 g_value_take_object (value, address);
611 case PROP_REMOTE_ADDRESS:
612 address = g_socket_get_remote_address (socket, NULL);
613 g_value_take_object (value, address);
617 g_value_set_uint (value, socket->priv->timeout);
620 case PROP_MULTICAST_LOOPBACK:
621 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
624 case PROP_MULTICAST_TTL:
625 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
629 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
634 g_socket_set_property (GObject *object,
639 GSocket *socket = G_SOCKET (object);
644 socket->priv->family = g_value_get_enum (value);
648 socket->priv->type = g_value_get_enum (value);
652 socket->priv->protocol = g_value_get_enum (value);
656 socket->priv->fd = g_value_get_int (value);
660 g_socket_set_blocking (socket, g_value_get_boolean (value));
663 case PROP_LISTEN_BACKLOG:
664 g_socket_set_listen_backlog (socket, g_value_get_int (value));
668 g_socket_set_keepalive (socket, g_value_get_boolean (value));
672 g_socket_set_timeout (socket, g_value_get_uint (value));
675 case PROP_MULTICAST_LOOPBACK:
676 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
679 case PROP_MULTICAST_TTL:
680 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
684 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
689 g_socket_finalize (GObject *object)
691 GSocket *socket = G_SOCKET (object);
693 g_clear_error (&socket->priv->construct_error);
695 if (socket->priv->fd != -1 &&
696 !socket->priv->closed)
697 g_socket_close (socket, NULL);
699 if (socket->priv->remote_address)
700 g_object_unref (socket->priv->remote_address);
703 if (socket->priv->event != WSA_INVALID_EVENT)
705 WSACloseEvent (socket->priv->event);
706 socket->priv->event = WSA_INVALID_EVENT;
709 g_assert (socket->priv->requested_conditions == NULL);
712 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
713 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
717 g_socket_class_init (GSocketClass *klass)
719 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
722 /* Make sure winsock has been initialized */
723 type = g_inet_address_get_type ();
724 (type); /* To avoid -Wunused-but-set-variable */
727 /* There is no portable, thread-safe way to avoid having the process
728 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
729 * forced to simply ignore the signal process-wide.
731 signal (SIGPIPE, SIG_IGN);
734 g_type_class_add_private (klass, sizeof (GSocketPrivate));
736 gobject_class->finalize = g_socket_finalize;
737 gobject_class->constructed = g_socket_constructed;
738 gobject_class->set_property = g_socket_set_property;
739 gobject_class->get_property = g_socket_get_property;
741 g_object_class_install_property (gobject_class, PROP_FAMILY,
742 g_param_spec_enum ("family",
744 P_("The sockets address family"),
745 G_TYPE_SOCKET_FAMILY,
746 G_SOCKET_FAMILY_INVALID,
747 G_PARAM_CONSTRUCT_ONLY |
749 G_PARAM_STATIC_STRINGS));
751 g_object_class_install_property (gobject_class, PROP_TYPE,
752 g_param_spec_enum ("type",
754 P_("The sockets type"),
756 G_SOCKET_TYPE_STREAM,
757 G_PARAM_CONSTRUCT_ONLY |
759 G_PARAM_STATIC_STRINGS));
761 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
762 g_param_spec_enum ("protocol",
763 P_("Socket protocol"),
764 P_("The id of the protocol to use, or -1 for unknown"),
765 G_TYPE_SOCKET_PROTOCOL,
766 G_SOCKET_PROTOCOL_UNKNOWN,
767 G_PARAM_CONSTRUCT_ONLY |
769 G_PARAM_STATIC_STRINGS));
771 g_object_class_install_property (gobject_class, PROP_FD,
772 g_param_spec_int ("fd",
773 P_("File descriptor"),
774 P_("The sockets file descriptor"),
778 G_PARAM_CONSTRUCT_ONLY |
780 G_PARAM_STATIC_STRINGS));
782 g_object_class_install_property (gobject_class, PROP_BLOCKING,
783 g_param_spec_boolean ("blocking",
785 P_("Whether or not I/O on this socket is blocking"),
788 G_PARAM_STATIC_STRINGS));
790 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
791 g_param_spec_int ("listen-backlog",
792 P_("Listen backlog"),
793 P_("Outstanding connections in the listen queue"),
798 G_PARAM_STATIC_STRINGS));
800 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
801 g_param_spec_boolean ("keepalive",
802 P_("Keep connection alive"),
803 P_("Keep connection alive by sending periodic pings"),
806 G_PARAM_STATIC_STRINGS));
808 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
809 g_param_spec_object ("local-address",
811 P_("The local address the socket is bound to"),
812 G_TYPE_SOCKET_ADDRESS,
814 G_PARAM_STATIC_STRINGS));
816 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
817 g_param_spec_object ("remote-address",
818 P_("Remote address"),
819 P_("The remote address the socket is connected to"),
820 G_TYPE_SOCKET_ADDRESS,
822 G_PARAM_STATIC_STRINGS));
827 * The timeout in seconds on socket I/O
831 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
832 g_param_spec_uint ("timeout",
834 P_("The timeout in seconds on socket I/O"),
839 G_PARAM_STATIC_STRINGS));
842 * GSocket:multicast-loopback:
844 * Whether outgoing multicast packets loop back to the local host.
848 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
849 g_param_spec_boolean ("multicast-loopback",
850 P_("Multicast loopback"),
851 P_("Whether outgoing multicast packets loop back to the local host"),
854 G_PARAM_STATIC_STRINGS));
857 * GSocket:multicast-ttl:
859 * Time-to-live out outgoing multicast packets
863 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
864 g_param_spec_uint ("multicast-ttl",
866 P_("Time-to-live of outgoing multicast packets"),
869 G_PARAM_STATIC_STRINGS));
873 g_socket_initable_iface_init (GInitableIface *iface)
875 iface->init = g_socket_initable_init;
879 g_socket_init (GSocket *socket)
881 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
883 socket->priv->fd = -1;
884 socket->priv->blocking = TRUE;
885 socket->priv->listen_backlog = 10;
886 socket->priv->construct_error = NULL;
888 socket->priv->event = WSA_INVALID_EVENT;
893 g_socket_initable_init (GInitable *initable,
894 GCancellable *cancellable,
899 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
901 socket = G_SOCKET (initable);
903 if (cancellable != NULL)
905 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
906 _("Cancellable initialization not supported"));
910 socket->priv->inited = TRUE;
912 if (socket->priv->construct_error)
915 *error = g_error_copy (socket->priv->construct_error);
925 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
926 * @type: the socket type to use.
927 * @protocol: the id of the protocol to use, or 0 for default.
928 * @error: #GError for error reporting, or %NULL to ignore.
930 * Creates a new #GSocket with the defined family, type and protocol.
931 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
932 * for the family and type is used.
934 * The @protocol is a family and type specific int that specifies what
935 * kind of protocol to use. #GSocketProtocol lists several common ones.
936 * Many families only support one protocol, and use 0 for this, others
937 * support several and using 0 means to use the default protocol for
938 * the family and type.
940 * The protocol id is passed directly to the operating
941 * system, so you can use protocols not listed in #GSocketProtocol if you
942 * know the protocol number used for it.
944 * Returns: a #GSocket or %NULL on error.
945 * Free the returned object with g_object_unref().
950 g_socket_new (GSocketFamily family,
952 GSocketProtocol protocol,
955 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
959 "protocol", protocol,
964 * g_socket_new_from_fd:
965 * @fd: a native socket file descriptor.
966 * @error: #GError for error reporting, or %NULL to ignore.
968 * Creates a new #GSocket from a native file descriptor
969 * or winsock SOCKET handle.
971 * This reads all the settings from the file descriptor so that
972 * all properties should work. Note that the file descriptor
973 * will be set to non-blocking mode, independent on the blocking
974 * mode of the #GSocket.
976 * Returns: a #GSocket or %NULL on error.
977 * Free the returned object with g_object_unref().
982 g_socket_new_from_fd (gint fd,
985 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
992 * g_socket_set_blocking:
993 * @socket: a #GSocket.
994 * @blocking: Whether to use blocking I/O or not.
996 * Sets the blocking mode of the socket. In blocking mode
997 * all operations block until they succeed or there is an error. In
998 * non-blocking mode all functions return results immediately or
999 * with a %G_IO_ERROR_WOULD_BLOCK error.
1001 * All sockets are created in blocking mode. However, note that the
1002 * platform level socket is always non-blocking, and blocking mode
1003 * is a GSocket level feature.
1008 g_socket_set_blocking (GSocket *socket,
1011 g_return_if_fail (G_IS_SOCKET (socket));
1013 blocking = !!blocking;
1015 if (socket->priv->blocking == blocking)
1018 socket->priv->blocking = blocking;
1019 g_object_notify (G_OBJECT (socket), "blocking");
1023 * g_socket_get_blocking:
1024 * @socket: a #GSocket.
1026 * Gets the blocking mode of the socket. For details on blocking I/O,
1027 * see g_socket_set_blocking().
1029 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1034 g_socket_get_blocking (GSocket *socket)
1036 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1038 return socket->priv->blocking;
1042 * g_socket_set_keepalive:
1043 * @socket: a #GSocket.
1044 * @keepalive: Value for the keepalive flag
1046 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1047 * this flag is set on a socket, the system will attempt to verify that the
1048 * remote socket endpoint is still present if a sufficiently long period of
1049 * time passes with no data being exchanged. If the system is unable to
1050 * verify the presence of the remote endpoint, it will automatically close
1053 * This option is only functional on certain kinds of sockets. (Notably,
1054 * %G_SOCKET_PROTOCOL_TCP sockets.)
1056 * The exact time between pings is system- and protocol-dependent, but will
1057 * normally be at least two hours. Most commonly, you would set this flag
1058 * on a server socket if you want to allow clients to remain idle for long
1059 * periods of time, but also want to ensure that connections are eventually
1060 * garbage-collected if clients crash or become unreachable.
1065 g_socket_set_keepalive (GSocket *socket,
1070 g_return_if_fail (G_IS_SOCKET (socket));
1072 keepalive = !!keepalive;
1073 if (socket->priv->keepalive == keepalive)
1076 value = (gint) keepalive;
1077 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1078 (gpointer) &value, sizeof (value)) < 0)
1080 int errsv = get_socket_errno ();
1081 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1085 socket->priv->keepalive = keepalive;
1086 g_object_notify (G_OBJECT (socket), "keepalive");
1090 * g_socket_get_keepalive:
1091 * @socket: a #GSocket.
1093 * Gets the keepalive mode of the socket. For details on this,
1094 * see g_socket_set_keepalive().
1096 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1101 g_socket_get_keepalive (GSocket *socket)
1103 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1105 return socket->priv->keepalive;
1109 * g_socket_get_listen_backlog:
1110 * @socket: a #GSocket.
1112 * Gets the listen backlog setting of the socket. For details on this,
1113 * see g_socket_set_listen_backlog().
1115 * Returns: the maximum number of pending connections.
1120 g_socket_get_listen_backlog (GSocket *socket)
1122 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1124 return socket->priv->listen_backlog;
1128 * g_socket_set_listen_backlog:
1129 * @socket: a #GSocket.
1130 * @backlog: the maximum number of pending connections.
1132 * Sets the maximum number of outstanding connections allowed
1133 * when listening on this socket. If more clients than this are
1134 * connecting to the socket and the application is not handling them
1135 * on time then the new connections will be refused.
1137 * Note that this must be called before g_socket_listen() and has no
1138 * effect if called after that.
1143 g_socket_set_listen_backlog (GSocket *socket,
1146 g_return_if_fail (G_IS_SOCKET (socket));
1147 g_return_if_fail (!socket->priv->listening);
1149 if (backlog != socket->priv->listen_backlog)
1151 socket->priv->listen_backlog = backlog;
1152 g_object_notify (G_OBJECT (socket), "listen-backlog");
1157 * g_socket_get_timeout:
1158 * @socket: a #GSocket.
1160 * Gets the timeout setting of the socket. For details on this, see
1161 * g_socket_set_timeout().
1163 * Returns: the timeout in seconds
1168 g_socket_get_timeout (GSocket *socket)
1170 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1172 return socket->priv->timeout;
1176 * g_socket_set_timeout:
1177 * @socket: a #GSocket.
1178 * @timeout: the timeout for @socket, in seconds, or 0 for none
1180 * Sets the time in seconds after which I/O operations on @socket will
1181 * time out if they have not yet completed.
1183 * On a blocking socket, this means that any blocking #GSocket
1184 * operation will time out after @timeout seconds of inactivity,
1185 * returning %G_IO_ERROR_TIMED_OUT.
1187 * On a non-blocking socket, calls to g_socket_condition_wait() will
1188 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1189 * created with g_socket_create_source() will trigger after
1190 * @timeout seconds of inactivity, with the requested condition
1191 * set, at which point calling g_socket_receive(), g_socket_send(),
1192 * g_socket_check_connect_result(), etc, will fail with
1193 * %G_IO_ERROR_TIMED_OUT.
1195 * If @timeout is 0 (the default), operations will never time out
1198 * Note that if an I/O operation is interrupted by a signal, this may
1199 * cause the timeout to be reset.
1204 g_socket_set_timeout (GSocket *socket,
1207 g_return_if_fail (G_IS_SOCKET (socket));
1209 if (timeout != socket->priv->timeout)
1211 socket->priv->timeout = timeout;
1212 g_object_notify (G_OBJECT (socket), "timeout");
1217 * g_socket_get_multicast_loopback:
1218 * @socket: a #GSocket.
1220 * Gets the multicast loopback setting on @socket; if %TRUE (the
1221 * default), outgoing multicast packets will be looped back to
1222 * multicast listeners on the same host.
1224 * Returns: the multicast loopback setting on @socket
1229 g_socket_get_multicast_loopback (GSocket *socket)
1232 guint value = 0, optlen;
1234 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1236 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1238 optlen = sizeof (guchar);
1239 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1242 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1244 optlen = sizeof (guint);
1245 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1249 g_return_val_if_reached (FALSE);
1253 int errsv = get_socket_errno ();
1254 g_warning ("error getting multicast loopback: %s", socket_strerror (errsv));
1262 * g_socket_set_multicast_loopback:
1263 * @socket: a #GSocket.
1264 * @loopback: whether @socket should receive messages sent to its
1265 * multicast groups from the local host
1267 * Sets whether outgoing multicast packets will be received by sockets
1268 * listening on that multicast address on the same host. This is %TRUE
1274 g_socket_set_multicast_loopback (GSocket *socket,
1279 g_return_if_fail (G_IS_SOCKET (socket));
1281 loopback = !!loopback;
1283 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1285 guchar value = (guchar)loopback;
1287 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1288 &value, sizeof (value));
1290 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1292 guint value = (guint)loopback;
1294 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1295 &value, sizeof (value));
1298 g_return_if_reached ();
1302 int errsv = get_socket_errno ();
1303 g_warning ("error setting multicast loopback: %s", socket_strerror (errsv));
1307 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1311 * g_socket_get_multicast_ttl:
1312 * @socket: a #GSocket.
1314 * Gets the multicast time-to-live setting on @socket; see
1315 * g_socket_set_multicast_ttl() for more details.
1317 * Returns: the multicast time-to-live setting on @socket
1322 g_socket_get_multicast_ttl (GSocket *socket)
1325 guint value, optlen;
1327 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1329 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1333 optlen = sizeof (optval);
1334 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1338 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1340 optlen = sizeof (value);
1341 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1345 g_return_val_if_reached (FALSE);
1349 int errsv = get_socket_errno ();
1350 g_warning ("error getting multicast ttl: %s", socket_strerror (errsv));
1358 * g_socket_set_multicast_ttl:
1359 * @socket: a #GSocket.
1360 * @ttl: the time-to-live value for all multicast datagrams on @socket
1362 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1363 * By default, this is 1, meaning that multicast packets will not leave
1364 * the local network.
1369 g_socket_set_multicast_ttl (GSocket *socket,
1374 g_return_if_fail (G_IS_SOCKET (socket));
1376 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1378 guchar optval = (guchar)ttl;
1380 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1381 &optval, sizeof (optval));
1383 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1385 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1386 &ttl, sizeof (ttl));
1389 g_return_if_reached ();
1393 int errsv = get_socket_errno ();
1394 g_warning ("error setting multicast ttl: %s", socket_strerror (errsv));
1398 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1402 * g_socket_get_family:
1403 * @socket: a #GSocket.
1405 * Gets the socket family of the socket.
1407 * Returns: a #GSocketFamily
1412 g_socket_get_family (GSocket *socket)
1414 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1416 return socket->priv->family;
1420 * g_socket_get_socket_type:
1421 * @socket: a #GSocket.
1423 * Gets the socket type of the socket.
1425 * Returns: a #GSocketType
1430 g_socket_get_socket_type (GSocket *socket)
1432 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1434 return socket->priv->type;
1438 * g_socket_get_protocol:
1439 * @socket: a #GSocket.
1441 * Gets the socket protocol id the socket was created with.
1442 * In case the protocol is unknown, -1 is returned.
1444 * Returns: a protocol id, or -1 if unknown
1449 g_socket_get_protocol (GSocket *socket)
1451 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1453 return socket->priv->protocol;
1458 * @socket: a #GSocket.
1460 * Returns the underlying OS socket object. On unix this
1461 * is a socket file descriptor, and on windows this is
1462 * a Winsock2 SOCKET handle. This may be useful for
1463 * doing platform specific or otherwise unusual operations
1466 * Returns: the file descriptor of the socket.
1471 g_socket_get_fd (GSocket *socket)
1473 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1475 return socket->priv->fd;
1479 * g_socket_get_local_address:
1480 * @socket: a #GSocket.
1481 * @error: #GError for error reporting, or %NULL to ignore.
1483 * Try to get the local address of a bound socket. This is only
1484 * useful if the socket has been bound to a local address,
1485 * either explicitly or implicitly when connecting.
1487 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1488 * Free the returned object with g_object_unref().
1493 g_socket_get_local_address (GSocket *socket,
1496 struct sockaddr_storage buffer;
1497 guint32 len = sizeof (buffer);
1499 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1501 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1503 int errsv = get_socket_errno ();
1504 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1505 _("could not get local address: %s"), socket_strerror (errsv));
1509 return g_socket_address_new_from_native (&buffer, len);
1513 * g_socket_get_remote_address:
1514 * @socket: a #GSocket.
1515 * @error: #GError for error reporting, or %NULL to ignore.
1517 * Try to get the remove address of a connected socket. This is only
1518 * useful for connection oriented sockets that have been connected.
1520 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1521 * Free the returned object with g_object_unref().
1526 g_socket_get_remote_address (GSocket *socket,
1529 struct sockaddr_storage buffer;
1530 guint32 len = sizeof (buffer);
1532 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1534 if (socket->priv->connect_pending)
1536 if (!g_socket_check_connect_result (socket, error))
1539 socket->priv->connect_pending = FALSE;
1542 if (!socket->priv->remote_address)
1544 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1546 int errsv = get_socket_errno ();
1547 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1548 _("could not get remote address: %s"), socket_strerror (errsv));
1552 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1555 return g_object_ref (socket->priv->remote_address);
1559 * g_socket_is_connected:
1560 * @socket: a #GSocket.
1562 * Check whether the socket is connected. This is only useful for
1563 * connection-oriented sockets.
1565 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1570 g_socket_is_connected (GSocket *socket)
1572 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1574 return socket->priv->connected;
1579 * @socket: a #GSocket.
1580 * @error: #GError for error reporting, or %NULL to ignore.
1582 * Marks the socket as a server socket, i.e. a socket that is used
1583 * to accept incoming requests using g_socket_accept().
1585 * Before calling this the socket must be bound to a local address using
1588 * To set the maximum amount of outstanding clients, use
1589 * g_socket_set_listen_backlog().
1591 * Returns: %TRUE on success, %FALSE on error.
1596 g_socket_listen (GSocket *socket,
1599 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1601 if (!check_socket (socket, error))
1604 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1606 int errsv = get_socket_errno ();
1608 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1609 _("could not listen: %s"), socket_strerror (errsv));
1613 socket->priv->listening = TRUE;
1620 * @socket: a #GSocket.
1621 * @address: a #GSocketAddress specifying the local address.
1622 * @allow_reuse: whether to allow reusing this address
1623 * @error: #GError for error reporting, or %NULL to ignore.
1625 * When a socket is created it is attached to an address family, but it
1626 * doesn't have an address in this family. g_socket_bind() assigns the
1627 * address (sometimes called name) of the socket.
1629 * It is generally required to bind to a local address before you can
1630 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1631 * In certain situations, you may also want to bind a socket that will be
1632 * used to initiate connections, though this is not normally required.
1634 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1635 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1636 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1637 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1638 * that address was previously used by another socket that has not yet been
1639 * fully cleaned-up by the kernel. Failing to set this flag on a server
1640 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1641 * the server program is stopped and then immediately restarted.)
1643 * Returns: %TRUE on success, %FALSE on error.
1648 g_socket_bind (GSocket *socket,
1649 GSocketAddress *address,
1650 gboolean reuse_address,
1653 struct sockaddr_storage addr;
1655 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1657 if (!check_socket (socket, error))
1660 /* SO_REUSEADDR on windows means something else and is not what we want.
1661 It always allows the unix variant of SO_REUSEADDR anyway */
1666 value = (int) !!reuse_address;
1667 /* Ignore errors here, the only likely error is "not supported", and
1668 this is a "best effort" thing mainly */
1669 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1670 (gpointer) &value, sizeof (value));
1674 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1677 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1678 g_socket_address_get_native_size (address)) < 0)
1680 int errsv = get_socket_errno ();
1682 G_IO_ERROR, socket_io_error_from_errno (errsv),
1683 _("Error binding to address: %s"), socket_strerror (errsv));
1691 g_socket_multicast_group_operation (GSocket *socket,
1692 GInetAddress *group,
1693 const gchar *interface,
1694 gboolean join_group,
1697 const guint8 *native_addr;
1698 gint optname, result;
1700 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1701 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
1702 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
1703 g_return_val_if_fail (g_inet_address_get_family (group) == socket->priv->family, FALSE);
1705 if (!check_socket (socket, error))
1708 native_addr = g_inet_address_to_bytes (group);
1709 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1711 #ifdef HAVE_IP_MREQN
1712 struct ip_mreqn mc_req;
1714 struct ip_mreq mc_req;
1717 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
1719 #ifdef HAVE_IP_MREQN
1721 mc_req.imr_ifindex = if_nametoindex (interface);
1723 mc_req.imr_ifindex = 0; /* Pick any. */
1725 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
1728 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
1729 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
1730 &mc_req, sizeof (mc_req));
1732 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1734 struct ipv6_mreq mc_req_ipv6;
1736 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
1738 mc_req_ipv6.ipv6mr_interface = if_nametoindex (interface);
1740 mc_req_ipv6.ipv6mr_interface = 0;
1742 optname = join_group ? IPV6_ADD_MEMBERSHIP : IPV6_DROP_MEMBERSHIP;
1743 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
1744 &mc_req_ipv6, sizeof (mc_req_ipv6));
1747 g_return_val_if_reached (FALSE);
1751 int errsv = get_socket_errno ();
1753 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1755 _("Error joining multicast group: %s") :
1756 _("Error leaving multicast group: %s"),
1757 socket_strerror (errsv));
1765 * g_socket_join_multicast_group:
1766 * @socket: a #GSocket.
1767 * @group: a #GInetAddress specifying the group address to join.
1768 * @interface: Interface to use
1769 * @error: #GError for error reporting, or %NULL to ignore.
1771 * Registers @socket to receive multicast messages sent to @group.
1772 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
1773 * been bound to an appropriate interface and port with
1776 * Returns: %TRUE on success, %FALSE on error.
1781 g_socket_join_multicast_group (GSocket *socket,
1782 GInetAddress *group,
1783 const gchar *interface,
1786 return g_socket_multicast_group_operation (socket, group, interface, TRUE, error);
1790 * g_socket_leave_multicast_group:
1791 * @socket: a #GSocket.
1792 * @group: a #GInetAddress specifying the group address to leave.
1793 * @interface: Interface to use
1794 * @error: #GError for error reporting, or %NULL to ignore.
1796 * Removes @socket from the multicast group @group (while still
1797 * allowing it to receive unicast messages).
1799 * Returns: %TRUE on success, %FALSE on error.
1804 g_socket_leave_multicast_group (GSocket *socket,
1805 GInetAddress *group,
1806 const gchar *interface,
1809 return g_socket_multicast_group_operation (socket, group, interface, FALSE, error);
1813 * g_socket_speaks_ipv4:
1814 * @socket: a #GSocket
1816 * Checks if a socket is capable of speaking IPv4.
1818 * IPv4 sockets are capable of speaking IPv4. On some operating systems
1819 * and under some combinations of circumstances IPv6 sockets are also
1820 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
1823 * No other types of sockets are currently considered as being capable
1826 * Returns: %TRUE if this socket can be used with IPv4.
1831 g_socket_speaks_ipv4 (GSocket *socket)
1833 switch (socket->priv->family)
1835 case G_SOCKET_FAMILY_IPV4:
1838 case G_SOCKET_FAMILY_IPV6:
1839 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1841 guint sizeof_int = sizeof (int);
1844 if (getsockopt (socket->priv->fd,
1845 IPPROTO_IPV6, IPV6_V6ONLY,
1846 &v6_only, &sizeof_int) != 0)
1862 * @socket: a #GSocket.
1863 * @cancellable: (allow-none): a %GCancellable or %NULL
1864 * @error: #GError for error reporting, or %NULL to ignore.
1866 * Accept incoming connections on a connection-based socket. This removes
1867 * the first outstanding connection request from the listening socket and
1868 * creates a #GSocket object for it.
1870 * The @socket must be bound to a local address with g_socket_bind() and
1871 * must be listening for incoming connections (g_socket_listen()).
1873 * If there are no outstanding connections then the operation will block
1874 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1875 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1877 * Returns: (transfer full): a new #GSocket, or %NULL on error.
1878 * Free the returned object with g_object_unref().
1883 g_socket_accept (GSocket *socket,
1884 GCancellable *cancellable,
1887 GSocket *new_socket;
1890 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1892 if (!check_socket (socket, error))
1897 if (socket->priv->blocking &&
1898 !g_socket_condition_wait (socket,
1899 G_IO_IN, cancellable, error))
1902 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1904 int errsv = get_socket_errno ();
1906 win32_unset_event_mask (socket, FD_ACCEPT);
1911 if (socket->priv->blocking)
1913 #ifdef WSAEWOULDBLOCK
1914 if (errsv == WSAEWOULDBLOCK)
1917 if (errsv == EWOULDBLOCK ||
1923 g_set_error (error, G_IO_ERROR,
1924 socket_io_error_from_errno (errsv),
1925 _("Error accepting connection: %s"), socket_strerror (errsv));
1931 win32_unset_event_mask (socket, FD_ACCEPT);
1935 /* The socket inherits the accepting sockets event mask and even object,
1936 we need to remove that */
1937 WSAEventSelect (ret, NULL, 0);
1943 /* We always want to set close-on-exec to protect users. If you
1944 need to so some weird inheritance to exec you can re-enable this
1945 using lower level hacks with g_socket_get_fd(). */
1946 flags = fcntl (ret, F_GETFD, 0);
1948 (flags & FD_CLOEXEC) == 0)
1950 flags |= FD_CLOEXEC;
1951 fcntl (ret, F_SETFD, flags);
1956 new_socket = g_socket_new_from_fd (ret, error);
1957 if (new_socket == NULL)
1966 new_socket->priv->protocol = socket->priv->protocol;
1973 * @socket: a #GSocket.
1974 * @address: a #GSocketAddress specifying the remote address.
1975 * @cancellable: (allow-none): a %GCancellable or %NULL
1976 * @error: #GError for error reporting, or %NULL to ignore.
1978 * Connect the socket to the specified remote address.
1980 * For connection oriented socket this generally means we attempt to make
1981 * a connection to the @address. For a connection-less socket it sets
1982 * the default address for g_socket_send() and discards all incoming datagrams
1983 * from other sources.
1985 * Generally connection oriented sockets can only connect once, but
1986 * connection-less sockets can connect multiple times to change the
1989 * If the connect call needs to do network I/O it will block, unless
1990 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1991 * and the user can be notified of the connection finishing by waiting
1992 * for the G_IO_OUT condition. The result of the connection must then be
1993 * checked with g_socket_check_connect_result().
1995 * Returns: %TRUE if connected, %FALSE on error.
2000 g_socket_connect (GSocket *socket,
2001 GSocketAddress *address,
2002 GCancellable *cancellable,
2005 struct sockaddr_storage buffer;
2007 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2009 if (!check_socket (socket, error))
2012 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2015 if (socket->priv->remote_address)
2016 g_object_unref (socket->priv->remote_address);
2017 socket->priv->remote_address = g_object_ref (address);
2021 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2022 g_socket_address_get_native_size (address)) < 0)
2024 int errsv = get_socket_errno ();
2030 if (errsv == EINPROGRESS)
2032 if (errsv == WSAEWOULDBLOCK)
2035 if (socket->priv->blocking)
2037 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2039 if (g_socket_check_connect_result (socket, error))
2045 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2046 _("Connection in progress"));
2047 socket->priv->connect_pending = TRUE;
2051 g_set_error_literal (error, G_IO_ERROR,
2052 socket_io_error_from_errno (errsv),
2053 socket_strerror (errsv));
2060 win32_unset_event_mask (socket, FD_CONNECT);
2062 socket->priv->connected = TRUE;
2068 * g_socket_check_connect_result:
2069 * @socket: a #GSocket
2070 * @error: #GError for error reporting, or %NULL to ignore.
2072 * Checks and resets the pending connect error for the socket.
2073 * This is used to check for errors when g_socket_connect() is
2074 * used in non-blocking mode.
2076 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2081 g_socket_check_connect_result (GSocket *socket,
2087 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2089 if (!check_socket (socket, error))
2092 optlen = sizeof (value);
2093 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
2095 int errsv = get_socket_errno ();
2097 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2098 _("Unable to get pending error: %s"), socket_strerror (errsv));
2104 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2105 socket_strerror (value));
2106 if (socket->priv->remote_address)
2108 g_object_unref (socket->priv->remote_address);
2109 socket->priv->remote_address = NULL;
2114 socket->priv->connected = TRUE;
2120 * @socket: a #GSocket
2121 * @buffer: a buffer to read data into (which should be at least @size
2123 * @size: the number of bytes you want to read from the socket
2124 * @cancellable: (allow-none): a %GCancellable or %NULL
2125 * @error: #GError for error reporting, or %NULL to ignore.
2127 * Receive data (up to @size bytes) from a socket. This is mainly used by
2128 * connection-oriented sockets; it is identical to g_socket_receive_from()
2129 * with @address set to %NULL.
2131 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2132 * g_socket_receive() will always read either 0 or 1 complete messages from
2133 * the socket. If the received message is too large to fit in @buffer, then
2134 * the data beyond @size bytes will be discarded, without any explicit
2135 * indication that this has occurred.
2137 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2138 * number of bytes, up to @size. If more than @size bytes have been
2139 * received, the additional data will be returned in future calls to
2140 * g_socket_receive().
2142 * If the socket is in blocking mode the call will block until there
2143 * is some data to receive, the connection is closed, or there is an
2144 * error. If there is no data available and the socket is in
2145 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2146 * returned. To be notified when data is available, wait for the
2147 * %G_IO_IN condition.
2149 * On error -1 is returned and @error is set accordingly.
2151 * Returns: Number of bytes read, or 0 if the connection was closed by
2152 * the peer, or -1 on error
2157 g_socket_receive (GSocket *socket,
2160 GCancellable *cancellable,
2163 return g_socket_receive_with_blocking (socket, buffer, size,
2164 socket->priv->blocking,
2165 cancellable, error);
2169 * g_socket_receive_with_blocking:
2170 * @socket: a #GSocket
2171 * @buffer: a buffer to read data into (which should be at least @size
2173 * @size: the number of bytes you want to read from the socket
2174 * @blocking: whether to do blocking or non-blocking I/O
2175 * @cancellable: (allow-none): a %GCancellable or %NULL
2176 * @error: #GError for error reporting, or %NULL to ignore.
2178 * This behaves exactly the same as g_socket_receive(), except that
2179 * the choice of blocking or non-blocking behavior is determined by
2180 * the @blocking argument rather than by @socket's properties.
2182 * Returns: Number of bytes read, or 0 if the connection was closed by
2183 * the peer, or -1 on error
2188 g_socket_receive_with_blocking (GSocket *socket,
2192 GCancellable *cancellable,
2197 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2199 if (!check_socket (socket, error))
2202 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2208 !g_socket_condition_wait (socket,
2209 G_IO_IN, cancellable, error))
2212 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2214 int errsv = get_socket_errno ();
2221 #ifdef WSAEWOULDBLOCK
2222 if (errsv == WSAEWOULDBLOCK)
2225 if (errsv == EWOULDBLOCK ||
2231 win32_unset_event_mask (socket, FD_READ);
2233 g_set_error (error, G_IO_ERROR,
2234 socket_io_error_from_errno (errsv),
2235 _("Error receiving data: %s"), socket_strerror (errsv));
2239 win32_unset_event_mask (socket, FD_READ);
2248 * g_socket_receive_from:
2249 * @socket: a #GSocket
2250 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2252 * @buffer: (array length=size) (element-type guint8): a buffer to
2253 * read data into (which should be at least @size bytes long).
2254 * @size: the number of bytes you want to read from the socket
2255 * @cancellable: (allow-none): a %GCancellable or %NULL
2256 * @error: #GError for error reporting, or %NULL to ignore.
2258 * Receive data (up to @size bytes) from a socket.
2260 * If @address is non-%NULL then @address will be set equal to the
2261 * source address of the received packet.
2262 * @address is owned by the caller.
2264 * See g_socket_receive() for additional information.
2266 * Returns: Number of bytes read, or 0 if the connection was closed by
2267 * the peer, or -1 on error
2272 g_socket_receive_from (GSocket *socket,
2273 GSocketAddress **address,
2276 GCancellable *cancellable,
2284 return g_socket_receive_message (socket,
2292 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2293 * one, which can be confusing and annoying. So if possible, we want
2294 * to suppress the signal entirely.
2297 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2299 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2304 * @socket: a #GSocket
2305 * @buffer: (array length=size) (element-type guint8): the buffer
2306 * containing the data to send.
2307 * @size: the number of bytes to send
2308 * @cancellable: (allow-none): a %GCancellable or %NULL
2309 * @error: #GError for error reporting, or %NULL to ignore.
2311 * Tries to send @size bytes from @buffer on the socket. This is
2312 * mainly used by connection-oriented sockets; it is identical to
2313 * g_socket_send_to() with @address set to %NULL.
2315 * If the socket is in blocking mode the call will block until there is
2316 * space for the data in the socket queue. If there is no space available
2317 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2318 * will be returned. To be notified when space is available, wait for the
2319 * %G_IO_OUT condition. Note though that you may still receive
2320 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2321 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2322 * very common due to the way the underlying APIs work.)
2324 * On error -1 is returned and @error is set accordingly.
2326 * Returns: Number of bytes written (which may be less than @size), or -1
2332 g_socket_send (GSocket *socket,
2333 const gchar *buffer,
2335 GCancellable *cancellable,
2338 return g_socket_send_with_blocking (socket, buffer, size,
2339 socket->priv->blocking,
2340 cancellable, error);
2344 * g_socket_send_with_blocking:
2345 * @socket: a #GSocket
2346 * @buffer: (array length=size) (element-type guint8): the buffer
2347 * containing the data to send.
2348 * @size: the number of bytes to send
2349 * @blocking: whether to do blocking or non-blocking I/O
2350 * @cancellable: (allow-none): a %GCancellable or %NULL
2351 * @error: #GError for error reporting, or %NULL to ignore.
2353 * This behaves exactly the same as g_socket_send(), except that
2354 * the choice of blocking or non-blocking behavior is determined by
2355 * the @blocking argument rather than by @socket's properties.
2357 * Returns: Number of bytes written (which may be less than @size), or -1
2363 g_socket_send_with_blocking (GSocket *socket,
2364 const gchar *buffer,
2367 GCancellable *cancellable,
2372 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2374 if (!check_socket (socket, error))
2377 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2383 !g_socket_condition_wait (socket,
2384 G_IO_OUT, cancellable, error))
2387 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2389 int errsv = get_socket_errno ();
2394 #ifdef WSAEWOULDBLOCK
2395 if (errsv == WSAEWOULDBLOCK)
2396 win32_unset_event_mask (socket, FD_WRITE);
2401 #ifdef WSAEWOULDBLOCK
2402 if (errsv == WSAEWOULDBLOCK)
2405 if (errsv == EWOULDBLOCK ||
2411 g_set_error (error, G_IO_ERROR,
2412 socket_io_error_from_errno (errsv),
2413 _("Error sending data: %s"), socket_strerror (errsv));
2424 * @socket: a #GSocket
2425 * @address: a #GSocketAddress, or %NULL
2426 * @buffer: (array length=size) (element-type guint8): the buffer
2427 * containing the data to send.
2428 * @size: the number of bytes to send
2429 * @cancellable: (allow-none): a %GCancellable or %NULL
2430 * @error: #GError for error reporting, or %NULL to ignore.
2432 * Tries to send @size bytes from @buffer to @address. If @address is
2433 * %NULL then the message is sent to the default receiver (set by
2434 * g_socket_connect()).
2436 * See g_socket_send() for additional information.
2438 * Returns: Number of bytes written (which may be less than @size), or -1
2444 g_socket_send_to (GSocket *socket,
2445 GSocketAddress *address,
2446 const gchar *buffer,
2448 GCancellable *cancellable,
2456 return g_socket_send_message (socket,
2466 * g_socket_shutdown:
2467 * @socket: a #GSocket
2468 * @shutdown_read: whether to shut down the read side
2469 * @shutdown_write: whether to shut down the write side
2470 * @error: #GError for error reporting, or %NULL to ignore.
2472 * Shut down part of a full-duplex connection.
2474 * If @shutdown_read is %TRUE then the receiving side of the connection
2475 * is shut down, and further reading is disallowed.
2477 * If @shutdown_write is %TRUE then the sending side of the connection
2478 * is shut down, and further writing is disallowed.
2480 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2482 * One example where this is used is graceful disconnect for TCP connections
2483 * where you close the sending side, then wait for the other side to close
2484 * the connection, thus ensuring that the other side saw all sent data.
2486 * Returns: %TRUE on success, %FALSE on error
2491 g_socket_shutdown (GSocket *socket,
2492 gboolean shutdown_read,
2493 gboolean shutdown_write,
2498 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2500 if (!check_socket (socket, error))
2504 if (!shutdown_read && !shutdown_write)
2508 if (shutdown_read && shutdown_write)
2510 else if (shutdown_read)
2515 if (shutdown_read && shutdown_write)
2517 else if (shutdown_read)
2523 if (shutdown (socket->priv->fd, how) != 0)
2525 int errsv = get_socket_errno ();
2526 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2527 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2531 if (shutdown_read && shutdown_write)
2532 socket->priv->connected = FALSE;
2539 * @socket: a #GSocket
2540 * @error: #GError for error reporting, or %NULL to ignore.
2542 * Closes the socket, shutting down any active connection.
2544 * Closing a socket does not wait for all outstanding I/O operations
2545 * to finish, so the caller should not rely on them to be guaranteed
2546 * to complete even if the close returns with no error.
2548 * Once the socket is closed, all other operations will return
2549 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2552 * Sockets will be automatically closed when the last reference
2553 * is dropped, but you might want to call this function to make sure
2554 * resources are released as early as possible.
2556 * Beware that due to the way that TCP works, it is possible for
2557 * recently-sent data to be lost if either you close a socket while the
2558 * %G_IO_IN condition is set, or else if the remote connection tries to
2559 * send something to you after you close the socket but before it has
2560 * finished reading all of the data you sent. There is no easy generic
2561 * way to avoid this problem; the easiest fix is to design the network
2562 * protocol such that the client will never send data "out of turn".
2563 * Another solution is for the server to half-close the connection by
2564 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2565 * and then wait for the client to notice this and close its side of the
2566 * connection, after which the server can safely call g_socket_close().
2567 * (This is what #GTcpConnection does if you call
2568 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2569 * only works if the client will close its connection after the server
2572 * Returns: %TRUE on success, %FALSE on error
2577 g_socket_close (GSocket *socket,
2582 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2584 if (socket->priv->closed)
2585 return TRUE; /* Multiple close not an error */
2587 if (!check_socket (socket, error))
2593 res = closesocket (socket->priv->fd);
2595 res = close (socket->priv->fd);
2599 int errsv = get_socket_errno ();
2604 g_set_error (error, G_IO_ERROR,
2605 socket_io_error_from_errno (errsv),
2606 _("Error closing socket: %s"),
2607 socket_strerror (errsv));
2613 socket->priv->connected = FALSE;
2614 socket->priv->closed = TRUE;
2615 if (socket->priv->remote_address)
2617 g_object_unref (socket->priv->remote_address);
2618 socket->priv->remote_address = NULL;
2625 * g_socket_is_closed:
2626 * @socket: a #GSocket
2628 * Checks whether a socket is closed.
2630 * Returns: %TRUE if socket is closed, %FALSE otherwise
2635 g_socket_is_closed (GSocket *socket)
2637 return socket->priv->closed;
2641 /* Broken source, used on errors */
2643 broken_prepare (GSource *source,
2650 broken_check (GSource *source)
2656 broken_dispatch (GSource *source,
2657 GSourceFunc callback,
2663 static GSourceFuncs broken_funcs =
2672 network_events_for_condition (GIOCondition condition)
2676 if (condition & G_IO_IN)
2677 event_mask |= (FD_READ | FD_ACCEPT);
2678 if (condition & G_IO_OUT)
2679 event_mask |= (FD_WRITE | FD_CONNECT);
2680 event_mask |= FD_CLOSE;
2686 ensure_event (GSocket *socket)
2688 if (socket->priv->event == WSA_INVALID_EVENT)
2689 socket->priv->event = WSACreateEvent();
2693 update_select_events (GSocket *socket)
2700 ensure_event (socket);
2703 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2706 event_mask |= network_events_for_condition (*ptr);
2709 if (event_mask != socket->priv->selected_events)
2711 /* If no events selected, disable event so we can unset
2714 if (event_mask == 0)
2717 event = socket->priv->event;
2719 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2720 socket->priv->selected_events = event_mask;
2725 add_condition_watch (GSocket *socket,
2726 GIOCondition *condition)
2728 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2730 socket->priv->requested_conditions =
2731 g_list_prepend (socket->priv->requested_conditions, condition);
2733 update_select_events (socket);
2737 remove_condition_watch (GSocket *socket,
2738 GIOCondition *condition)
2740 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2742 socket->priv->requested_conditions =
2743 g_list_remove (socket->priv->requested_conditions, condition);
2745 update_select_events (socket);
2749 update_condition (GSocket *socket)
2751 WSANETWORKEVENTS events;
2752 GIOCondition condition;
2754 if (WSAEnumNetworkEvents (socket->priv->fd,
2755 socket->priv->event,
2758 socket->priv->current_events |= events.lNetworkEvents;
2759 if (events.lNetworkEvents & FD_WRITE &&
2760 events.iErrorCode[FD_WRITE_BIT] != 0)
2761 socket->priv->current_errors |= FD_WRITE;
2762 if (events.lNetworkEvents & FD_CONNECT &&
2763 events.iErrorCode[FD_CONNECT_BIT] != 0)
2764 socket->priv->current_errors |= FD_CONNECT;
2768 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2769 condition |= G_IO_IN;
2771 if (socket->priv->current_events & FD_CLOSE ||
2772 socket->priv->closed)
2773 condition |= G_IO_HUP;
2775 /* Never report both G_IO_OUT and HUP, these are
2776 mutually exclusive (can't write to a closed socket) */
2777 if ((condition & G_IO_HUP) == 0 &&
2778 socket->priv->current_events & FD_WRITE)
2780 if (socket->priv->current_errors & FD_WRITE)
2781 condition |= G_IO_ERR;
2783 condition |= G_IO_OUT;
2787 if (socket->priv->current_events & FD_CONNECT)
2789 if (socket->priv->current_errors & FD_CONNECT)
2790 condition |= (G_IO_HUP | G_IO_ERR);
2792 condition |= G_IO_OUT;
2804 GIOCondition condition;
2805 GCancellable *cancellable;
2806 GPollFD cancel_pollfd;
2807 gint64 timeout_time;
2811 socket_source_prepare (GSource *source,
2814 GSocketSource *socket_source = (GSocketSource *)source;
2816 if (g_cancellable_is_cancelled (socket_source->cancellable))
2819 if (socket_source->timeout_time)
2823 now = g_source_get_time (source);
2824 /* Round up to ensure that we don't try again too early */
2825 *timeout = (socket_source->timeout_time - now + 999) / 1000;
2828 socket_source->socket->priv->timed_out = TRUE;
2837 socket_source->pollfd.revents = update_condition (socket_source->socket);
2840 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2847 socket_source_check (GSource *source)
2851 return socket_source_prepare (source, &timeout);
2855 socket_source_dispatch (GSource *source,
2856 GSourceFunc callback,
2859 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2860 GSocketSource *socket_source = (GSocketSource *)source;
2863 socket_source->pollfd.revents = update_condition (socket_source->socket);
2865 if (socket_source->socket->priv->timed_out)
2866 socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
2868 return (*func) (socket_source->socket,
2869 socket_source->pollfd.revents & socket_source->condition,
2874 socket_source_finalize (GSource *source)
2876 GSocketSource *socket_source = (GSocketSource *)source;
2879 socket = socket_source->socket;
2882 remove_condition_watch (socket, &socket_source->condition);
2885 g_object_unref (socket);
2887 if (socket_source->cancellable)
2889 g_cancellable_release_fd (socket_source->cancellable);
2890 g_object_unref (socket_source->cancellable);
2895 socket_source_closure_callback (GSocket *socket,
2896 GIOCondition condition,
2899 GClosure *closure = data;
2901 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
2902 GValue result_value = G_VALUE_INIT;
2905 g_value_init (&result_value, G_TYPE_BOOLEAN);
2907 g_value_init (¶ms[0], G_TYPE_SOCKET);
2908 g_value_set_object (¶ms[0], socket);
2909 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
2910 g_value_set_flags (¶ms[1], condition);
2912 g_closure_invoke (closure, &result_value, 2, params, NULL);
2914 result = g_value_get_boolean (&result_value);
2915 g_value_unset (&result_value);
2916 g_value_unset (¶ms[0]);
2917 g_value_unset (¶ms[1]);
2922 static GSourceFuncs socket_source_funcs =
2924 socket_source_prepare,
2925 socket_source_check,
2926 socket_source_dispatch,
2927 socket_source_finalize,
2928 (GSourceFunc)socket_source_closure_callback,
2929 (GSourceDummyMarshal)g_cclosure_marshal_generic,
2933 socket_source_new (GSocket *socket,
2934 GIOCondition condition,
2935 GCancellable *cancellable)
2938 GSocketSource *socket_source;
2941 ensure_event (socket);
2943 if (socket->priv->event == WSA_INVALID_EVENT)
2945 g_warning ("Failed to create WSAEvent");
2946 return g_source_new (&broken_funcs, sizeof (GSource));
2950 condition |= G_IO_HUP | G_IO_ERR;
2952 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2953 g_source_set_name (source, "GSocket");
2954 socket_source = (GSocketSource *)source;
2956 socket_source->socket = g_object_ref (socket);
2957 socket_source->condition = condition;
2959 if (g_cancellable_make_pollfd (cancellable,
2960 &socket_source->cancel_pollfd))
2962 socket_source->cancellable = g_object_ref (cancellable);
2963 g_source_add_poll (source, &socket_source->cancel_pollfd);
2967 add_condition_watch (socket, &socket_source->condition);
2968 socket_source->pollfd.fd = (gintptr) socket->priv->event;
2970 socket_source->pollfd.fd = socket->priv->fd;
2973 socket_source->pollfd.events = condition;
2974 socket_source->pollfd.revents = 0;
2975 g_source_add_poll (source, &socket_source->pollfd);
2977 if (socket->priv->timeout)
2978 socket_source->timeout_time = g_get_monotonic_time () +
2979 socket->priv->timeout * 1000000;
2982 socket_source->timeout_time = 0;
2988 * g_socket_create_source: (skip)
2989 * @socket: a #GSocket
2990 * @condition: a #GIOCondition mask to monitor
2991 * @cancellable: (allow-none): a %GCancellable or %NULL
2993 * Creates a %GSource that can be attached to a %GMainContext to monitor
2994 * for the availibility of the specified @condition on the socket.
2996 * The callback on the source is of the #GSocketSourceFunc type.
2998 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2999 * these conditions will always be reported output if they are true.
3001 * @cancellable if not %NULL can be used to cancel the source, which will
3002 * cause the source to trigger, reporting the current condition (which
3003 * is likely 0 unless cancellation happened at the same time as a
3004 * condition change). You can check for this in the callback using
3005 * g_cancellable_is_cancelled().
3007 * If @socket has a timeout set, and it is reached before @condition
3008 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3009 * %G_IO_OUT depending on @condition. However, @socket will have been
3010 * marked as having had a timeout, and so the next #GSocket I/O method
3011 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3013 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3018 g_socket_create_source (GSocket *socket,
3019 GIOCondition condition,
3020 GCancellable *cancellable)
3022 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3024 return socket_source_new (socket, condition, cancellable);
3028 * g_socket_condition_check:
3029 * @socket: a #GSocket
3030 * @condition: a #GIOCondition mask to check
3032 * Checks on the readiness of @socket to perform operations.
3033 * The operations specified in @condition are checked for and masked
3034 * against the currently-satisfied conditions on @socket. The result
3037 * Note that on Windows, it is possible for an operation to return
3038 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3039 * g_socket_condition_check() has claimed that the socket is ready for
3040 * writing. Rather than calling g_socket_condition_check() and then
3041 * writing to the socket if it succeeds, it is generally better to
3042 * simply try writing to the socket right away, and try again later if
3043 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3045 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3046 * these conditions will always be set in the output if they are true.
3048 * This call never blocks.
3050 * Returns: the @GIOCondition mask of the current state
3055 g_socket_condition_check (GSocket *socket,
3056 GIOCondition condition)
3058 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3060 if (!check_socket (socket, NULL))
3065 GIOCondition current_condition;
3067 condition |= G_IO_ERR | G_IO_HUP;
3069 add_condition_watch (socket, &condition);
3070 current_condition = update_condition (socket);
3071 remove_condition_watch (socket, &condition);
3072 return condition & current_condition;
3078 poll_fd.fd = socket->priv->fd;
3079 poll_fd.events = condition;
3082 result = g_poll (&poll_fd, 1, 0);
3083 while (result == -1 && get_socket_errno () == EINTR);
3085 return poll_fd.revents;
3091 * g_socket_condition_wait:
3092 * @socket: a #GSocket
3093 * @condition: a #GIOCondition mask to wait for
3094 * @cancellable: (allow-none): a #GCancellable, or %NULL
3095 * @error: a #GError pointer, or %NULL
3097 * Waits for @condition to become true on @socket. When the condition
3098 * is met, %TRUE is returned.
3100 * If @cancellable is cancelled before the condition is met, or if the
3101 * socket has a timeout set and it is reached before the condition is
3102 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3103 * the appropriate value (%G_IO_ERROR_CANCELLED or
3104 * %G_IO_ERROR_TIMED_OUT).
3106 * Returns: %TRUE if the condition was met, %FALSE otherwise
3111 g_socket_condition_wait (GSocket *socket,
3112 GIOCondition condition,
3113 GCancellable *cancellable,
3116 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3118 if (!check_socket (socket, error))
3121 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3126 GIOCondition current_condition;
3132 /* Always check these */
3133 condition |= G_IO_ERR | G_IO_HUP;
3135 add_condition_watch (socket, &condition);
3138 events[num_events++] = socket->priv->event;
3140 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3141 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3143 if (socket->priv->timeout)
3144 timeout = socket->priv->timeout * 1000;
3146 timeout = WSA_INFINITE;
3148 current_condition = update_condition (socket);
3149 while ((condition & current_condition) == 0)
3151 res = WSAWaitForMultipleEvents(num_events, events,
3152 FALSE, timeout, FALSE);
3153 if (res == WSA_WAIT_FAILED)
3155 int errsv = get_socket_errno ();
3157 g_set_error (error, G_IO_ERROR,
3158 socket_io_error_from_errno (errsv),
3159 _("Waiting for socket condition: %s"),
3160 socket_strerror (errsv));
3163 else if (res == WSA_WAIT_TIMEOUT)
3165 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3166 _("Socket I/O timed out"));
3170 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3173 current_condition = update_condition (socket);
3175 remove_condition_watch (socket, &condition);
3177 g_cancellable_release_fd (cancellable);
3179 return (condition & current_condition) != 0;
3188 poll_fd[0].fd = socket->priv->fd;
3189 poll_fd[0].events = condition;
3192 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3195 if (socket->priv->timeout)
3196 timeout = socket->priv->timeout * 1000;
3201 result = g_poll (poll_fd, num, timeout);
3202 while (result == -1 && get_socket_errno () == EINTR);
3205 g_cancellable_release_fd (cancellable);
3209 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3210 _("Socket I/O timed out"));
3214 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3220 * g_socket_send_message:
3221 * @socket: a #GSocket
3222 * @address: a #GSocketAddress, or %NULL
3223 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3224 * @num_vectors: the number of elements in @vectors, or -1
3225 * @messages: (array length=num_messages) (allow-none): a pointer to an
3226 * array of #GSocketControlMessages, or %NULL.
3227 * @num_messages: number of elements in @messages, or -1.
3228 * @flags: an int containing #GSocketMsgFlags flags
3229 * @cancellable: (allow-none): a %GCancellable or %NULL
3230 * @error: #GError for error reporting, or %NULL to ignore.
3232 * Send data to @address on @socket. This is the most complicated and
3233 * fully-featured version of this call. For easier use, see
3234 * g_socket_send() and g_socket_send_to().
3236 * If @address is %NULL then the message is sent to the default receiver
3237 * (set by g_socket_connect()).
3239 * @vectors must point to an array of #GOutputVector structs and
3240 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3241 * then @vectors is assumed to be terminated by a #GOutputVector with a
3242 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3243 * that the sent data will be gathered from. Using multiple
3244 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3245 * data from multiple sources into a single buffer, and more
3246 * network-efficient than making multiple calls to g_socket_send().
3248 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3249 * #GSocketControlMessage instances. These correspond to the control
3250 * messages to be sent on the socket.
3251 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3254 * @flags modify how the message is sent. The commonly available arguments
3255 * for this are available in the #GSocketMsgFlags enum, but the
3256 * values there are the same as the system values, and the flags
3257 * are passed in as-is, so you can pass in system-specific flags too.
3259 * If the socket is in blocking mode the call will block until there is
3260 * space for the data in the socket queue. If there is no space available
3261 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3262 * will be returned. To be notified when space is available, wait for the
3263 * %G_IO_OUT condition. Note though that you may still receive
3264 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3265 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3266 * very common due to the way the underlying APIs work.)
3268 * On error -1 is returned and @error is set accordingly.
3270 * Returns: Number of bytes written (which may be less than @size), or -1
3276 g_socket_send_message (GSocket *socket,
3277 GSocketAddress *address,
3278 GOutputVector *vectors,
3280 GSocketControlMessage **messages,
3283 GCancellable *cancellable,
3286 GOutputVector one_vector;
3289 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3291 if (!check_socket (socket, error))
3294 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3297 if (num_vectors == -1)
3299 for (num_vectors = 0;
3300 vectors[num_vectors].buffer != NULL;
3305 if (num_messages == -1)
3307 for (num_messages = 0;
3308 messages != NULL && messages[num_messages] != NULL;
3313 if (num_vectors == 0)
3317 one_vector.buffer = &zero;
3318 one_vector.size = 1;
3320 vectors = &one_vector;
3333 msg.msg_namelen = g_socket_address_get_native_size (address);
3334 msg.msg_name = g_alloca (msg.msg_namelen);
3335 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3340 msg.msg_name = NULL;
3341 msg.msg_namelen = 0;
3346 /* this entire expression will be evaluated at compile time */
3347 if (sizeof *msg.msg_iov == sizeof *vectors &&
3348 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3349 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3350 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3351 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3352 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3353 G_STRUCT_OFFSET (GOutputVector, size))
3354 /* ABI is compatible */
3356 msg.msg_iov = (struct iovec *) vectors;
3357 msg.msg_iovlen = num_vectors;
3360 /* ABI is incompatible */
3364 msg.msg_iov = g_newa (struct iovec, num_vectors);
3365 for (i = 0; i < num_vectors; i++)
3367 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3368 msg.msg_iov[i].iov_len = vectors[i].size;
3370 msg.msg_iovlen = num_vectors;
3376 struct cmsghdr *cmsg;
3379 msg.msg_controllen = 0;
3380 for (i = 0; i < num_messages; i++)
3381 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3383 if (msg.msg_controllen == 0)
3384 msg.msg_control = NULL;
3387 msg.msg_control = g_alloca (msg.msg_controllen);
3388 memset (msg.msg_control, '\0', msg.msg_controllen);
3391 cmsg = CMSG_FIRSTHDR (&msg);
3392 for (i = 0; i < num_messages; i++)
3394 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3395 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3396 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3397 g_socket_control_message_serialize (messages[i],
3399 cmsg = CMSG_NXTHDR (&msg, cmsg);
3401 g_assert (cmsg == NULL);
3406 if (socket->priv->blocking &&
3407 !g_socket_condition_wait (socket,
3408 G_IO_OUT, cancellable, error))
3411 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3414 int errsv = get_socket_errno ();
3419 if (socket->priv->blocking &&
3420 (errsv == EWOULDBLOCK ||
3424 g_set_error (error, G_IO_ERROR,
3425 socket_io_error_from_errno (errsv),
3426 _("Error sending message: %s"), socket_strerror (errsv));
3437 struct sockaddr_storage addr;
3444 /* Win32 doesn't support control messages.
3445 Actually this is possible for raw and datagram sockets
3446 via WSASendMessage on Vista or later, but that doesn't
3448 if (num_messages != 0)
3450 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3451 _("GSocketControlMessage not supported on windows"));
3456 bufs = g_newa (WSABUF, num_vectors);
3457 for (i = 0; i < num_vectors; i++)
3459 bufs[i].buf = (char *)vectors[i].buffer;
3460 bufs[i].len = (gulong)vectors[i].size;
3464 addrlen = 0; /* Avoid warning */
3467 addrlen = g_socket_address_get_native_size (address);
3468 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3474 if (socket->priv->blocking &&
3475 !g_socket_condition_wait (socket,
3476 G_IO_OUT, cancellable, error))
3480 result = WSASendTo (socket->priv->fd,
3483 (const struct sockaddr *)&addr, addrlen,
3486 result = WSASend (socket->priv->fd,
3493 int errsv = get_socket_errno ();
3495 if (errsv == WSAEINTR)
3498 if (errsv == WSAEWOULDBLOCK)
3499 win32_unset_event_mask (socket, FD_WRITE);
3501 if (socket->priv->blocking &&
3502 errsv == WSAEWOULDBLOCK)
3505 g_set_error (error, G_IO_ERROR,
3506 socket_io_error_from_errno (errsv),
3507 _("Error sending message: %s"), socket_strerror (errsv));
3520 * g_socket_receive_message:
3521 * @socket: a #GSocket
3522 * @address: (out) (allow-none): a pointer to a #GSocketAddress
3524 * @vectors: (array length=num_vectors): an array of #GInputVector structs
3525 * @num_vectors: the number of elements in @vectors, or -1
3526 * @messages: (array length=num_messages) (allow-none): a pointer which
3527 * may be filled with an array of #GSocketControlMessages, or %NULL
3528 * @num_messages: a pointer which will be filled with the number of
3529 * elements in @messages, or %NULL
3530 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3531 * @cancellable: (allow-none): a %GCancellable or %NULL
3532 * @error: a #GError pointer, or %NULL
3534 * Receive data from a socket. This is the most complicated and
3535 * fully-featured version of this call. For easier use, see
3536 * g_socket_receive() and g_socket_receive_from().
3538 * If @address is non-%NULL then @address will be set equal to the
3539 * source address of the received packet.
3540 * @address is owned by the caller.
3542 * @vector must point to an array of #GInputVector structs and
3543 * @num_vectors must be the length of this array. These structs
3544 * describe the buffers that received data will be scattered into.
3545 * If @num_vectors is -1, then @vectors is assumed to be terminated
3546 * by a #GInputVector with a %NULL buffer pointer.
3548 * As a special case, if @num_vectors is 0 (in which case, @vectors
3549 * may of course be %NULL), then a single byte is received and
3550 * discarded. This is to facilitate the common practice of sending a
3551 * single '\0' byte for the purposes of transferring ancillary data.
3553 * @messages, if non-%NULL, will be set to point to a newly-allocated
3554 * array of #GSocketControlMessage instances or %NULL if no such
3555 * messages was received. These correspond to the control messages
3556 * received from the kernel, one #GSocketControlMessage per message
3557 * from the kernel. This array is %NULL-terminated and must be freed
3558 * by the caller using g_free() after calling g_object_unref() on each
3559 * element. If @messages is %NULL, any control messages received will
3562 * @num_messages, if non-%NULL, will be set to the number of control
3563 * messages received.
3565 * If both @messages and @num_messages are non-%NULL, then
3566 * @num_messages gives the number of #GSocketControlMessage instances
3567 * in @messages (ie: not including the %NULL terminator).
3569 * @flags is an in/out parameter. The commonly available arguments
3570 * for this are available in the #GSocketMsgFlags enum, but the
3571 * values there are the same as the system values, and the flags
3572 * are passed in as-is, so you can pass in system-specific flags too
3573 * (and g_socket_receive_message() may pass system-specific flags out).
3575 * As with g_socket_receive(), data may be discarded if @socket is
3576 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3577 * provide enough buffer space to read a complete message. You can pass
3578 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3579 * removing it from the receive queue, but there is no portable way to find
3580 * out the length of the message other than by reading it into a
3581 * sufficiently-large buffer.
3583 * If the socket is in blocking mode the call will block until there
3584 * is some data to receive, the connection is closed, or there is an
3585 * error. If there is no data available and the socket is in
3586 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3587 * returned. To be notified when data is available, wait for the
3588 * %G_IO_IN condition.
3590 * On error -1 is returned and @error is set accordingly.
3592 * Returns: Number of bytes read, or 0 if the connection was closed by
3593 * the peer, or -1 on error
3598 g_socket_receive_message (GSocket *socket,
3599 GSocketAddress **address,
3600 GInputVector *vectors,
3602 GSocketControlMessage ***messages,
3605 GCancellable *cancellable,
3608 GInputVector one_vector;
3611 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3613 if (!check_socket (socket, error))
3616 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3619 if (num_vectors == -1)
3621 for (num_vectors = 0;
3622 vectors[num_vectors].buffer != NULL;
3627 if (num_vectors == 0)
3629 one_vector.buffer = &one_byte;
3630 one_vector.size = 1;
3632 vectors = &one_vector;
3639 struct sockaddr_storage one_sockaddr;
3644 msg.msg_name = &one_sockaddr;
3645 msg.msg_namelen = sizeof (struct sockaddr_storage);
3649 msg.msg_name = NULL;
3650 msg.msg_namelen = 0;
3654 /* this entire expression will be evaluated at compile time */
3655 if (sizeof *msg.msg_iov == sizeof *vectors &&
3656 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3657 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3658 G_STRUCT_OFFSET (GInputVector, buffer) &&
3659 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3660 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3661 G_STRUCT_OFFSET (GInputVector, size))
3662 /* ABI is compatible */
3664 msg.msg_iov = (struct iovec *) vectors;
3665 msg.msg_iovlen = num_vectors;
3668 /* ABI is incompatible */
3672 msg.msg_iov = g_newa (struct iovec, num_vectors);
3673 for (i = 0; i < num_vectors; i++)
3675 msg.msg_iov[i].iov_base = vectors[i].buffer;
3676 msg.msg_iov[i].iov_len = vectors[i].size;
3678 msg.msg_iovlen = num_vectors;
3682 msg.msg_control = g_alloca (2048);
3683 msg.msg_controllen = 2048;
3687 msg.msg_flags = *flags;
3691 /* We always set the close-on-exec flag so we don't leak file
3692 * descriptors into child processes. Note that gunixfdmessage.c
3693 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
3695 #ifdef MSG_CMSG_CLOEXEC
3696 msg.msg_flags |= MSG_CMSG_CLOEXEC;
3702 if (socket->priv->blocking &&
3703 !g_socket_condition_wait (socket,
3704 G_IO_IN, cancellable, error))
3707 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3708 #ifdef MSG_CMSG_CLOEXEC
3709 if (result < 0 && get_socket_errno () == EINVAL)
3711 /* We must be running on an old kernel. Call without the flag. */
3712 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
3713 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3719 int errsv = get_socket_errno ();
3724 if (socket->priv->blocking &&
3725 (errsv == EWOULDBLOCK ||
3729 g_set_error (error, G_IO_ERROR,
3730 socket_io_error_from_errno (errsv),
3731 _("Error receiving message: %s"), socket_strerror (errsv));
3738 /* decode address */
3739 if (address != NULL)
3741 if (msg.msg_namelen > 0)
3742 *address = g_socket_address_new_from_native (msg.msg_name,
3748 /* decode control messages */
3750 GPtrArray *my_messages = NULL;
3751 struct cmsghdr *cmsg;
3753 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3755 GSocketControlMessage *message;
3757 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3759 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3761 if (message == NULL)
3762 /* We've already spewed about the problem in the
3763 deserialization code, so just continue */
3766 if (messages == NULL)
3768 /* we have to do it this way if the user ignores the
3769 * messages so that we will close any received fds.
3771 g_object_unref (message);
3775 if (my_messages == NULL)
3776 my_messages = g_ptr_array_new ();
3777 g_ptr_array_add (my_messages, message);
3782 *num_messages = my_messages != NULL ? my_messages->len : 0;
3786 if (my_messages == NULL)
3792 g_ptr_array_add (my_messages, NULL);
3793 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3798 g_assert (my_messages == NULL);
3802 /* capture the flags */
3804 *flags = msg.msg_flags;
3810 struct sockaddr_storage addr;
3812 DWORD bytes_received;
3819 bufs = g_newa (WSABUF, num_vectors);
3820 for (i = 0; i < num_vectors; i++)
3822 bufs[i].buf = (char *)vectors[i].buffer;
3823 bufs[i].len = (gulong)vectors[i].size;
3835 if (socket->priv->blocking &&
3836 !g_socket_condition_wait (socket,
3837 G_IO_IN, cancellable, error))
3840 addrlen = sizeof addr;
3842 result = WSARecvFrom (socket->priv->fd,
3844 &bytes_received, &win_flags,
3845 (struct sockaddr *)&addr, &addrlen,
3848 result = WSARecv (socket->priv->fd,
3850 &bytes_received, &win_flags,
3854 int errsv = get_socket_errno ();
3856 if (errsv == WSAEINTR)
3859 win32_unset_event_mask (socket, FD_READ);
3861 if (socket->priv->blocking &&
3862 errsv == WSAEWOULDBLOCK)
3865 g_set_error (error, G_IO_ERROR,
3866 socket_io_error_from_errno (errsv),
3867 _("Error receiving message: %s"), socket_strerror (errsv));
3871 win32_unset_event_mask (socket, FD_READ);
3875 /* decode address */
3876 if (address != NULL)
3879 *address = g_socket_address_new_from_native (&addr, addrlen);
3884 /* capture the flags */
3888 if (messages != NULL)
3890 if (num_messages != NULL)
3893 return bytes_received;
3899 * g_socket_get_credentials:
3900 * @socket: a #GSocket.
3901 * @error: #GError for error reporting, or %NULL to ignore.
3903 * Returns the credentials of the foreign process connected to this
3904 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
3907 * If this operation isn't supported on the OS, the method fails with
3908 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
3909 * by reading the %SO_PEERCRED option on the underlying socket.
3911 * Other ways to obtain credentials from a foreign peer includes the
3912 * #GUnixCredentialsMessage type and
3913 * g_unix_connection_send_credentials() /
3914 * g_unix_connection_receive_credentials() functions.
3916 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
3917 * that must be freed with g_object_unref().
3922 g_socket_get_credentials (GSocket *socket,
3927 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
3928 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3932 #if defined(__linux__) || defined(__OpenBSD__)
3935 #if defined(__linux__)
3936 struct ucred native_creds;
3937 optlen = sizeof (struct ucred);
3938 #elif defined(__OpenBSD__)
3939 struct sockpeercred native_creds;
3940 optlen = sizeof (struct sockpeercred);
3942 if (getsockopt (socket->priv->fd,
3945 (void *)&native_creds,
3948 int errsv = get_socket_errno ();
3951 socket_io_error_from_errno (errsv),
3952 _("Unable to get pending error: %s"),
3953 socket_strerror (errsv));
3957 ret = g_credentials_new ();
3958 g_credentials_set_native (ret,
3959 #if defined(__linux__)
3960 G_CREDENTIALS_TYPE_LINUX_UCRED,
3961 #elif defined(__OpenBSD__)
3962 G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
3968 g_set_error_literal (error,
3970 G_IO_ERROR_NOT_SUPPORTED,
3971 _("g_socket_get_credentials not implemented for this OS"));