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 source_specific,
1692 const gchar *interface,
1693 gboolean join_group,
1696 const guint8 *native_addr;
1697 gint optname, result;
1699 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1700 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
1701 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
1702 g_return_val_if_fail (g_inet_address_get_family (group) == socket->priv->family, FALSE);
1704 if (!check_socket (socket, error))
1707 native_addr = g_inet_address_to_bytes (group);
1708 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1710 #ifdef HAVE_IP_MREQN
1711 struct ip_mreqn mc_req;
1713 struct ip_mreq mc_req;
1716 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
1718 #ifdef HAVE_IP_MREQN
1720 mc_req.imr_ifindex = if_nametoindex (interface);
1722 mc_req.imr_ifindex = 0; /* Pick any. */
1724 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
1727 if (source_specific)
1728 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
1730 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
1731 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
1732 &mc_req, sizeof (mc_req));
1734 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1736 struct ipv6_mreq mc_req_ipv6;
1738 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
1740 mc_req_ipv6.ipv6mr_interface = if_nametoindex (interface);
1742 mc_req_ipv6.ipv6mr_interface = 0;
1744 optname = join_group ? IPV6_ADD_MEMBERSHIP : IPV6_DROP_MEMBERSHIP;
1745 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
1746 &mc_req_ipv6, sizeof (mc_req_ipv6));
1749 g_return_val_if_reached (FALSE);
1753 int errsv = get_socket_errno ();
1755 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1757 _("Error joining multicast group: %s") :
1758 _("Error leaving multicast group: %s"),
1759 socket_strerror (errsv));
1767 * g_socket_join_multicast_group:
1768 * @socket: a #GSocket.
1769 * @group: a #GInetAddress specifying the group address to join.
1770 * @interface: Interface to use
1771 * @source_specific: %TRUE if source-specific multicast should be used
1772 * @error: #GError for error reporting, or %NULL to ignore.
1774 * Registers @socket to receive multicast messages sent to @group.
1775 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
1776 * been bound to an appropriate interface and port with
1779 * If @source_specific is %TRUE, source-specific multicast as defined
1780 * in RFC 4604 is used.
1782 * Returns: %TRUE on success, %FALSE on error.
1787 g_socket_join_multicast_group (GSocket *socket,
1788 GInetAddress *group,
1789 gboolean source_specific,
1790 const gchar *interface,
1793 return g_socket_multicast_group_operation (socket, group, source_specific, interface, TRUE, error);
1797 * g_socket_leave_multicast_group:
1798 * @socket: a #GSocket.
1799 * @group: a #GInetAddress specifying the group address to leave.
1800 * @interface: Interface to use
1801 * @source_specific: %TRUE if source-specific multicast should be used
1802 * @error: #GError for error reporting, or %NULL to ignore.
1804 * Removes @socket from the multicast group @group (while still
1805 * allowing it to receive unicast messages).
1807 * If @source_specific is %TRUE, source-specific multicast as defined
1808 * in RFC 4604 is used.
1810 * Returns: %TRUE on success, %FALSE on error.
1815 g_socket_leave_multicast_group (GSocket *socket,
1816 GInetAddress *group,
1817 gboolean source_specific,
1818 const gchar *interface,
1821 return g_socket_multicast_group_operation (socket, group, source_specific, interface, FALSE, error);
1825 * g_socket_speaks_ipv4:
1826 * @socket: a #GSocket
1828 * Checks if a socket is capable of speaking IPv4.
1830 * IPv4 sockets are capable of speaking IPv4. On some operating systems
1831 * and under some combinations of circumstances IPv6 sockets are also
1832 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
1835 * No other types of sockets are currently considered as being capable
1838 * Returns: %TRUE if this socket can be used with IPv4.
1843 g_socket_speaks_ipv4 (GSocket *socket)
1845 switch (socket->priv->family)
1847 case G_SOCKET_FAMILY_IPV4:
1850 case G_SOCKET_FAMILY_IPV6:
1851 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1853 guint sizeof_int = sizeof (int);
1856 if (getsockopt (socket->priv->fd,
1857 IPPROTO_IPV6, IPV6_V6ONLY,
1858 &v6_only, &sizeof_int) != 0)
1874 * @socket: a #GSocket.
1875 * @cancellable: (allow-none): a %GCancellable or %NULL
1876 * @error: #GError for error reporting, or %NULL to ignore.
1878 * Accept incoming connections on a connection-based socket. This removes
1879 * the first outstanding connection request from the listening socket and
1880 * creates a #GSocket object for it.
1882 * The @socket must be bound to a local address with g_socket_bind() and
1883 * must be listening for incoming connections (g_socket_listen()).
1885 * If there are no outstanding connections then the operation will block
1886 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1887 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1889 * Returns: (transfer full): a new #GSocket, or %NULL on error.
1890 * Free the returned object with g_object_unref().
1895 g_socket_accept (GSocket *socket,
1896 GCancellable *cancellable,
1899 GSocket *new_socket;
1902 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1904 if (!check_socket (socket, error))
1909 if (socket->priv->blocking &&
1910 !g_socket_condition_wait (socket,
1911 G_IO_IN, cancellable, error))
1914 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1916 int errsv = get_socket_errno ();
1918 win32_unset_event_mask (socket, FD_ACCEPT);
1923 if (socket->priv->blocking)
1925 #ifdef WSAEWOULDBLOCK
1926 if (errsv == WSAEWOULDBLOCK)
1929 if (errsv == EWOULDBLOCK ||
1935 g_set_error (error, G_IO_ERROR,
1936 socket_io_error_from_errno (errsv),
1937 _("Error accepting connection: %s"), socket_strerror (errsv));
1943 win32_unset_event_mask (socket, FD_ACCEPT);
1947 /* The socket inherits the accepting sockets event mask and even object,
1948 we need to remove that */
1949 WSAEventSelect (ret, NULL, 0);
1955 /* We always want to set close-on-exec to protect users. If you
1956 need to so some weird inheritance to exec you can re-enable this
1957 using lower level hacks with g_socket_get_fd(). */
1958 flags = fcntl (ret, F_GETFD, 0);
1960 (flags & FD_CLOEXEC) == 0)
1962 flags |= FD_CLOEXEC;
1963 fcntl (ret, F_SETFD, flags);
1968 new_socket = g_socket_new_from_fd (ret, error);
1969 if (new_socket == NULL)
1978 new_socket->priv->protocol = socket->priv->protocol;
1985 * @socket: a #GSocket.
1986 * @address: a #GSocketAddress specifying the remote address.
1987 * @cancellable: (allow-none): a %GCancellable or %NULL
1988 * @error: #GError for error reporting, or %NULL to ignore.
1990 * Connect the socket to the specified remote address.
1992 * For connection oriented socket this generally means we attempt to make
1993 * a connection to the @address. For a connection-less socket it sets
1994 * the default address for g_socket_send() and discards all incoming datagrams
1995 * from other sources.
1997 * Generally connection oriented sockets can only connect once, but
1998 * connection-less sockets can connect multiple times to change the
2001 * If the connect call needs to do network I/O it will block, unless
2002 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2003 * and the user can be notified of the connection finishing by waiting
2004 * for the G_IO_OUT condition. The result of the connection must then be
2005 * checked with g_socket_check_connect_result().
2007 * Returns: %TRUE if connected, %FALSE on error.
2012 g_socket_connect (GSocket *socket,
2013 GSocketAddress *address,
2014 GCancellable *cancellable,
2017 struct sockaddr_storage buffer;
2019 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2021 if (!check_socket (socket, error))
2024 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2027 if (socket->priv->remote_address)
2028 g_object_unref (socket->priv->remote_address);
2029 socket->priv->remote_address = g_object_ref (address);
2033 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2034 g_socket_address_get_native_size (address)) < 0)
2036 int errsv = get_socket_errno ();
2042 if (errsv == EINPROGRESS)
2044 if (errsv == WSAEWOULDBLOCK)
2047 if (socket->priv->blocking)
2049 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2051 if (g_socket_check_connect_result (socket, error))
2057 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2058 _("Connection in progress"));
2059 socket->priv->connect_pending = TRUE;
2063 g_set_error_literal (error, G_IO_ERROR,
2064 socket_io_error_from_errno (errsv),
2065 socket_strerror (errsv));
2072 win32_unset_event_mask (socket, FD_CONNECT);
2074 socket->priv->connected = TRUE;
2080 * g_socket_check_connect_result:
2081 * @socket: a #GSocket
2082 * @error: #GError for error reporting, or %NULL to ignore.
2084 * Checks and resets the pending connect error for the socket.
2085 * This is used to check for errors when g_socket_connect() is
2086 * used in non-blocking mode.
2088 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2093 g_socket_check_connect_result (GSocket *socket,
2099 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2101 if (!check_socket (socket, error))
2104 optlen = sizeof (value);
2105 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
2107 int errsv = get_socket_errno ();
2109 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2110 _("Unable to get pending error: %s"), socket_strerror (errsv));
2116 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2117 socket_strerror (value));
2118 if (socket->priv->remote_address)
2120 g_object_unref (socket->priv->remote_address);
2121 socket->priv->remote_address = NULL;
2126 socket->priv->connected = TRUE;
2132 * @socket: a #GSocket
2133 * @buffer: a buffer to read data into (which should be at least @size
2135 * @size: the number of bytes you want to read from the socket
2136 * @cancellable: (allow-none): a %GCancellable or %NULL
2137 * @error: #GError for error reporting, or %NULL to ignore.
2139 * Receive data (up to @size bytes) from a socket. This is mainly used by
2140 * connection-oriented sockets; it is identical to g_socket_receive_from()
2141 * with @address set to %NULL.
2143 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2144 * g_socket_receive() will always read either 0 or 1 complete messages from
2145 * the socket. If the received message is too large to fit in @buffer, then
2146 * the data beyond @size bytes will be discarded, without any explicit
2147 * indication that this has occurred.
2149 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2150 * number of bytes, up to @size. If more than @size bytes have been
2151 * received, the additional data will be returned in future calls to
2152 * g_socket_receive().
2154 * If the socket is in blocking mode the call will block until there
2155 * is some data to receive, the connection is closed, or there is an
2156 * error. If there is no data available and the socket is in
2157 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2158 * returned. To be notified when data is available, wait for the
2159 * %G_IO_IN condition.
2161 * On error -1 is returned and @error is set accordingly.
2163 * Returns: Number of bytes read, or 0 if the connection was closed by
2164 * the peer, or -1 on error
2169 g_socket_receive (GSocket *socket,
2172 GCancellable *cancellable,
2175 return g_socket_receive_with_blocking (socket, buffer, size,
2176 socket->priv->blocking,
2177 cancellable, error);
2181 * g_socket_receive_with_blocking:
2182 * @socket: a #GSocket
2183 * @buffer: a buffer to read data into (which should be at least @size
2185 * @size: the number of bytes you want to read from the socket
2186 * @blocking: whether to do blocking or non-blocking I/O
2187 * @cancellable: (allow-none): a %GCancellable or %NULL
2188 * @error: #GError for error reporting, or %NULL to ignore.
2190 * This behaves exactly the same as g_socket_receive(), except that
2191 * the choice of blocking or non-blocking behavior is determined by
2192 * the @blocking argument rather than by @socket's properties.
2194 * Returns: Number of bytes read, or 0 if the connection was closed by
2195 * the peer, or -1 on error
2200 g_socket_receive_with_blocking (GSocket *socket,
2204 GCancellable *cancellable,
2209 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2211 if (!check_socket (socket, error))
2214 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2220 !g_socket_condition_wait (socket,
2221 G_IO_IN, cancellable, error))
2224 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2226 int errsv = get_socket_errno ();
2233 #ifdef WSAEWOULDBLOCK
2234 if (errsv == WSAEWOULDBLOCK)
2237 if (errsv == EWOULDBLOCK ||
2243 win32_unset_event_mask (socket, FD_READ);
2245 g_set_error (error, G_IO_ERROR,
2246 socket_io_error_from_errno (errsv),
2247 _("Error receiving data: %s"), socket_strerror (errsv));
2251 win32_unset_event_mask (socket, FD_READ);
2260 * g_socket_receive_from:
2261 * @socket: a #GSocket
2262 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2264 * @buffer: (array length=size) (element-type guint8): a buffer to
2265 * read data into (which should be at least @size bytes long).
2266 * @size: the number of bytes you want to read from the socket
2267 * @cancellable: (allow-none): a %GCancellable or %NULL
2268 * @error: #GError for error reporting, or %NULL to ignore.
2270 * Receive data (up to @size bytes) from a socket.
2272 * If @address is non-%NULL then @address will be set equal to the
2273 * source address of the received packet.
2274 * @address is owned by the caller.
2276 * See g_socket_receive() for additional information.
2278 * Returns: Number of bytes read, or 0 if the connection was closed by
2279 * the peer, or -1 on error
2284 g_socket_receive_from (GSocket *socket,
2285 GSocketAddress **address,
2288 GCancellable *cancellable,
2296 return g_socket_receive_message (socket,
2304 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2305 * one, which can be confusing and annoying. So if possible, we want
2306 * to suppress the signal entirely.
2309 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2311 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2316 * @socket: a #GSocket
2317 * @buffer: (array length=size) (element-type guint8): the buffer
2318 * containing the data to send.
2319 * @size: the number of bytes to send
2320 * @cancellable: (allow-none): a %GCancellable or %NULL
2321 * @error: #GError for error reporting, or %NULL to ignore.
2323 * Tries to send @size bytes from @buffer on the socket. This is
2324 * mainly used by connection-oriented sockets; it is identical to
2325 * g_socket_send_to() with @address set to %NULL.
2327 * If the socket is in blocking mode the call will block until there is
2328 * space for the data in the socket queue. If there is no space available
2329 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2330 * will be returned. To be notified when space is available, wait for the
2331 * %G_IO_OUT condition. Note though that you may still receive
2332 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2333 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2334 * very common due to the way the underlying APIs work.)
2336 * On error -1 is returned and @error is set accordingly.
2338 * Returns: Number of bytes written (which may be less than @size), or -1
2344 g_socket_send (GSocket *socket,
2345 const gchar *buffer,
2347 GCancellable *cancellable,
2350 return g_socket_send_with_blocking (socket, buffer, size,
2351 socket->priv->blocking,
2352 cancellable, error);
2356 * g_socket_send_with_blocking:
2357 * @socket: a #GSocket
2358 * @buffer: (array length=size) (element-type guint8): the buffer
2359 * containing the data to send.
2360 * @size: the number of bytes to send
2361 * @blocking: whether to do blocking or non-blocking I/O
2362 * @cancellable: (allow-none): a %GCancellable or %NULL
2363 * @error: #GError for error reporting, or %NULL to ignore.
2365 * This behaves exactly the same as g_socket_send(), except that
2366 * the choice of blocking or non-blocking behavior is determined by
2367 * the @blocking argument rather than by @socket's properties.
2369 * Returns: Number of bytes written (which may be less than @size), or -1
2375 g_socket_send_with_blocking (GSocket *socket,
2376 const gchar *buffer,
2379 GCancellable *cancellable,
2384 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2386 if (!check_socket (socket, error))
2389 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2395 !g_socket_condition_wait (socket,
2396 G_IO_OUT, cancellable, error))
2399 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2401 int errsv = get_socket_errno ();
2406 #ifdef WSAEWOULDBLOCK
2407 if (errsv == WSAEWOULDBLOCK)
2408 win32_unset_event_mask (socket, FD_WRITE);
2413 #ifdef WSAEWOULDBLOCK
2414 if (errsv == WSAEWOULDBLOCK)
2417 if (errsv == EWOULDBLOCK ||
2423 g_set_error (error, G_IO_ERROR,
2424 socket_io_error_from_errno (errsv),
2425 _("Error sending data: %s"), socket_strerror (errsv));
2436 * @socket: a #GSocket
2437 * @address: a #GSocketAddress, or %NULL
2438 * @buffer: (array length=size) (element-type guint8): the buffer
2439 * containing the data to send.
2440 * @size: the number of bytes to send
2441 * @cancellable: (allow-none): a %GCancellable or %NULL
2442 * @error: #GError for error reporting, or %NULL to ignore.
2444 * Tries to send @size bytes from @buffer to @address. If @address is
2445 * %NULL then the message is sent to the default receiver (set by
2446 * g_socket_connect()).
2448 * See g_socket_send() for additional information.
2450 * Returns: Number of bytes written (which may be less than @size), or -1
2456 g_socket_send_to (GSocket *socket,
2457 GSocketAddress *address,
2458 const gchar *buffer,
2460 GCancellable *cancellable,
2468 return g_socket_send_message (socket,
2478 * g_socket_shutdown:
2479 * @socket: a #GSocket
2480 * @shutdown_read: whether to shut down the read side
2481 * @shutdown_write: whether to shut down the write side
2482 * @error: #GError for error reporting, or %NULL to ignore.
2484 * Shut down part of a full-duplex connection.
2486 * If @shutdown_read is %TRUE then the receiving side of the connection
2487 * is shut down, and further reading is disallowed.
2489 * If @shutdown_write is %TRUE then the sending side of the connection
2490 * is shut down, and further writing is disallowed.
2492 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2494 * One example where this is used is graceful disconnect for TCP connections
2495 * where you close the sending side, then wait for the other side to close
2496 * the connection, thus ensuring that the other side saw all sent data.
2498 * Returns: %TRUE on success, %FALSE on error
2503 g_socket_shutdown (GSocket *socket,
2504 gboolean shutdown_read,
2505 gboolean shutdown_write,
2510 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2512 if (!check_socket (socket, error))
2516 if (!shutdown_read && !shutdown_write)
2520 if (shutdown_read && shutdown_write)
2522 else if (shutdown_read)
2527 if (shutdown_read && shutdown_write)
2529 else if (shutdown_read)
2535 if (shutdown (socket->priv->fd, how) != 0)
2537 int errsv = get_socket_errno ();
2538 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2539 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2543 if (shutdown_read && shutdown_write)
2544 socket->priv->connected = FALSE;
2551 * @socket: a #GSocket
2552 * @error: #GError for error reporting, or %NULL to ignore.
2554 * Closes the socket, shutting down any active connection.
2556 * Closing a socket does not wait for all outstanding I/O operations
2557 * to finish, so the caller should not rely on them to be guaranteed
2558 * to complete even if the close returns with no error.
2560 * Once the socket is closed, all other operations will return
2561 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2564 * Sockets will be automatically closed when the last reference
2565 * is dropped, but you might want to call this function to make sure
2566 * resources are released as early as possible.
2568 * Beware that due to the way that TCP works, it is possible for
2569 * recently-sent data to be lost if either you close a socket while the
2570 * %G_IO_IN condition is set, or else if the remote connection tries to
2571 * send something to you after you close the socket but before it has
2572 * finished reading all of the data you sent. There is no easy generic
2573 * way to avoid this problem; the easiest fix is to design the network
2574 * protocol such that the client will never send data "out of turn".
2575 * Another solution is for the server to half-close the connection by
2576 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2577 * and then wait for the client to notice this and close its side of the
2578 * connection, after which the server can safely call g_socket_close().
2579 * (This is what #GTcpConnection does if you call
2580 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2581 * only works if the client will close its connection after the server
2584 * Returns: %TRUE on success, %FALSE on error
2589 g_socket_close (GSocket *socket,
2594 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2596 if (socket->priv->closed)
2597 return TRUE; /* Multiple close not an error */
2599 if (!check_socket (socket, error))
2605 res = closesocket (socket->priv->fd);
2607 res = close (socket->priv->fd);
2611 int errsv = get_socket_errno ();
2616 g_set_error (error, G_IO_ERROR,
2617 socket_io_error_from_errno (errsv),
2618 _("Error closing socket: %s"),
2619 socket_strerror (errsv));
2625 socket->priv->connected = FALSE;
2626 socket->priv->closed = TRUE;
2627 if (socket->priv->remote_address)
2629 g_object_unref (socket->priv->remote_address);
2630 socket->priv->remote_address = NULL;
2637 * g_socket_is_closed:
2638 * @socket: a #GSocket
2640 * Checks whether a socket is closed.
2642 * Returns: %TRUE if socket is closed, %FALSE otherwise
2647 g_socket_is_closed (GSocket *socket)
2649 return socket->priv->closed;
2653 /* Broken source, used on errors */
2655 broken_prepare (GSource *source,
2662 broken_check (GSource *source)
2668 broken_dispatch (GSource *source,
2669 GSourceFunc callback,
2675 static GSourceFuncs broken_funcs =
2684 network_events_for_condition (GIOCondition condition)
2688 if (condition & G_IO_IN)
2689 event_mask |= (FD_READ | FD_ACCEPT);
2690 if (condition & G_IO_OUT)
2691 event_mask |= (FD_WRITE | FD_CONNECT);
2692 event_mask |= FD_CLOSE;
2698 ensure_event (GSocket *socket)
2700 if (socket->priv->event == WSA_INVALID_EVENT)
2701 socket->priv->event = WSACreateEvent();
2705 update_select_events (GSocket *socket)
2712 ensure_event (socket);
2715 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2718 event_mask |= network_events_for_condition (*ptr);
2721 if (event_mask != socket->priv->selected_events)
2723 /* If no events selected, disable event so we can unset
2726 if (event_mask == 0)
2729 event = socket->priv->event;
2731 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2732 socket->priv->selected_events = event_mask;
2737 add_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_prepend (socket->priv->requested_conditions, condition);
2745 update_select_events (socket);
2749 remove_condition_watch (GSocket *socket,
2750 GIOCondition *condition)
2752 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2754 socket->priv->requested_conditions =
2755 g_list_remove (socket->priv->requested_conditions, condition);
2757 update_select_events (socket);
2761 update_condition (GSocket *socket)
2763 WSANETWORKEVENTS events;
2764 GIOCondition condition;
2766 if (WSAEnumNetworkEvents (socket->priv->fd,
2767 socket->priv->event,
2770 socket->priv->current_events |= events.lNetworkEvents;
2771 if (events.lNetworkEvents & FD_WRITE &&
2772 events.iErrorCode[FD_WRITE_BIT] != 0)
2773 socket->priv->current_errors |= FD_WRITE;
2774 if (events.lNetworkEvents & FD_CONNECT &&
2775 events.iErrorCode[FD_CONNECT_BIT] != 0)
2776 socket->priv->current_errors |= FD_CONNECT;
2780 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2781 condition |= G_IO_IN;
2783 if (socket->priv->current_events & FD_CLOSE ||
2784 socket->priv->closed)
2785 condition |= G_IO_HUP;
2787 /* Never report both G_IO_OUT and HUP, these are
2788 mutually exclusive (can't write to a closed socket) */
2789 if ((condition & G_IO_HUP) == 0 &&
2790 socket->priv->current_events & FD_WRITE)
2792 if (socket->priv->current_errors & FD_WRITE)
2793 condition |= G_IO_ERR;
2795 condition |= G_IO_OUT;
2799 if (socket->priv->current_events & FD_CONNECT)
2801 if (socket->priv->current_errors & FD_CONNECT)
2802 condition |= (G_IO_HUP | G_IO_ERR);
2804 condition |= G_IO_OUT;
2816 GIOCondition condition;
2817 GCancellable *cancellable;
2818 GPollFD cancel_pollfd;
2819 gint64 timeout_time;
2823 socket_source_prepare (GSource *source,
2826 GSocketSource *socket_source = (GSocketSource *)source;
2828 if (g_cancellable_is_cancelled (socket_source->cancellable))
2831 if (socket_source->timeout_time)
2835 now = g_source_get_time (source);
2836 /* Round up to ensure that we don't try again too early */
2837 *timeout = (socket_source->timeout_time - now + 999) / 1000;
2840 socket_source->socket->priv->timed_out = TRUE;
2849 socket_source->pollfd.revents = update_condition (socket_source->socket);
2852 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2859 socket_source_check (GSource *source)
2863 return socket_source_prepare (source, &timeout);
2867 socket_source_dispatch (GSource *source,
2868 GSourceFunc callback,
2871 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2872 GSocketSource *socket_source = (GSocketSource *)source;
2875 socket_source->pollfd.revents = update_condition (socket_source->socket);
2877 if (socket_source->socket->priv->timed_out)
2878 socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
2880 return (*func) (socket_source->socket,
2881 socket_source->pollfd.revents & socket_source->condition,
2886 socket_source_finalize (GSource *source)
2888 GSocketSource *socket_source = (GSocketSource *)source;
2891 socket = socket_source->socket;
2894 remove_condition_watch (socket, &socket_source->condition);
2897 g_object_unref (socket);
2899 if (socket_source->cancellable)
2901 g_cancellable_release_fd (socket_source->cancellable);
2902 g_object_unref (socket_source->cancellable);
2907 socket_source_closure_callback (GSocket *socket,
2908 GIOCondition condition,
2911 GClosure *closure = data;
2913 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
2914 GValue result_value = G_VALUE_INIT;
2917 g_value_init (&result_value, G_TYPE_BOOLEAN);
2919 g_value_init (¶ms[0], G_TYPE_SOCKET);
2920 g_value_set_object (¶ms[0], socket);
2921 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
2922 g_value_set_flags (¶ms[1], condition);
2924 g_closure_invoke (closure, &result_value, 2, params, NULL);
2926 result = g_value_get_boolean (&result_value);
2927 g_value_unset (&result_value);
2928 g_value_unset (¶ms[0]);
2929 g_value_unset (¶ms[1]);
2934 static GSourceFuncs socket_source_funcs =
2936 socket_source_prepare,
2937 socket_source_check,
2938 socket_source_dispatch,
2939 socket_source_finalize,
2940 (GSourceFunc)socket_source_closure_callback,
2941 (GSourceDummyMarshal)g_cclosure_marshal_generic,
2945 socket_source_new (GSocket *socket,
2946 GIOCondition condition,
2947 GCancellable *cancellable)
2950 GSocketSource *socket_source;
2953 ensure_event (socket);
2955 if (socket->priv->event == WSA_INVALID_EVENT)
2957 g_warning ("Failed to create WSAEvent");
2958 return g_source_new (&broken_funcs, sizeof (GSource));
2962 condition |= G_IO_HUP | G_IO_ERR;
2964 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2965 g_source_set_name (source, "GSocket");
2966 socket_source = (GSocketSource *)source;
2968 socket_source->socket = g_object_ref (socket);
2969 socket_source->condition = condition;
2971 if (g_cancellable_make_pollfd (cancellable,
2972 &socket_source->cancel_pollfd))
2974 socket_source->cancellable = g_object_ref (cancellable);
2975 g_source_add_poll (source, &socket_source->cancel_pollfd);
2979 add_condition_watch (socket, &socket_source->condition);
2980 socket_source->pollfd.fd = (gintptr) socket->priv->event;
2982 socket_source->pollfd.fd = socket->priv->fd;
2985 socket_source->pollfd.events = condition;
2986 socket_source->pollfd.revents = 0;
2987 g_source_add_poll (source, &socket_source->pollfd);
2989 if (socket->priv->timeout)
2990 socket_source->timeout_time = g_get_monotonic_time () +
2991 socket->priv->timeout * 1000000;
2994 socket_source->timeout_time = 0;
3000 * g_socket_create_source: (skip)
3001 * @socket: a #GSocket
3002 * @condition: a #GIOCondition mask to monitor
3003 * @cancellable: (allow-none): a %GCancellable or %NULL
3005 * Creates a %GSource that can be attached to a %GMainContext to monitor
3006 * for the availibility of the specified @condition on the socket.
3008 * The callback on the source is of the #GSocketSourceFunc type.
3010 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3011 * these conditions will always be reported output if they are true.
3013 * @cancellable if not %NULL can be used to cancel the source, which will
3014 * cause the source to trigger, reporting the current condition (which
3015 * is likely 0 unless cancellation happened at the same time as a
3016 * condition change). You can check for this in the callback using
3017 * g_cancellable_is_cancelled().
3019 * If @socket has a timeout set, and it is reached before @condition
3020 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3021 * %G_IO_OUT depending on @condition. However, @socket will have been
3022 * marked as having had a timeout, and so the next #GSocket I/O method
3023 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3025 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3030 g_socket_create_source (GSocket *socket,
3031 GIOCondition condition,
3032 GCancellable *cancellable)
3034 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3036 return socket_source_new (socket, condition, cancellable);
3040 * g_socket_condition_check:
3041 * @socket: a #GSocket
3042 * @condition: a #GIOCondition mask to check
3044 * Checks on the readiness of @socket to perform operations.
3045 * The operations specified in @condition are checked for and masked
3046 * against the currently-satisfied conditions on @socket. The result
3049 * Note that on Windows, it is possible for an operation to return
3050 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3051 * g_socket_condition_check() has claimed that the socket is ready for
3052 * writing. Rather than calling g_socket_condition_check() and then
3053 * writing to the socket if it succeeds, it is generally better to
3054 * simply try writing to the socket right away, and try again later if
3055 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3057 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3058 * these conditions will always be set in the output if they are true.
3060 * This call never blocks.
3062 * Returns: the @GIOCondition mask of the current state
3067 g_socket_condition_check (GSocket *socket,
3068 GIOCondition condition)
3070 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3072 if (!check_socket (socket, NULL))
3077 GIOCondition current_condition;
3079 condition |= G_IO_ERR | G_IO_HUP;
3081 add_condition_watch (socket, &condition);
3082 current_condition = update_condition (socket);
3083 remove_condition_watch (socket, &condition);
3084 return condition & current_condition;
3090 poll_fd.fd = socket->priv->fd;
3091 poll_fd.events = condition;
3094 result = g_poll (&poll_fd, 1, 0);
3095 while (result == -1 && get_socket_errno () == EINTR);
3097 return poll_fd.revents;
3103 * g_socket_condition_wait:
3104 * @socket: a #GSocket
3105 * @condition: a #GIOCondition mask to wait for
3106 * @cancellable: (allow-none): a #GCancellable, or %NULL
3107 * @error: a #GError pointer, or %NULL
3109 * Waits for @condition to become true on @socket. When the condition
3110 * is met, %TRUE is returned.
3112 * If @cancellable is cancelled before the condition is met, or if the
3113 * socket has a timeout set and it is reached before the condition is
3114 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3115 * the appropriate value (%G_IO_ERROR_CANCELLED or
3116 * %G_IO_ERROR_TIMED_OUT).
3118 * Returns: %TRUE if the condition was met, %FALSE otherwise
3123 g_socket_condition_wait (GSocket *socket,
3124 GIOCondition condition,
3125 GCancellable *cancellable,
3128 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3130 if (!check_socket (socket, error))
3133 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3138 GIOCondition current_condition;
3144 /* Always check these */
3145 condition |= G_IO_ERR | G_IO_HUP;
3147 add_condition_watch (socket, &condition);
3150 events[num_events++] = socket->priv->event;
3152 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3153 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3155 if (socket->priv->timeout)
3156 timeout = socket->priv->timeout * 1000;
3158 timeout = WSA_INFINITE;
3160 current_condition = update_condition (socket);
3161 while ((condition & current_condition) == 0)
3163 res = WSAWaitForMultipleEvents(num_events, events,
3164 FALSE, timeout, FALSE);
3165 if (res == WSA_WAIT_FAILED)
3167 int errsv = get_socket_errno ();
3169 g_set_error (error, G_IO_ERROR,
3170 socket_io_error_from_errno (errsv),
3171 _("Waiting for socket condition: %s"),
3172 socket_strerror (errsv));
3175 else if (res == WSA_WAIT_TIMEOUT)
3177 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3178 _("Socket I/O timed out"));
3182 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3185 current_condition = update_condition (socket);
3187 remove_condition_watch (socket, &condition);
3189 g_cancellable_release_fd (cancellable);
3191 return (condition & current_condition) != 0;
3200 poll_fd[0].fd = socket->priv->fd;
3201 poll_fd[0].events = condition;
3204 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3207 if (socket->priv->timeout)
3208 timeout = socket->priv->timeout * 1000;
3213 result = g_poll (poll_fd, num, timeout);
3214 while (result == -1 && get_socket_errno () == EINTR);
3217 g_cancellable_release_fd (cancellable);
3221 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3222 _("Socket I/O timed out"));
3226 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3232 * g_socket_send_message:
3233 * @socket: a #GSocket
3234 * @address: a #GSocketAddress, or %NULL
3235 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3236 * @num_vectors: the number of elements in @vectors, or -1
3237 * @messages: (array length=num_messages) (allow-none): a pointer to an
3238 * array of #GSocketControlMessages, or %NULL.
3239 * @num_messages: number of elements in @messages, or -1.
3240 * @flags: an int containing #GSocketMsgFlags flags
3241 * @cancellable: (allow-none): a %GCancellable or %NULL
3242 * @error: #GError for error reporting, or %NULL to ignore.
3244 * Send data to @address on @socket. This is the most complicated and
3245 * fully-featured version of this call. For easier use, see
3246 * g_socket_send() and g_socket_send_to().
3248 * If @address is %NULL then the message is sent to the default receiver
3249 * (set by g_socket_connect()).
3251 * @vectors must point to an array of #GOutputVector structs and
3252 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3253 * then @vectors is assumed to be terminated by a #GOutputVector with a
3254 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3255 * that the sent data will be gathered from. Using multiple
3256 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3257 * data from multiple sources into a single buffer, and more
3258 * network-efficient than making multiple calls to g_socket_send().
3260 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3261 * #GSocketControlMessage instances. These correspond to the control
3262 * messages to be sent on the socket.
3263 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3266 * @flags modify how the message is sent. The commonly available arguments
3267 * for this are available in the #GSocketMsgFlags enum, but the
3268 * values there are the same as the system values, and the flags
3269 * are passed in as-is, so you can pass in system-specific flags too.
3271 * If the socket is in blocking mode the call will block until there is
3272 * space for the data in the socket queue. If there is no space available
3273 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3274 * will be returned. To be notified when space is available, wait for the
3275 * %G_IO_OUT condition. Note though that you may still receive
3276 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3277 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3278 * very common due to the way the underlying APIs work.)
3280 * On error -1 is returned and @error is set accordingly.
3282 * Returns: Number of bytes written (which may be less than @size), or -1
3288 g_socket_send_message (GSocket *socket,
3289 GSocketAddress *address,
3290 GOutputVector *vectors,
3292 GSocketControlMessage **messages,
3295 GCancellable *cancellable,
3298 GOutputVector one_vector;
3301 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3303 if (!check_socket (socket, error))
3306 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3309 if (num_vectors == -1)
3311 for (num_vectors = 0;
3312 vectors[num_vectors].buffer != NULL;
3317 if (num_messages == -1)
3319 for (num_messages = 0;
3320 messages != NULL && messages[num_messages] != NULL;
3325 if (num_vectors == 0)
3329 one_vector.buffer = &zero;
3330 one_vector.size = 1;
3332 vectors = &one_vector;
3345 msg.msg_namelen = g_socket_address_get_native_size (address);
3346 msg.msg_name = g_alloca (msg.msg_namelen);
3347 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3352 msg.msg_name = NULL;
3353 msg.msg_namelen = 0;
3358 /* this entire expression will be evaluated at compile time */
3359 if (sizeof *msg.msg_iov == sizeof *vectors &&
3360 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3361 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3362 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3363 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3364 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3365 G_STRUCT_OFFSET (GOutputVector, size))
3366 /* ABI is compatible */
3368 msg.msg_iov = (struct iovec *) vectors;
3369 msg.msg_iovlen = num_vectors;
3372 /* ABI is incompatible */
3376 msg.msg_iov = g_newa (struct iovec, num_vectors);
3377 for (i = 0; i < num_vectors; i++)
3379 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3380 msg.msg_iov[i].iov_len = vectors[i].size;
3382 msg.msg_iovlen = num_vectors;
3388 struct cmsghdr *cmsg;
3391 msg.msg_controllen = 0;
3392 for (i = 0; i < num_messages; i++)
3393 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3395 if (msg.msg_controllen == 0)
3396 msg.msg_control = NULL;
3399 msg.msg_control = g_alloca (msg.msg_controllen);
3400 memset (msg.msg_control, '\0', msg.msg_controllen);
3403 cmsg = CMSG_FIRSTHDR (&msg);
3404 for (i = 0; i < num_messages; i++)
3406 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3407 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3408 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3409 g_socket_control_message_serialize (messages[i],
3411 cmsg = CMSG_NXTHDR (&msg, cmsg);
3413 g_assert (cmsg == NULL);
3418 if (socket->priv->blocking &&
3419 !g_socket_condition_wait (socket,
3420 G_IO_OUT, cancellable, error))
3423 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3426 int errsv = get_socket_errno ();
3431 if (socket->priv->blocking &&
3432 (errsv == EWOULDBLOCK ||
3436 g_set_error (error, G_IO_ERROR,
3437 socket_io_error_from_errno (errsv),
3438 _("Error sending message: %s"), socket_strerror (errsv));
3449 struct sockaddr_storage addr;
3456 /* Win32 doesn't support control messages.
3457 Actually this is possible for raw and datagram sockets
3458 via WSASendMessage on Vista or later, but that doesn't
3460 if (num_messages != 0)
3462 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3463 _("GSocketControlMessage not supported on windows"));
3468 bufs = g_newa (WSABUF, num_vectors);
3469 for (i = 0; i < num_vectors; i++)
3471 bufs[i].buf = (char *)vectors[i].buffer;
3472 bufs[i].len = (gulong)vectors[i].size;
3476 addrlen = 0; /* Avoid warning */
3479 addrlen = g_socket_address_get_native_size (address);
3480 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3486 if (socket->priv->blocking &&
3487 !g_socket_condition_wait (socket,
3488 G_IO_OUT, cancellable, error))
3492 result = WSASendTo (socket->priv->fd,
3495 (const struct sockaddr *)&addr, addrlen,
3498 result = WSASend (socket->priv->fd,
3505 int errsv = get_socket_errno ();
3507 if (errsv == WSAEINTR)
3510 if (errsv == WSAEWOULDBLOCK)
3511 win32_unset_event_mask (socket, FD_WRITE);
3513 if (socket->priv->blocking &&
3514 errsv == WSAEWOULDBLOCK)
3517 g_set_error (error, G_IO_ERROR,
3518 socket_io_error_from_errno (errsv),
3519 _("Error sending message: %s"), socket_strerror (errsv));
3532 * g_socket_receive_message:
3533 * @socket: a #GSocket
3534 * @address: (out) (allow-none): a pointer to a #GSocketAddress
3536 * @vectors: (array length=num_vectors): an array of #GInputVector structs
3537 * @num_vectors: the number of elements in @vectors, or -1
3538 * @messages: (array length=num_messages) (allow-none): a pointer which
3539 * may be filled with an array of #GSocketControlMessages, or %NULL
3540 * @num_messages: a pointer which will be filled with the number of
3541 * elements in @messages, or %NULL
3542 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3543 * @cancellable: (allow-none): a %GCancellable or %NULL
3544 * @error: a #GError pointer, or %NULL
3546 * Receive data from a socket. This is the most complicated and
3547 * fully-featured version of this call. For easier use, see
3548 * g_socket_receive() and g_socket_receive_from().
3550 * If @address is non-%NULL then @address will be set equal to the
3551 * source address of the received packet.
3552 * @address is owned by the caller.
3554 * @vector must point to an array of #GInputVector structs and
3555 * @num_vectors must be the length of this array. These structs
3556 * describe the buffers that received data will be scattered into.
3557 * If @num_vectors is -1, then @vectors is assumed to be terminated
3558 * by a #GInputVector with a %NULL buffer pointer.
3560 * As a special case, if @num_vectors is 0 (in which case, @vectors
3561 * may of course be %NULL), then a single byte is received and
3562 * discarded. This is to facilitate the common practice of sending a
3563 * single '\0' byte for the purposes of transferring ancillary data.
3565 * @messages, if non-%NULL, will be set to point to a newly-allocated
3566 * array of #GSocketControlMessage instances or %NULL if no such
3567 * messages was received. These correspond to the control messages
3568 * received from the kernel, one #GSocketControlMessage per message
3569 * from the kernel. This array is %NULL-terminated and must be freed
3570 * by the caller using g_free() after calling g_object_unref() on each
3571 * element. If @messages is %NULL, any control messages received will
3574 * @num_messages, if non-%NULL, will be set to the number of control
3575 * messages received.
3577 * If both @messages and @num_messages are non-%NULL, then
3578 * @num_messages gives the number of #GSocketControlMessage instances
3579 * in @messages (ie: not including the %NULL terminator).
3581 * @flags is an in/out parameter. The commonly available arguments
3582 * for this are available in the #GSocketMsgFlags enum, but the
3583 * values there are the same as the system values, and the flags
3584 * are passed in as-is, so you can pass in system-specific flags too
3585 * (and g_socket_receive_message() may pass system-specific flags out).
3587 * As with g_socket_receive(), data may be discarded if @socket is
3588 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3589 * provide enough buffer space to read a complete message. You can pass
3590 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3591 * removing it from the receive queue, but there is no portable way to find
3592 * out the length of the message other than by reading it into a
3593 * sufficiently-large buffer.
3595 * If the socket is in blocking mode the call will block until there
3596 * is some data to receive, the connection is closed, or there is an
3597 * error. If there is no data available and the socket is in
3598 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3599 * returned. To be notified when data is available, wait for the
3600 * %G_IO_IN condition.
3602 * On error -1 is returned and @error is set accordingly.
3604 * Returns: Number of bytes read, or 0 if the connection was closed by
3605 * the peer, or -1 on error
3610 g_socket_receive_message (GSocket *socket,
3611 GSocketAddress **address,
3612 GInputVector *vectors,
3614 GSocketControlMessage ***messages,
3617 GCancellable *cancellable,
3620 GInputVector one_vector;
3623 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3625 if (!check_socket (socket, error))
3628 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3631 if (num_vectors == -1)
3633 for (num_vectors = 0;
3634 vectors[num_vectors].buffer != NULL;
3639 if (num_vectors == 0)
3641 one_vector.buffer = &one_byte;
3642 one_vector.size = 1;
3644 vectors = &one_vector;
3651 struct sockaddr_storage one_sockaddr;
3656 msg.msg_name = &one_sockaddr;
3657 msg.msg_namelen = sizeof (struct sockaddr_storage);
3661 msg.msg_name = NULL;
3662 msg.msg_namelen = 0;
3666 /* this entire expression will be evaluated at compile time */
3667 if (sizeof *msg.msg_iov == sizeof *vectors &&
3668 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3669 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3670 G_STRUCT_OFFSET (GInputVector, buffer) &&
3671 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3672 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3673 G_STRUCT_OFFSET (GInputVector, size))
3674 /* ABI is compatible */
3676 msg.msg_iov = (struct iovec *) vectors;
3677 msg.msg_iovlen = num_vectors;
3680 /* ABI is incompatible */
3684 msg.msg_iov = g_newa (struct iovec, num_vectors);
3685 for (i = 0; i < num_vectors; i++)
3687 msg.msg_iov[i].iov_base = vectors[i].buffer;
3688 msg.msg_iov[i].iov_len = vectors[i].size;
3690 msg.msg_iovlen = num_vectors;
3694 msg.msg_control = g_alloca (2048);
3695 msg.msg_controllen = 2048;
3699 msg.msg_flags = *flags;
3703 /* We always set the close-on-exec flag so we don't leak file
3704 * descriptors into child processes. Note that gunixfdmessage.c
3705 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
3707 #ifdef MSG_CMSG_CLOEXEC
3708 msg.msg_flags |= MSG_CMSG_CLOEXEC;
3714 if (socket->priv->blocking &&
3715 !g_socket_condition_wait (socket,
3716 G_IO_IN, cancellable, error))
3719 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3720 #ifdef MSG_CMSG_CLOEXEC
3721 if (result < 0 && get_socket_errno () == EINVAL)
3723 /* We must be running on an old kernel. Call without the flag. */
3724 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
3725 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3731 int errsv = get_socket_errno ();
3736 if (socket->priv->blocking &&
3737 (errsv == EWOULDBLOCK ||
3741 g_set_error (error, G_IO_ERROR,
3742 socket_io_error_from_errno (errsv),
3743 _("Error receiving message: %s"), socket_strerror (errsv));
3750 /* decode address */
3751 if (address != NULL)
3753 if (msg.msg_namelen > 0)
3754 *address = g_socket_address_new_from_native (msg.msg_name,
3760 /* decode control messages */
3762 GPtrArray *my_messages = NULL;
3763 struct cmsghdr *cmsg;
3765 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3767 GSocketControlMessage *message;
3769 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3771 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3773 if (message == NULL)
3774 /* We've already spewed about the problem in the
3775 deserialization code, so just continue */
3778 if (messages == NULL)
3780 /* we have to do it this way if the user ignores the
3781 * messages so that we will close any received fds.
3783 g_object_unref (message);
3787 if (my_messages == NULL)
3788 my_messages = g_ptr_array_new ();
3789 g_ptr_array_add (my_messages, message);
3794 *num_messages = my_messages != NULL ? my_messages->len : 0;
3798 if (my_messages == NULL)
3804 g_ptr_array_add (my_messages, NULL);
3805 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3810 g_assert (my_messages == NULL);
3814 /* capture the flags */
3816 *flags = msg.msg_flags;
3822 struct sockaddr_storage addr;
3824 DWORD bytes_received;
3831 bufs = g_newa (WSABUF, num_vectors);
3832 for (i = 0; i < num_vectors; i++)
3834 bufs[i].buf = (char *)vectors[i].buffer;
3835 bufs[i].len = (gulong)vectors[i].size;
3847 if (socket->priv->blocking &&
3848 !g_socket_condition_wait (socket,
3849 G_IO_IN, cancellable, error))
3852 addrlen = sizeof addr;
3854 result = WSARecvFrom (socket->priv->fd,
3856 &bytes_received, &win_flags,
3857 (struct sockaddr *)&addr, &addrlen,
3860 result = WSARecv (socket->priv->fd,
3862 &bytes_received, &win_flags,
3866 int errsv = get_socket_errno ();
3868 if (errsv == WSAEINTR)
3871 win32_unset_event_mask (socket, FD_READ);
3873 if (socket->priv->blocking &&
3874 errsv == WSAEWOULDBLOCK)
3877 g_set_error (error, G_IO_ERROR,
3878 socket_io_error_from_errno (errsv),
3879 _("Error receiving message: %s"), socket_strerror (errsv));
3883 win32_unset_event_mask (socket, FD_READ);
3887 /* decode address */
3888 if (address != NULL)
3891 *address = g_socket_address_new_from_native (&addr, addrlen);
3896 /* capture the flags */
3900 if (messages != NULL)
3902 if (num_messages != NULL)
3905 return bytes_received;
3911 * g_socket_get_credentials:
3912 * @socket: a #GSocket.
3913 * @error: #GError for error reporting, or %NULL to ignore.
3915 * Returns the credentials of the foreign process connected to this
3916 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
3919 * If this operation isn't supported on the OS, the method fails with
3920 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
3921 * by reading the %SO_PEERCRED option on the underlying socket.
3923 * Other ways to obtain credentials from a foreign peer includes the
3924 * #GUnixCredentialsMessage type and
3925 * g_unix_connection_send_credentials() /
3926 * g_unix_connection_receive_credentials() functions.
3928 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
3929 * that must be freed with g_object_unref().
3934 g_socket_get_credentials (GSocket *socket,
3939 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
3940 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3944 #if defined(__linux__) || defined(__OpenBSD__)
3947 #if defined(__linux__)
3948 struct ucred native_creds;
3949 optlen = sizeof (struct ucred);
3950 #elif defined(__OpenBSD__)
3951 struct sockpeercred native_creds;
3952 optlen = sizeof (struct sockpeercred);
3954 if (getsockopt (socket->priv->fd,
3957 (void *)&native_creds,
3960 int errsv = get_socket_errno ();
3963 socket_io_error_from_errno (errsv),
3964 _("Unable to get pending error: %s"),
3965 socket_strerror (errsv));
3969 ret = g_credentials_new ();
3970 g_credentials_set_native (ret,
3971 #if defined(__linux__)
3972 G_CREDENTIALS_TYPE_LINUX_UCRED,
3973 #elif defined(__OpenBSD__)
3974 G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
3980 g_set_error_literal (error,
3982 G_IO_ERROR_NOT_SUPPORTED,
3983 _("g_socket_get_credentials not implemented for this OS"));