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));
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);
621 g_value_set_uint (value, g_socket_get_ttl (socket));
625 g_value_set_boolean (value, g_socket_get_broadcast (socket));
628 case PROP_MULTICAST_LOOPBACK:
629 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
632 case PROP_MULTICAST_TTL:
633 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
637 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
642 g_socket_set_property (GObject *object,
647 GSocket *socket = G_SOCKET (object);
652 socket->priv->family = g_value_get_enum (value);
656 socket->priv->type = g_value_get_enum (value);
660 socket->priv->protocol = g_value_get_enum (value);
664 socket->priv->fd = g_value_get_int (value);
668 g_socket_set_blocking (socket, g_value_get_boolean (value));
671 case PROP_LISTEN_BACKLOG:
672 g_socket_set_listen_backlog (socket, g_value_get_int (value));
676 g_socket_set_keepalive (socket, g_value_get_boolean (value));
680 g_socket_set_timeout (socket, g_value_get_uint (value));
684 g_socket_set_ttl (socket, g_value_get_uint (value));
688 g_socket_set_broadcast (socket, g_value_get_boolean (value));
691 case PROP_MULTICAST_LOOPBACK:
692 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
695 case PROP_MULTICAST_TTL:
696 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
700 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
705 g_socket_finalize (GObject *object)
707 GSocket *socket = G_SOCKET (object);
709 g_clear_error (&socket->priv->construct_error);
711 if (socket->priv->fd != -1 &&
712 !socket->priv->closed)
713 g_socket_close (socket, NULL);
715 if (socket->priv->remote_address)
716 g_object_unref (socket->priv->remote_address);
719 if (socket->priv->event != WSA_INVALID_EVENT)
721 WSACloseEvent (socket->priv->event);
722 socket->priv->event = WSA_INVALID_EVENT;
725 g_assert (socket->priv->requested_conditions == NULL);
728 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
729 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
733 g_socket_class_init (GSocketClass *klass)
735 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
738 /* Make sure winsock has been initialized */
739 type = g_inet_address_get_type ();
740 (type); /* To avoid -Wunused-but-set-variable */
743 /* There is no portable, thread-safe way to avoid having the process
744 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
745 * forced to simply ignore the signal process-wide.
747 signal (SIGPIPE, SIG_IGN);
750 g_type_class_add_private (klass, sizeof (GSocketPrivate));
752 gobject_class->finalize = g_socket_finalize;
753 gobject_class->constructed = g_socket_constructed;
754 gobject_class->set_property = g_socket_set_property;
755 gobject_class->get_property = g_socket_get_property;
757 g_object_class_install_property (gobject_class, PROP_FAMILY,
758 g_param_spec_enum ("family",
760 P_("The sockets address family"),
761 G_TYPE_SOCKET_FAMILY,
762 G_SOCKET_FAMILY_INVALID,
763 G_PARAM_CONSTRUCT_ONLY |
765 G_PARAM_STATIC_STRINGS));
767 g_object_class_install_property (gobject_class, PROP_TYPE,
768 g_param_spec_enum ("type",
770 P_("The sockets type"),
772 G_SOCKET_TYPE_STREAM,
773 G_PARAM_CONSTRUCT_ONLY |
775 G_PARAM_STATIC_STRINGS));
777 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
778 g_param_spec_enum ("protocol",
779 P_("Socket protocol"),
780 P_("The id of the protocol to use, or -1 for unknown"),
781 G_TYPE_SOCKET_PROTOCOL,
782 G_SOCKET_PROTOCOL_UNKNOWN,
783 G_PARAM_CONSTRUCT_ONLY |
785 G_PARAM_STATIC_STRINGS));
787 g_object_class_install_property (gobject_class, PROP_FD,
788 g_param_spec_int ("fd",
789 P_("File descriptor"),
790 P_("The sockets file descriptor"),
794 G_PARAM_CONSTRUCT_ONLY |
796 G_PARAM_STATIC_STRINGS));
798 g_object_class_install_property (gobject_class, PROP_BLOCKING,
799 g_param_spec_boolean ("blocking",
801 P_("Whether or not I/O on this socket is blocking"),
804 G_PARAM_STATIC_STRINGS));
806 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
807 g_param_spec_int ("listen-backlog",
808 P_("Listen backlog"),
809 P_("Outstanding connections in the listen queue"),
814 G_PARAM_STATIC_STRINGS));
816 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
817 g_param_spec_boolean ("keepalive",
818 P_("Keep connection alive"),
819 P_("Keep connection alive by sending periodic pings"),
822 G_PARAM_STATIC_STRINGS));
824 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
825 g_param_spec_object ("local-address",
827 P_("The local address the socket is bound to"),
828 G_TYPE_SOCKET_ADDRESS,
830 G_PARAM_STATIC_STRINGS));
832 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
833 g_param_spec_object ("remote-address",
834 P_("Remote address"),
835 P_("The remote address the socket is connected to"),
836 G_TYPE_SOCKET_ADDRESS,
838 G_PARAM_STATIC_STRINGS));
843 * The timeout in seconds on socket I/O
847 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
848 g_param_spec_uint ("timeout",
850 P_("The timeout in seconds on socket I/O"),
855 G_PARAM_STATIC_STRINGS));
860 * Whether the socket should allow sending to and receiving from broadcast addresses.
864 g_object_class_install_property (gobject_class, PROP_BROADCAST,
865 g_param_spec_boolean ("broadcast",
867 P_("Whether to allow sending to and receiving from broadcast addresses"),
870 G_PARAM_STATIC_STRINGS));
875 * Time-to-live for outgoing unicast packets
879 g_object_class_install_property (gobject_class, PROP_TTL,
880 g_param_spec_uint ("ttl",
882 P_("Time-to-live of outgoing unicast packets"),
885 G_PARAM_STATIC_STRINGS));
888 * GSocket:multicast-loopback:
890 * Whether outgoing multicast packets loop back to the local host.
894 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
895 g_param_spec_boolean ("multicast-loopback",
896 P_("Multicast loopback"),
897 P_("Whether outgoing multicast packets loop back to the local host"),
900 G_PARAM_STATIC_STRINGS));
903 * GSocket:multicast-ttl:
905 * Time-to-live out outgoing multicast packets
909 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
910 g_param_spec_uint ("multicast-ttl",
912 P_("Time-to-live of outgoing multicast packets"),
915 G_PARAM_STATIC_STRINGS));
919 g_socket_initable_iface_init (GInitableIface *iface)
921 iface->init = g_socket_initable_init;
925 g_socket_init (GSocket *socket)
927 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
929 socket->priv->fd = -1;
930 socket->priv->blocking = TRUE;
931 socket->priv->listen_backlog = 10;
932 socket->priv->construct_error = NULL;
934 socket->priv->event = WSA_INVALID_EVENT;
939 g_socket_initable_init (GInitable *initable,
940 GCancellable *cancellable,
945 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
947 socket = G_SOCKET (initable);
949 if (cancellable != NULL)
951 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
952 _("Cancellable initialization not supported"));
956 socket->priv->inited = TRUE;
958 if (socket->priv->construct_error)
961 *error = g_error_copy (socket->priv->construct_error);
971 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
972 * @type: the socket type to use.
973 * @protocol: the id of the protocol to use, or 0 for default.
974 * @error: #GError for error reporting, or %NULL to ignore.
976 * Creates a new #GSocket with the defined family, type and protocol.
977 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
978 * for the family and type is used.
980 * The @protocol is a family and type specific int that specifies what
981 * kind of protocol to use. #GSocketProtocol lists several common ones.
982 * Many families only support one protocol, and use 0 for this, others
983 * support several and using 0 means to use the default protocol for
984 * the family and type.
986 * The protocol id is passed directly to the operating
987 * system, so you can use protocols not listed in #GSocketProtocol if you
988 * know the protocol number used for it.
990 * Returns: a #GSocket or %NULL on error.
991 * Free the returned object with g_object_unref().
996 g_socket_new (GSocketFamily family,
998 GSocketProtocol protocol,
1001 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1005 "protocol", protocol,
1010 * g_socket_new_from_fd:
1011 * @fd: a native socket file descriptor.
1012 * @error: #GError for error reporting, or %NULL to ignore.
1014 * Creates a new #GSocket from a native file descriptor
1015 * or winsock SOCKET handle.
1017 * This reads all the settings from the file descriptor so that
1018 * all properties should work. Note that the file descriptor
1019 * will be set to non-blocking mode, independent on the blocking
1020 * mode of the #GSocket.
1022 * Returns: a #GSocket or %NULL on error.
1023 * Free the returned object with g_object_unref().
1028 g_socket_new_from_fd (gint fd,
1031 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1038 * g_socket_set_blocking:
1039 * @socket: a #GSocket.
1040 * @blocking: Whether to use blocking I/O or not.
1042 * Sets the blocking mode of the socket. In blocking mode
1043 * all operations block until they succeed or there is an error. In
1044 * non-blocking mode all functions return results immediately or
1045 * with a %G_IO_ERROR_WOULD_BLOCK error.
1047 * All sockets are created in blocking mode. However, note that the
1048 * platform level socket is always non-blocking, and blocking mode
1049 * is a GSocket level feature.
1054 g_socket_set_blocking (GSocket *socket,
1057 g_return_if_fail (G_IS_SOCKET (socket));
1059 blocking = !!blocking;
1061 if (socket->priv->blocking == blocking)
1064 socket->priv->blocking = blocking;
1065 g_object_notify (G_OBJECT (socket), "blocking");
1069 * g_socket_get_blocking:
1070 * @socket: a #GSocket.
1072 * Gets the blocking mode of the socket. For details on blocking I/O,
1073 * see g_socket_set_blocking().
1075 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1080 g_socket_get_blocking (GSocket *socket)
1082 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1084 return socket->priv->blocking;
1088 * g_socket_set_keepalive:
1089 * @socket: a #GSocket.
1090 * @keepalive: Value for the keepalive flag
1092 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1093 * this flag is set on a socket, the system will attempt to verify that the
1094 * remote socket endpoint is still present if a sufficiently long period of
1095 * time passes with no data being exchanged. If the system is unable to
1096 * verify the presence of the remote endpoint, it will automatically close
1099 * This option is only functional on certain kinds of sockets. (Notably,
1100 * %G_SOCKET_PROTOCOL_TCP sockets.)
1102 * The exact time between pings is system- and protocol-dependent, but will
1103 * normally be at least two hours. Most commonly, you would set this flag
1104 * on a server socket if you want to allow clients to remain idle for long
1105 * periods of time, but also want to ensure that connections are eventually
1106 * garbage-collected if clients crash or become unreachable.
1111 g_socket_set_keepalive (GSocket *socket,
1116 g_return_if_fail (G_IS_SOCKET (socket));
1118 keepalive = !!keepalive;
1119 if (socket->priv->keepalive == keepalive)
1122 value = (gint) keepalive;
1123 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1124 (gpointer) &value, sizeof (value)) < 0)
1126 int errsv = get_socket_errno ();
1127 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1131 socket->priv->keepalive = keepalive;
1132 g_object_notify (G_OBJECT (socket), "keepalive");
1136 * g_socket_get_keepalive:
1137 * @socket: a #GSocket.
1139 * Gets the keepalive mode of the socket. For details on this,
1140 * see g_socket_set_keepalive().
1142 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1147 g_socket_get_keepalive (GSocket *socket)
1149 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1151 return socket->priv->keepalive;
1155 * g_socket_get_listen_backlog:
1156 * @socket: a #GSocket.
1158 * Gets the listen backlog setting of the socket. For details on this,
1159 * see g_socket_set_listen_backlog().
1161 * Returns: the maximum number of pending connections.
1166 g_socket_get_listen_backlog (GSocket *socket)
1168 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1170 return socket->priv->listen_backlog;
1174 * g_socket_set_listen_backlog:
1175 * @socket: a #GSocket.
1176 * @backlog: the maximum number of pending connections.
1178 * Sets the maximum number of outstanding connections allowed
1179 * when listening on this socket. If more clients than this are
1180 * connecting to the socket and the application is not handling them
1181 * on time then the new connections will be refused.
1183 * Note that this must be called before g_socket_listen() and has no
1184 * effect if called after that.
1189 g_socket_set_listen_backlog (GSocket *socket,
1192 g_return_if_fail (G_IS_SOCKET (socket));
1193 g_return_if_fail (!socket->priv->listening);
1195 if (backlog != socket->priv->listen_backlog)
1197 socket->priv->listen_backlog = backlog;
1198 g_object_notify (G_OBJECT (socket), "listen-backlog");
1203 * g_socket_get_timeout:
1204 * @socket: a #GSocket.
1206 * Gets the timeout setting of the socket. For details on this, see
1207 * g_socket_set_timeout().
1209 * Returns: the timeout in seconds
1214 g_socket_get_timeout (GSocket *socket)
1216 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1218 return socket->priv->timeout;
1222 * g_socket_set_timeout:
1223 * @socket: a #GSocket.
1224 * @timeout: the timeout for @socket, in seconds, or 0 for none
1226 * Sets the time in seconds after which I/O operations on @socket will
1227 * time out if they have not yet completed.
1229 * On a blocking socket, this means that any blocking #GSocket
1230 * operation will time out after @timeout seconds of inactivity,
1231 * returning %G_IO_ERROR_TIMED_OUT.
1233 * On a non-blocking socket, calls to g_socket_condition_wait() will
1234 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1235 * created with g_socket_create_source() will trigger after
1236 * @timeout seconds of inactivity, with the requested condition
1237 * set, at which point calling g_socket_receive(), g_socket_send(),
1238 * g_socket_check_connect_result(), etc, will fail with
1239 * %G_IO_ERROR_TIMED_OUT.
1241 * If @timeout is 0 (the default), operations will never time out
1244 * Note that if an I/O operation is interrupted by a signal, this may
1245 * cause the timeout to be reset.
1250 g_socket_set_timeout (GSocket *socket,
1253 g_return_if_fail (G_IS_SOCKET (socket));
1255 if (timeout != socket->priv->timeout)
1257 socket->priv->timeout = timeout;
1258 g_object_notify (G_OBJECT (socket), "timeout");
1264 * @socket: a #GSocket.
1266 * Gets the unicast time-to-live setting on @socket; see
1267 * g_socket_set_ttl() for more details.
1269 * Returns: the time-to-live setting on @socket
1274 g_socket_get_ttl (GSocket *socket)
1277 guint value, optlen;
1279 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1281 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1285 optlen = sizeof (optval);
1286 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_TTL,
1290 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1292 optlen = sizeof (value);
1293 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1297 g_return_val_if_reached (FALSE);
1301 int errsv = get_socket_errno ();
1302 g_warning ("error getting unicast ttl: %s", socket_strerror (errsv));
1311 * @socket: a #GSocket.
1312 * @ttl: the time-to-live value for all unicast packets on @socket
1314 * Sets the time-to-live for outgoing unicast packets on @socket.
1315 * By default the platform-specific default value is used.
1320 g_socket_set_ttl (GSocket *socket,
1325 g_return_if_fail (G_IS_SOCKET (socket));
1327 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1329 guchar optval = (guchar)ttl;
1331 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_TTL,
1332 &optval, sizeof (optval));
1334 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1336 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1337 &ttl, sizeof (ttl));
1340 g_return_if_reached ();
1344 int errsv = get_socket_errno ();
1345 g_warning ("error setting unicast ttl: %s", socket_strerror (errsv));
1349 g_object_notify (G_OBJECT (socket), "ttl");
1353 * g_socket_get_broadcast:
1354 * @socket: a #GSocket.
1356 * Gets the broadcast setting on @socket; if %TRUE,
1357 * it is possible to send packets to broadcast
1358 * addresses or receive from broadcast addresses.
1360 * Returns: the broadcast setting on @socket
1365 g_socket_get_broadcast (GSocket *socket)
1368 guint value = 0, optlen;
1370 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1372 optlen = sizeof (guchar);
1373 result = getsockopt (socket->priv->fd, SOL_SOCKET, SO_BROADCAST,
1378 int errsv = get_socket_errno ();
1379 g_warning ("error getting broadcast: %s", socket_strerror (errsv));
1387 * g_socket_set_broadcast:
1388 * @socket: a #GSocket.
1389 * @loopback: whether @socket should allow sending to and receiving
1390 * from broadcast addresses
1392 * Sets whether @socket should allow sending to and receiving from
1393 * broadcast addresses. This is %FALSE by default.
1398 g_socket_set_broadcast (GSocket *socket,
1404 g_return_if_fail (G_IS_SOCKET (socket));
1406 broadcast = !!broadcast;
1407 value = (guchar)broadcast;
1409 result = setsockopt (socket->priv->fd, SOL_SOCKET, SO_BROADCAST,
1410 &value, sizeof (value));
1414 int errsv = get_socket_errno ();
1415 g_warning ("error setting broadcast: %s", socket_strerror (errsv));
1419 g_object_notify (G_OBJECT (socket), "broadcast");
1423 * g_socket_get_multicast_loopback:
1424 * @socket: a #GSocket.
1426 * Gets the multicast loopback setting on @socket; if %TRUE (the
1427 * default), outgoing multicast packets will be looped back to
1428 * multicast listeners on the same host.
1430 * Returns: the multicast loopback setting on @socket
1435 g_socket_get_multicast_loopback (GSocket *socket)
1438 guint value = 0, optlen;
1440 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1442 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1444 optlen = sizeof (guchar);
1445 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1448 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1450 optlen = sizeof (guint);
1451 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1455 g_return_val_if_reached (FALSE);
1459 int errsv = get_socket_errno ();
1460 g_warning ("error getting multicast loopback: %s", socket_strerror (errsv));
1468 * g_socket_set_multicast_loopback:
1469 * @socket: a #GSocket.
1470 * @loopback: whether @socket should receive messages sent to its
1471 * multicast groups from the local host
1473 * Sets whether outgoing multicast packets will be received by sockets
1474 * listening on that multicast address on the same host. This is %TRUE
1480 g_socket_set_multicast_loopback (GSocket *socket,
1485 g_return_if_fail (G_IS_SOCKET (socket));
1487 loopback = !!loopback;
1489 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1491 guchar value = (guchar)loopback;
1493 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1494 &value, sizeof (value));
1496 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1498 guint value = (guint)loopback;
1500 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1501 &value, sizeof (value));
1504 g_return_if_reached ();
1508 int errsv = get_socket_errno ();
1509 g_warning ("error setting multicast loopback: %s", socket_strerror (errsv));
1513 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1517 * g_socket_get_multicast_ttl:
1518 * @socket: a #GSocket.
1520 * Gets the multicast time-to-live setting on @socket; see
1521 * g_socket_set_multicast_ttl() for more details.
1523 * Returns: the multicast time-to-live setting on @socket
1528 g_socket_get_multicast_ttl (GSocket *socket)
1531 guint value, optlen;
1533 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1535 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1539 optlen = sizeof (optval);
1540 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1544 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1546 optlen = sizeof (value);
1547 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1551 g_return_val_if_reached (FALSE);
1555 int errsv = get_socket_errno ();
1556 g_warning ("error getting multicast ttl: %s", socket_strerror (errsv));
1564 * g_socket_set_multicast_ttl:
1565 * @socket: a #GSocket.
1566 * @ttl: the time-to-live value for all multicast datagrams on @socket
1568 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1569 * By default, this is 1, meaning that multicast packets will not leave
1570 * the local network.
1575 g_socket_set_multicast_ttl (GSocket *socket,
1580 g_return_if_fail (G_IS_SOCKET (socket));
1582 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1584 guchar optval = (guchar)ttl;
1586 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1587 &optval, sizeof (optval));
1589 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1591 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1592 &ttl, sizeof (ttl));
1595 g_return_if_reached ();
1599 int errsv = get_socket_errno ();
1600 g_warning ("error setting multicast ttl: %s", socket_strerror (errsv));
1604 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1608 * g_socket_get_family:
1609 * @socket: a #GSocket.
1611 * Gets the socket family of the socket.
1613 * Returns: a #GSocketFamily
1618 g_socket_get_family (GSocket *socket)
1620 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1622 return socket->priv->family;
1626 * g_socket_get_socket_type:
1627 * @socket: a #GSocket.
1629 * Gets the socket type of the socket.
1631 * Returns: a #GSocketType
1636 g_socket_get_socket_type (GSocket *socket)
1638 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1640 return socket->priv->type;
1644 * g_socket_get_protocol:
1645 * @socket: a #GSocket.
1647 * Gets the socket protocol id the socket was created with.
1648 * In case the protocol is unknown, -1 is returned.
1650 * Returns: a protocol id, or -1 if unknown
1655 g_socket_get_protocol (GSocket *socket)
1657 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1659 return socket->priv->protocol;
1664 * @socket: a #GSocket.
1666 * Returns the underlying OS socket object. On unix this
1667 * is a socket file descriptor, and on windows this is
1668 * a Winsock2 SOCKET handle. This may be useful for
1669 * doing platform specific or otherwise unusual operations
1672 * Returns: the file descriptor of the socket.
1677 g_socket_get_fd (GSocket *socket)
1679 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1681 return socket->priv->fd;
1685 * g_socket_get_local_address:
1686 * @socket: a #GSocket.
1687 * @error: #GError for error reporting, or %NULL to ignore.
1689 * Try to get the local address of a bound socket. This is only
1690 * useful if the socket has been bound to a local address,
1691 * either explicitly or implicitly when connecting.
1693 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1694 * Free the returned object with g_object_unref().
1699 g_socket_get_local_address (GSocket *socket,
1702 struct sockaddr_storage buffer;
1703 guint32 len = sizeof (buffer);
1705 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1707 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1709 int errsv = get_socket_errno ();
1710 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1711 _("could not get local address: %s"), socket_strerror (errsv));
1715 return g_socket_address_new_from_native (&buffer, len);
1719 * g_socket_get_remote_address:
1720 * @socket: a #GSocket.
1721 * @error: #GError for error reporting, or %NULL to ignore.
1723 * Try to get the remove address of a connected socket. This is only
1724 * useful for connection oriented sockets that have been connected.
1726 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1727 * Free the returned object with g_object_unref().
1732 g_socket_get_remote_address (GSocket *socket,
1735 struct sockaddr_storage buffer;
1736 guint32 len = sizeof (buffer);
1738 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1740 if (socket->priv->connect_pending)
1742 if (!g_socket_check_connect_result (socket, error))
1745 socket->priv->connect_pending = FALSE;
1748 if (!socket->priv->remote_address)
1750 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1752 int errsv = get_socket_errno ();
1753 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1754 _("could not get remote address: %s"), socket_strerror (errsv));
1758 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1761 return g_object_ref (socket->priv->remote_address);
1765 * g_socket_is_connected:
1766 * @socket: a #GSocket.
1768 * Check whether the socket is connected. This is only useful for
1769 * connection-oriented sockets.
1771 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1776 g_socket_is_connected (GSocket *socket)
1778 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1780 return socket->priv->connected;
1785 * @socket: a #GSocket.
1786 * @error: #GError for error reporting, or %NULL to ignore.
1788 * Marks the socket as a server socket, i.e. a socket that is used
1789 * to accept incoming requests using g_socket_accept().
1791 * Before calling this the socket must be bound to a local address using
1794 * To set the maximum amount of outstanding clients, use
1795 * g_socket_set_listen_backlog().
1797 * Returns: %TRUE on success, %FALSE on error.
1802 g_socket_listen (GSocket *socket,
1805 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1807 if (!check_socket (socket, error))
1810 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1812 int errsv = get_socket_errno ();
1814 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1815 _("could not listen: %s"), socket_strerror (errsv));
1819 socket->priv->listening = TRUE;
1826 * @socket: a #GSocket.
1827 * @address: a #GSocketAddress specifying the local address.
1828 * @allow_reuse: whether to allow reusing this address
1829 * @error: #GError for error reporting, or %NULL to ignore.
1831 * When a socket is created it is attached to an address family, but it
1832 * doesn't have an address in this family. g_socket_bind() assigns the
1833 * address (sometimes called name) of the socket.
1835 * It is generally required to bind to a local address before you can
1836 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1837 * In certain situations, you may also want to bind a socket that will be
1838 * used to initiate connections, though this is not normally required.
1840 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1841 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1842 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1843 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1844 * that address was previously used by another socket that has not yet been
1845 * fully cleaned-up by the kernel. Failing to set this flag on a server
1846 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1847 * the server program is stopped and then immediately restarted.)
1849 * Returns: %TRUE on success, %FALSE on error.
1854 g_socket_bind (GSocket *socket,
1855 GSocketAddress *address,
1856 gboolean reuse_address,
1859 struct sockaddr_storage addr;
1861 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1863 if (!check_socket (socket, error))
1866 /* SO_REUSEADDR on windows means something else and is not what we want.
1867 It always allows the unix variant of SO_REUSEADDR anyway */
1872 value = (int) !!reuse_address;
1873 /* Ignore errors here, the only likely error is "not supported", and
1874 this is a "best effort" thing mainly */
1875 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1876 (gpointer) &value, sizeof (value));
1880 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1883 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1884 g_socket_address_get_native_size (address)) < 0)
1886 int errsv = get_socket_errno ();
1888 G_IO_ERROR, socket_io_error_from_errno (errsv),
1889 _("Error binding to address: %s"), socket_strerror (errsv));
1897 g_socket_multicast_group_operation (GSocket *socket,
1898 GInetAddress *group,
1899 gboolean source_specific,
1900 const gchar *interface,
1901 gboolean join_group,
1904 const guint8 *native_addr;
1905 gint optname, result;
1907 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1908 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
1909 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
1910 g_return_val_if_fail (g_inet_address_get_family (group) == socket->priv->family, FALSE);
1912 if (!check_socket (socket, error))
1915 native_addr = g_inet_address_to_bytes (group);
1916 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1918 #ifdef HAVE_IP_MREQN
1919 struct ip_mreqn mc_req;
1921 struct ip_mreq mc_req;
1924 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
1926 #ifdef HAVE_IP_MREQN
1928 mc_req.imr_ifindex = if_nametoindex (interface);
1930 mc_req.imr_ifindex = 0; /* Pick any. */
1932 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
1935 if (source_specific)
1936 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
1938 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
1939 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
1940 &mc_req, sizeof (mc_req));
1942 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1944 struct ipv6_mreq mc_req_ipv6;
1946 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
1948 mc_req_ipv6.ipv6mr_interface = if_nametoindex (interface);
1950 mc_req_ipv6.ipv6mr_interface = 0;
1952 optname = join_group ? IPV6_ADD_MEMBERSHIP : IPV6_DROP_MEMBERSHIP;
1953 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
1954 &mc_req_ipv6, sizeof (mc_req_ipv6));
1957 g_return_val_if_reached (FALSE);
1961 int errsv = get_socket_errno ();
1963 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1965 _("Error joining multicast group: %s") :
1966 _("Error leaving multicast group: %s"),
1967 socket_strerror (errsv));
1975 * g_socket_join_multicast_group:
1976 * @socket: a #GSocket.
1977 * @group: a #GInetAddress specifying the group address to join.
1978 * @interface: Interface to use
1979 * @source_specific: %TRUE if source-specific multicast should be used
1980 * @error: #GError for error reporting, or %NULL to ignore.
1982 * Registers @socket to receive multicast messages sent to @group.
1983 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
1984 * been bound to an appropriate interface and port with
1987 * If @source_specific is %TRUE, source-specific multicast as defined
1988 * in RFC 4604 is used.
1990 * Returns: %TRUE on success, %FALSE on error.
1995 g_socket_join_multicast_group (GSocket *socket,
1996 GInetAddress *group,
1997 gboolean source_specific,
1998 const gchar *interface,
2001 return g_socket_multicast_group_operation (socket, group, source_specific, interface, TRUE, error);
2005 * g_socket_leave_multicast_group:
2006 * @socket: a #GSocket.
2007 * @group: a #GInetAddress specifying the group address to leave.
2008 * @interface: Interface to use
2009 * @source_specific: %TRUE if source-specific multicast should be used
2010 * @error: #GError for error reporting, or %NULL to ignore.
2012 * Removes @socket from the multicast group @group (while still
2013 * allowing it to receive unicast messages).
2015 * If @source_specific is %TRUE, source-specific multicast as defined
2016 * in RFC 4604 is used.
2018 * Returns: %TRUE on success, %FALSE on error.
2023 g_socket_leave_multicast_group (GSocket *socket,
2024 GInetAddress *group,
2025 gboolean source_specific,
2026 const gchar *interface,
2029 return g_socket_multicast_group_operation (socket, group, source_specific, interface, FALSE, error);
2033 * g_socket_speaks_ipv4:
2034 * @socket: a #GSocket
2036 * Checks if a socket is capable of speaking IPv4.
2038 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2039 * and under some combinations of circumstances IPv6 sockets are also
2040 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2043 * No other types of sockets are currently considered as being capable
2046 * Returns: %TRUE if this socket can be used with IPv4.
2051 g_socket_speaks_ipv4 (GSocket *socket)
2053 switch (socket->priv->family)
2055 case G_SOCKET_FAMILY_IPV4:
2058 case G_SOCKET_FAMILY_IPV6:
2059 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2061 guint sizeof_int = sizeof (int);
2064 if (getsockopt (socket->priv->fd,
2065 IPPROTO_IPV6, IPV6_V6ONLY,
2066 &v6_only, &sizeof_int) != 0)
2082 * @socket: a #GSocket.
2083 * @cancellable: (allow-none): a %GCancellable or %NULL
2084 * @error: #GError for error reporting, or %NULL to ignore.
2086 * Accept incoming connections on a connection-based socket. This removes
2087 * the first outstanding connection request from the listening socket and
2088 * creates a #GSocket object for it.
2090 * The @socket must be bound to a local address with g_socket_bind() and
2091 * must be listening for incoming connections (g_socket_listen()).
2093 * If there are no outstanding connections then the operation will block
2094 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2095 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2097 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2098 * Free the returned object with g_object_unref().
2103 g_socket_accept (GSocket *socket,
2104 GCancellable *cancellable,
2107 GSocket *new_socket;
2110 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2112 if (!check_socket (socket, error))
2117 if (socket->priv->blocking &&
2118 !g_socket_condition_wait (socket,
2119 G_IO_IN, cancellable, error))
2122 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2124 int errsv = get_socket_errno ();
2126 win32_unset_event_mask (socket, FD_ACCEPT);
2131 if (socket->priv->blocking)
2133 #ifdef WSAEWOULDBLOCK
2134 if (errsv == WSAEWOULDBLOCK)
2137 if (errsv == EWOULDBLOCK ||
2143 g_set_error (error, G_IO_ERROR,
2144 socket_io_error_from_errno (errsv),
2145 _("Error accepting connection: %s"), socket_strerror (errsv));
2151 win32_unset_event_mask (socket, FD_ACCEPT);
2155 /* The socket inherits the accepting sockets event mask and even object,
2156 we need to remove that */
2157 WSAEventSelect (ret, NULL, 0);
2163 /* We always want to set close-on-exec to protect users. If you
2164 need to so some weird inheritance to exec you can re-enable this
2165 using lower level hacks with g_socket_get_fd(). */
2166 flags = fcntl (ret, F_GETFD, 0);
2168 (flags & FD_CLOEXEC) == 0)
2170 flags |= FD_CLOEXEC;
2171 fcntl (ret, F_SETFD, flags);
2176 new_socket = g_socket_new_from_fd (ret, error);
2177 if (new_socket == NULL)
2186 new_socket->priv->protocol = socket->priv->protocol;
2193 * @socket: a #GSocket.
2194 * @address: a #GSocketAddress specifying the remote address.
2195 * @cancellable: (allow-none): a %GCancellable or %NULL
2196 * @error: #GError for error reporting, or %NULL to ignore.
2198 * Connect the socket to the specified remote address.
2200 * For connection oriented socket this generally means we attempt to make
2201 * a connection to the @address. For a connection-less socket it sets
2202 * the default address for g_socket_send() and discards all incoming datagrams
2203 * from other sources.
2205 * Generally connection oriented sockets can only connect once, but
2206 * connection-less sockets can connect multiple times to change the
2209 * If the connect call needs to do network I/O it will block, unless
2210 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2211 * and the user can be notified of the connection finishing by waiting
2212 * for the G_IO_OUT condition. The result of the connection must then be
2213 * checked with g_socket_check_connect_result().
2215 * Returns: %TRUE if connected, %FALSE on error.
2220 g_socket_connect (GSocket *socket,
2221 GSocketAddress *address,
2222 GCancellable *cancellable,
2225 struct sockaddr_storage buffer;
2227 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2229 if (!check_socket (socket, error))
2232 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2235 if (socket->priv->remote_address)
2236 g_object_unref (socket->priv->remote_address);
2237 socket->priv->remote_address = g_object_ref (address);
2241 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2242 g_socket_address_get_native_size (address)) < 0)
2244 int errsv = get_socket_errno ();
2250 if (errsv == EINPROGRESS)
2252 if (errsv == WSAEWOULDBLOCK)
2255 if (socket->priv->blocking)
2257 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2259 if (g_socket_check_connect_result (socket, error))
2265 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2266 _("Connection in progress"));
2267 socket->priv->connect_pending = TRUE;
2271 g_set_error_literal (error, G_IO_ERROR,
2272 socket_io_error_from_errno (errsv),
2273 socket_strerror (errsv));
2280 win32_unset_event_mask (socket, FD_CONNECT);
2282 socket->priv->connected = TRUE;
2288 * g_socket_check_connect_result:
2289 * @socket: a #GSocket
2290 * @error: #GError for error reporting, or %NULL to ignore.
2292 * Checks and resets the pending connect error for the socket.
2293 * This is used to check for errors when g_socket_connect() is
2294 * used in non-blocking mode.
2296 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2301 g_socket_check_connect_result (GSocket *socket,
2307 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2309 if (!check_socket (socket, error))
2312 optlen = sizeof (value);
2313 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
2315 int errsv = get_socket_errno ();
2317 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2318 _("Unable to get pending error: %s"), socket_strerror (errsv));
2324 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2325 socket_strerror (value));
2326 if (socket->priv->remote_address)
2328 g_object_unref (socket->priv->remote_address);
2329 socket->priv->remote_address = NULL;
2334 socket->priv->connected = TRUE;
2340 * @socket: a #GSocket
2341 * @buffer: a buffer to read data into (which should be at least @size
2343 * @size: the number of bytes you want to read from the socket
2344 * @cancellable: (allow-none): a %GCancellable or %NULL
2345 * @error: #GError for error reporting, or %NULL to ignore.
2347 * Receive data (up to @size bytes) from a socket. This is mainly used by
2348 * connection-oriented sockets; it is identical to g_socket_receive_from()
2349 * with @address set to %NULL.
2351 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2352 * g_socket_receive() will always read either 0 or 1 complete messages from
2353 * the socket. If the received message is too large to fit in @buffer, then
2354 * the data beyond @size bytes will be discarded, without any explicit
2355 * indication that this has occurred.
2357 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2358 * number of bytes, up to @size. If more than @size bytes have been
2359 * received, the additional data will be returned in future calls to
2360 * g_socket_receive().
2362 * If the socket is in blocking mode the call will block until there
2363 * is some data to receive, the connection is closed, or there is an
2364 * error. If there is no data available and the socket is in
2365 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2366 * returned. To be notified when data is available, wait for the
2367 * %G_IO_IN condition.
2369 * On error -1 is returned and @error is set accordingly.
2371 * Returns: Number of bytes read, or 0 if the connection was closed by
2372 * the peer, or -1 on error
2377 g_socket_receive (GSocket *socket,
2380 GCancellable *cancellable,
2383 return g_socket_receive_with_blocking (socket, buffer, size,
2384 socket->priv->blocking,
2385 cancellable, error);
2389 * g_socket_receive_with_blocking:
2390 * @socket: a #GSocket
2391 * @buffer: a buffer to read data into (which should be at least @size
2393 * @size: the number of bytes you want to read from the socket
2394 * @blocking: whether to do blocking or non-blocking I/O
2395 * @cancellable: (allow-none): a %GCancellable or %NULL
2396 * @error: #GError for error reporting, or %NULL to ignore.
2398 * This behaves exactly the same as g_socket_receive(), except that
2399 * the choice of blocking or non-blocking behavior is determined by
2400 * the @blocking argument rather than by @socket's properties.
2402 * Returns: Number of bytes read, or 0 if the connection was closed by
2403 * the peer, or -1 on error
2408 g_socket_receive_with_blocking (GSocket *socket,
2412 GCancellable *cancellable,
2417 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2419 if (!check_socket (socket, error))
2422 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2428 !g_socket_condition_wait (socket,
2429 G_IO_IN, cancellable, error))
2432 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2434 int errsv = get_socket_errno ();
2441 #ifdef WSAEWOULDBLOCK
2442 if (errsv == WSAEWOULDBLOCK)
2445 if (errsv == EWOULDBLOCK ||
2451 win32_unset_event_mask (socket, FD_READ);
2453 g_set_error (error, G_IO_ERROR,
2454 socket_io_error_from_errno (errsv),
2455 _("Error receiving data: %s"), socket_strerror (errsv));
2459 win32_unset_event_mask (socket, FD_READ);
2468 * g_socket_receive_from:
2469 * @socket: a #GSocket
2470 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2472 * @buffer: (array length=size) (element-type guint8): a buffer to
2473 * read data into (which should be at least @size bytes long).
2474 * @size: the number of bytes you want to read from the socket
2475 * @cancellable: (allow-none): a %GCancellable or %NULL
2476 * @error: #GError for error reporting, or %NULL to ignore.
2478 * Receive data (up to @size bytes) from a socket.
2480 * If @address is non-%NULL then @address will be set equal to the
2481 * source address of the received packet.
2482 * @address is owned by the caller.
2484 * See g_socket_receive() for additional information.
2486 * Returns: Number of bytes read, or 0 if the connection was closed by
2487 * the peer, or -1 on error
2492 g_socket_receive_from (GSocket *socket,
2493 GSocketAddress **address,
2496 GCancellable *cancellable,
2504 return g_socket_receive_message (socket,
2512 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2513 * one, which can be confusing and annoying. So if possible, we want
2514 * to suppress the signal entirely.
2517 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2519 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2524 * @socket: a #GSocket
2525 * @buffer: (array length=size) (element-type guint8): the buffer
2526 * containing the data to send.
2527 * @size: the number of bytes to send
2528 * @cancellable: (allow-none): a %GCancellable or %NULL
2529 * @error: #GError for error reporting, or %NULL to ignore.
2531 * Tries to send @size bytes from @buffer on the socket. This is
2532 * mainly used by connection-oriented sockets; it is identical to
2533 * g_socket_send_to() with @address set to %NULL.
2535 * If the socket is in blocking mode the call will block until there is
2536 * space for the data in the socket queue. If there is no space available
2537 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2538 * will be returned. To be notified when space is available, wait for the
2539 * %G_IO_OUT condition. Note though that you may still receive
2540 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2541 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2542 * very common due to the way the underlying APIs work.)
2544 * On error -1 is returned and @error is set accordingly.
2546 * Returns: Number of bytes written (which may be less than @size), or -1
2552 g_socket_send (GSocket *socket,
2553 const gchar *buffer,
2555 GCancellable *cancellable,
2558 return g_socket_send_with_blocking (socket, buffer, size,
2559 socket->priv->blocking,
2560 cancellable, error);
2564 * g_socket_send_with_blocking:
2565 * @socket: a #GSocket
2566 * @buffer: (array length=size) (element-type guint8): the buffer
2567 * containing the data to send.
2568 * @size: the number of bytes to send
2569 * @blocking: whether to do blocking or non-blocking I/O
2570 * @cancellable: (allow-none): a %GCancellable or %NULL
2571 * @error: #GError for error reporting, or %NULL to ignore.
2573 * This behaves exactly the same as g_socket_send(), except that
2574 * the choice of blocking or non-blocking behavior is determined by
2575 * the @blocking argument rather than by @socket's properties.
2577 * Returns: Number of bytes written (which may be less than @size), or -1
2583 g_socket_send_with_blocking (GSocket *socket,
2584 const gchar *buffer,
2587 GCancellable *cancellable,
2592 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2594 if (!check_socket (socket, error))
2597 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2603 !g_socket_condition_wait (socket,
2604 G_IO_OUT, cancellable, error))
2607 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2609 int errsv = get_socket_errno ();
2614 #ifdef WSAEWOULDBLOCK
2615 if (errsv == WSAEWOULDBLOCK)
2616 win32_unset_event_mask (socket, FD_WRITE);
2621 #ifdef WSAEWOULDBLOCK
2622 if (errsv == WSAEWOULDBLOCK)
2625 if (errsv == EWOULDBLOCK ||
2631 g_set_error (error, G_IO_ERROR,
2632 socket_io_error_from_errno (errsv),
2633 _("Error sending data: %s"), socket_strerror (errsv));
2644 * @socket: a #GSocket
2645 * @address: a #GSocketAddress, or %NULL
2646 * @buffer: (array length=size) (element-type guint8): the buffer
2647 * containing the data to send.
2648 * @size: the number of bytes to send
2649 * @cancellable: (allow-none): a %GCancellable or %NULL
2650 * @error: #GError for error reporting, or %NULL to ignore.
2652 * Tries to send @size bytes from @buffer to @address. If @address is
2653 * %NULL then the message is sent to the default receiver (set by
2654 * g_socket_connect()).
2656 * See g_socket_send() for additional information.
2658 * Returns: Number of bytes written (which may be less than @size), or -1
2664 g_socket_send_to (GSocket *socket,
2665 GSocketAddress *address,
2666 const gchar *buffer,
2668 GCancellable *cancellable,
2676 return g_socket_send_message (socket,
2686 * g_socket_shutdown:
2687 * @socket: a #GSocket
2688 * @shutdown_read: whether to shut down the read side
2689 * @shutdown_write: whether to shut down the write side
2690 * @error: #GError for error reporting, or %NULL to ignore.
2692 * Shut down part of a full-duplex connection.
2694 * If @shutdown_read is %TRUE then the receiving side of the connection
2695 * is shut down, and further reading is disallowed.
2697 * If @shutdown_write is %TRUE then the sending side of the connection
2698 * is shut down, and further writing is disallowed.
2700 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2702 * One example where this is used is graceful disconnect for TCP connections
2703 * where you close the sending side, then wait for the other side to close
2704 * the connection, thus ensuring that the other side saw all sent data.
2706 * Returns: %TRUE on success, %FALSE on error
2711 g_socket_shutdown (GSocket *socket,
2712 gboolean shutdown_read,
2713 gboolean shutdown_write,
2718 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2720 if (!check_socket (socket, error))
2724 if (!shutdown_read && !shutdown_write)
2728 if (shutdown_read && shutdown_write)
2730 else if (shutdown_read)
2735 if (shutdown_read && shutdown_write)
2737 else if (shutdown_read)
2743 if (shutdown (socket->priv->fd, how) != 0)
2745 int errsv = get_socket_errno ();
2746 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2747 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2751 if (shutdown_read && shutdown_write)
2752 socket->priv->connected = FALSE;
2759 * @socket: a #GSocket
2760 * @error: #GError for error reporting, or %NULL to ignore.
2762 * Closes the socket, shutting down any active connection.
2764 * Closing a socket does not wait for all outstanding I/O operations
2765 * to finish, so the caller should not rely on them to be guaranteed
2766 * to complete even if the close returns with no error.
2768 * Once the socket is closed, all other operations will return
2769 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2772 * Sockets will be automatically closed when the last reference
2773 * is dropped, but you might want to call this function to make sure
2774 * resources are released as early as possible.
2776 * Beware that due to the way that TCP works, it is possible for
2777 * recently-sent data to be lost if either you close a socket while the
2778 * %G_IO_IN condition is set, or else if the remote connection tries to
2779 * send something to you after you close the socket but before it has
2780 * finished reading all of the data you sent. There is no easy generic
2781 * way to avoid this problem; the easiest fix is to design the network
2782 * protocol such that the client will never send data "out of turn".
2783 * Another solution is for the server to half-close the connection by
2784 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2785 * and then wait for the client to notice this and close its side of the
2786 * connection, after which the server can safely call g_socket_close().
2787 * (This is what #GTcpConnection does if you call
2788 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2789 * only works if the client will close its connection after the server
2792 * Returns: %TRUE on success, %FALSE on error
2797 g_socket_close (GSocket *socket,
2802 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2804 if (socket->priv->closed)
2805 return TRUE; /* Multiple close not an error */
2807 if (!check_socket (socket, error))
2813 res = closesocket (socket->priv->fd);
2815 res = close (socket->priv->fd);
2819 int errsv = get_socket_errno ();
2824 g_set_error (error, G_IO_ERROR,
2825 socket_io_error_from_errno (errsv),
2826 _("Error closing socket: %s"),
2827 socket_strerror (errsv));
2833 socket->priv->connected = FALSE;
2834 socket->priv->closed = TRUE;
2835 if (socket->priv->remote_address)
2837 g_object_unref (socket->priv->remote_address);
2838 socket->priv->remote_address = NULL;
2845 * g_socket_is_closed:
2846 * @socket: a #GSocket
2848 * Checks whether a socket is closed.
2850 * Returns: %TRUE if socket is closed, %FALSE otherwise
2855 g_socket_is_closed (GSocket *socket)
2857 return socket->priv->closed;
2861 /* Broken source, used on errors */
2863 broken_prepare (GSource *source,
2870 broken_check (GSource *source)
2876 broken_dispatch (GSource *source,
2877 GSourceFunc callback,
2883 static GSourceFuncs broken_funcs =
2892 network_events_for_condition (GIOCondition condition)
2896 if (condition & G_IO_IN)
2897 event_mask |= (FD_READ | FD_ACCEPT);
2898 if (condition & G_IO_OUT)
2899 event_mask |= (FD_WRITE | FD_CONNECT);
2900 event_mask |= FD_CLOSE;
2906 ensure_event (GSocket *socket)
2908 if (socket->priv->event == WSA_INVALID_EVENT)
2909 socket->priv->event = WSACreateEvent();
2913 update_select_events (GSocket *socket)
2920 ensure_event (socket);
2923 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2926 event_mask |= network_events_for_condition (*ptr);
2929 if (event_mask != socket->priv->selected_events)
2931 /* If no events selected, disable event so we can unset
2934 if (event_mask == 0)
2937 event = socket->priv->event;
2939 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2940 socket->priv->selected_events = event_mask;
2945 add_condition_watch (GSocket *socket,
2946 GIOCondition *condition)
2948 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2950 socket->priv->requested_conditions =
2951 g_list_prepend (socket->priv->requested_conditions, condition);
2953 update_select_events (socket);
2957 remove_condition_watch (GSocket *socket,
2958 GIOCondition *condition)
2960 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2962 socket->priv->requested_conditions =
2963 g_list_remove (socket->priv->requested_conditions, condition);
2965 update_select_events (socket);
2969 update_condition (GSocket *socket)
2971 WSANETWORKEVENTS events;
2972 GIOCondition condition;
2974 if (WSAEnumNetworkEvents (socket->priv->fd,
2975 socket->priv->event,
2978 socket->priv->current_events |= events.lNetworkEvents;
2979 if (events.lNetworkEvents & FD_WRITE &&
2980 events.iErrorCode[FD_WRITE_BIT] != 0)
2981 socket->priv->current_errors |= FD_WRITE;
2982 if (events.lNetworkEvents & FD_CONNECT &&
2983 events.iErrorCode[FD_CONNECT_BIT] != 0)
2984 socket->priv->current_errors |= FD_CONNECT;
2988 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2989 condition |= G_IO_IN;
2991 if (socket->priv->current_events & FD_CLOSE ||
2992 socket->priv->closed)
2993 condition |= G_IO_HUP;
2995 /* Never report both G_IO_OUT and HUP, these are
2996 mutually exclusive (can't write to a closed socket) */
2997 if ((condition & G_IO_HUP) == 0 &&
2998 socket->priv->current_events & FD_WRITE)
3000 if (socket->priv->current_errors & FD_WRITE)
3001 condition |= G_IO_ERR;
3003 condition |= G_IO_OUT;
3007 if (socket->priv->current_events & FD_CONNECT)
3009 if (socket->priv->current_errors & FD_CONNECT)
3010 condition |= (G_IO_HUP | G_IO_ERR);
3012 condition |= G_IO_OUT;
3024 GIOCondition condition;
3025 GCancellable *cancellable;
3026 GPollFD cancel_pollfd;
3027 gint64 timeout_time;
3031 socket_source_prepare (GSource *source,
3034 GSocketSource *socket_source = (GSocketSource *)source;
3036 if (g_cancellable_is_cancelled (socket_source->cancellable))
3039 if (socket_source->timeout_time)
3043 now = g_source_get_time (source);
3044 /* Round up to ensure that we don't try again too early */
3045 *timeout = (socket_source->timeout_time - now + 999) / 1000;
3048 socket_source->socket->priv->timed_out = TRUE;
3057 socket_source->pollfd.revents = update_condition (socket_source->socket);
3060 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
3067 socket_source_check (GSource *source)
3071 return socket_source_prepare (source, &timeout);
3075 socket_source_dispatch (GSource *source,
3076 GSourceFunc callback,
3079 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3080 GSocketSource *socket_source = (GSocketSource *)source;
3083 socket_source->pollfd.revents = update_condition (socket_source->socket);
3085 if (socket_source->socket->priv->timed_out)
3086 socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
3088 return (*func) (socket_source->socket,
3089 socket_source->pollfd.revents & socket_source->condition,
3094 socket_source_finalize (GSource *source)
3096 GSocketSource *socket_source = (GSocketSource *)source;
3099 socket = socket_source->socket;
3102 remove_condition_watch (socket, &socket_source->condition);
3105 g_object_unref (socket);
3107 if (socket_source->cancellable)
3109 g_cancellable_release_fd (socket_source->cancellable);
3110 g_object_unref (socket_source->cancellable);
3115 socket_source_closure_callback (GSocket *socket,
3116 GIOCondition condition,
3119 GClosure *closure = data;
3121 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3122 GValue result_value = G_VALUE_INIT;
3125 g_value_init (&result_value, G_TYPE_BOOLEAN);
3127 g_value_init (¶ms[0], G_TYPE_SOCKET);
3128 g_value_set_object (¶ms[0], socket);
3129 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
3130 g_value_set_flags (¶ms[1], condition);
3132 g_closure_invoke (closure, &result_value, 2, params, NULL);
3134 result = g_value_get_boolean (&result_value);
3135 g_value_unset (&result_value);
3136 g_value_unset (¶ms[0]);
3137 g_value_unset (¶ms[1]);
3142 static GSourceFuncs socket_source_funcs =
3144 socket_source_prepare,
3145 socket_source_check,
3146 socket_source_dispatch,
3147 socket_source_finalize,
3148 (GSourceFunc)socket_source_closure_callback,
3149 (GSourceDummyMarshal)g_cclosure_marshal_generic,
3153 socket_source_new (GSocket *socket,
3154 GIOCondition condition,
3155 GCancellable *cancellable)
3158 GSocketSource *socket_source;
3161 ensure_event (socket);
3163 if (socket->priv->event == WSA_INVALID_EVENT)
3165 g_warning ("Failed to create WSAEvent");
3166 return g_source_new (&broken_funcs, sizeof (GSource));
3170 condition |= G_IO_HUP | G_IO_ERR;
3172 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3173 g_source_set_name (source, "GSocket");
3174 socket_source = (GSocketSource *)source;
3176 socket_source->socket = g_object_ref (socket);
3177 socket_source->condition = condition;
3179 if (g_cancellable_make_pollfd (cancellable,
3180 &socket_source->cancel_pollfd))
3182 socket_source->cancellable = g_object_ref (cancellable);
3183 g_source_add_poll (source, &socket_source->cancel_pollfd);
3187 add_condition_watch (socket, &socket_source->condition);
3188 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3190 socket_source->pollfd.fd = socket->priv->fd;
3193 socket_source->pollfd.events = condition;
3194 socket_source->pollfd.revents = 0;
3195 g_source_add_poll (source, &socket_source->pollfd);
3197 if (socket->priv->timeout)
3198 socket_source->timeout_time = g_get_monotonic_time () +
3199 socket->priv->timeout * 1000000;
3202 socket_source->timeout_time = 0;
3208 * g_socket_create_source: (skip)
3209 * @socket: a #GSocket
3210 * @condition: a #GIOCondition mask to monitor
3211 * @cancellable: (allow-none): a %GCancellable or %NULL
3213 * Creates a %GSource that can be attached to a %GMainContext to monitor
3214 * for the availibility of the specified @condition on the socket.
3216 * The callback on the source is of the #GSocketSourceFunc type.
3218 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3219 * these conditions will always be reported output if they are true.
3221 * @cancellable if not %NULL can be used to cancel the source, which will
3222 * cause the source to trigger, reporting the current condition (which
3223 * is likely 0 unless cancellation happened at the same time as a
3224 * condition change). You can check for this in the callback using
3225 * g_cancellable_is_cancelled().
3227 * If @socket has a timeout set, and it is reached before @condition
3228 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3229 * %G_IO_OUT depending on @condition. However, @socket will have been
3230 * marked as having had a timeout, and so the next #GSocket I/O method
3231 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3233 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3238 g_socket_create_source (GSocket *socket,
3239 GIOCondition condition,
3240 GCancellable *cancellable)
3242 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3244 return socket_source_new (socket, condition, cancellable);
3248 * g_socket_condition_check:
3249 * @socket: a #GSocket
3250 * @condition: a #GIOCondition mask to check
3252 * Checks on the readiness of @socket to perform operations.
3253 * The operations specified in @condition are checked for and masked
3254 * against the currently-satisfied conditions on @socket. The result
3257 * Note that on Windows, it is possible for an operation to return
3258 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3259 * g_socket_condition_check() has claimed that the socket is ready for
3260 * writing. Rather than calling g_socket_condition_check() and then
3261 * writing to the socket if it succeeds, it is generally better to
3262 * simply try writing to the socket right away, and try again later if
3263 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3265 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3266 * these conditions will always be set in the output if they are true.
3268 * This call never blocks.
3270 * Returns: the @GIOCondition mask of the current state
3275 g_socket_condition_check (GSocket *socket,
3276 GIOCondition condition)
3278 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3280 if (!check_socket (socket, NULL))
3285 GIOCondition current_condition;
3287 condition |= G_IO_ERR | G_IO_HUP;
3289 add_condition_watch (socket, &condition);
3290 current_condition = update_condition (socket);
3291 remove_condition_watch (socket, &condition);
3292 return condition & current_condition;
3298 poll_fd.fd = socket->priv->fd;
3299 poll_fd.events = condition;
3302 result = g_poll (&poll_fd, 1, 0);
3303 while (result == -1 && get_socket_errno () == EINTR);
3305 return poll_fd.revents;
3311 * g_socket_condition_wait:
3312 * @socket: a #GSocket
3313 * @condition: a #GIOCondition mask to wait for
3314 * @cancellable: (allow-none): a #GCancellable, or %NULL
3315 * @error: a #GError pointer, or %NULL
3317 * Waits for @condition to become true on @socket. When the condition
3318 * is met, %TRUE is returned.
3320 * If @cancellable is cancelled before the condition is met, or if the
3321 * socket has a timeout set and it is reached before the condition is
3322 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3323 * the appropriate value (%G_IO_ERROR_CANCELLED or
3324 * %G_IO_ERROR_TIMED_OUT).
3326 * Returns: %TRUE if the condition was met, %FALSE otherwise
3331 g_socket_condition_wait (GSocket *socket,
3332 GIOCondition condition,
3333 GCancellable *cancellable,
3336 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3338 if (!check_socket (socket, error))
3341 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3346 GIOCondition current_condition;
3352 /* Always check these */
3353 condition |= G_IO_ERR | G_IO_HUP;
3355 add_condition_watch (socket, &condition);
3358 events[num_events++] = socket->priv->event;
3360 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3361 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3363 if (socket->priv->timeout)
3364 timeout = socket->priv->timeout * 1000;
3366 timeout = WSA_INFINITE;
3368 current_condition = update_condition (socket);
3369 while ((condition & current_condition) == 0)
3371 res = WSAWaitForMultipleEvents(num_events, events,
3372 FALSE, timeout, FALSE);
3373 if (res == WSA_WAIT_FAILED)
3375 int errsv = get_socket_errno ();
3377 g_set_error (error, G_IO_ERROR,
3378 socket_io_error_from_errno (errsv),
3379 _("Waiting for socket condition: %s"),
3380 socket_strerror (errsv));
3383 else if (res == WSA_WAIT_TIMEOUT)
3385 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3386 _("Socket I/O timed out"));
3390 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3393 current_condition = update_condition (socket);
3395 remove_condition_watch (socket, &condition);
3397 g_cancellable_release_fd (cancellable);
3399 return (condition & current_condition) != 0;
3408 poll_fd[0].fd = socket->priv->fd;
3409 poll_fd[0].events = condition;
3412 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3415 if (socket->priv->timeout)
3416 timeout = socket->priv->timeout * 1000;
3421 result = g_poll (poll_fd, num, timeout);
3422 while (result == -1 && get_socket_errno () == EINTR);
3425 g_cancellable_release_fd (cancellable);
3429 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3430 _("Socket I/O timed out"));
3434 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3440 * g_socket_send_message:
3441 * @socket: a #GSocket
3442 * @address: a #GSocketAddress, or %NULL
3443 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3444 * @num_vectors: the number of elements in @vectors, or -1
3445 * @messages: (array length=num_messages) (allow-none): a pointer to an
3446 * array of #GSocketControlMessages, or %NULL.
3447 * @num_messages: number of elements in @messages, or -1.
3448 * @flags: an int containing #GSocketMsgFlags flags
3449 * @cancellable: (allow-none): a %GCancellable or %NULL
3450 * @error: #GError for error reporting, or %NULL to ignore.
3452 * Send data to @address on @socket. This is the most complicated and
3453 * fully-featured version of this call. For easier use, see
3454 * g_socket_send() and g_socket_send_to().
3456 * If @address is %NULL then the message is sent to the default receiver
3457 * (set by g_socket_connect()).
3459 * @vectors must point to an array of #GOutputVector structs and
3460 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3461 * then @vectors is assumed to be terminated by a #GOutputVector with a
3462 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3463 * that the sent data will be gathered from. Using multiple
3464 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3465 * data from multiple sources into a single buffer, and more
3466 * network-efficient than making multiple calls to g_socket_send().
3468 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3469 * #GSocketControlMessage instances. These correspond to the control
3470 * messages to be sent on the socket.
3471 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3474 * @flags modify how the message is sent. The commonly available arguments
3475 * for this are available in the #GSocketMsgFlags enum, but the
3476 * values there are the same as the system values, and the flags
3477 * are passed in as-is, so you can pass in system-specific flags too.
3479 * If the socket is in blocking mode the call will block until there is
3480 * space for the data in the socket queue. If there is no space available
3481 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3482 * will be returned. To be notified when space is available, wait for the
3483 * %G_IO_OUT condition. Note though that you may still receive
3484 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3485 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3486 * very common due to the way the underlying APIs work.)
3488 * On error -1 is returned and @error is set accordingly.
3490 * Returns: Number of bytes written (which may be less than @size), or -1
3496 g_socket_send_message (GSocket *socket,
3497 GSocketAddress *address,
3498 GOutputVector *vectors,
3500 GSocketControlMessage **messages,
3503 GCancellable *cancellable,
3506 GOutputVector one_vector;
3509 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3511 if (!check_socket (socket, error))
3514 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3517 if (num_vectors == -1)
3519 for (num_vectors = 0;
3520 vectors[num_vectors].buffer != NULL;
3525 if (num_messages == -1)
3527 for (num_messages = 0;
3528 messages != NULL && messages[num_messages] != NULL;
3533 if (num_vectors == 0)
3537 one_vector.buffer = &zero;
3538 one_vector.size = 1;
3540 vectors = &one_vector;
3553 msg.msg_namelen = g_socket_address_get_native_size (address);
3554 msg.msg_name = g_alloca (msg.msg_namelen);
3555 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3560 msg.msg_name = NULL;
3561 msg.msg_namelen = 0;
3566 /* this entire expression will be evaluated at compile time */
3567 if (sizeof *msg.msg_iov == sizeof *vectors &&
3568 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3569 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3570 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3571 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3572 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3573 G_STRUCT_OFFSET (GOutputVector, size))
3574 /* ABI is compatible */
3576 msg.msg_iov = (struct iovec *) vectors;
3577 msg.msg_iovlen = num_vectors;
3580 /* ABI is incompatible */
3584 msg.msg_iov = g_newa (struct iovec, num_vectors);
3585 for (i = 0; i < num_vectors; i++)
3587 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3588 msg.msg_iov[i].iov_len = vectors[i].size;
3590 msg.msg_iovlen = num_vectors;
3596 struct cmsghdr *cmsg;
3599 msg.msg_controllen = 0;
3600 for (i = 0; i < num_messages; i++)
3601 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3603 if (msg.msg_controllen == 0)
3604 msg.msg_control = NULL;
3607 msg.msg_control = g_alloca (msg.msg_controllen);
3608 memset (msg.msg_control, '\0', msg.msg_controllen);
3611 cmsg = CMSG_FIRSTHDR (&msg);
3612 for (i = 0; i < num_messages; i++)
3614 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3615 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3616 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3617 g_socket_control_message_serialize (messages[i],
3619 cmsg = CMSG_NXTHDR (&msg, cmsg);
3621 g_assert (cmsg == NULL);
3626 if (socket->priv->blocking &&
3627 !g_socket_condition_wait (socket,
3628 G_IO_OUT, cancellable, error))
3631 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3634 int errsv = get_socket_errno ();
3639 if (socket->priv->blocking &&
3640 (errsv == EWOULDBLOCK ||
3644 g_set_error (error, G_IO_ERROR,
3645 socket_io_error_from_errno (errsv),
3646 _("Error sending message: %s"), socket_strerror (errsv));
3657 struct sockaddr_storage addr;
3664 /* Win32 doesn't support control messages.
3665 Actually this is possible for raw and datagram sockets
3666 via WSASendMessage on Vista or later, but that doesn't
3668 if (num_messages != 0)
3670 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3671 _("GSocketControlMessage not supported on windows"));
3676 bufs = g_newa (WSABUF, num_vectors);
3677 for (i = 0; i < num_vectors; i++)
3679 bufs[i].buf = (char *)vectors[i].buffer;
3680 bufs[i].len = (gulong)vectors[i].size;
3684 addrlen = 0; /* Avoid warning */
3687 addrlen = g_socket_address_get_native_size (address);
3688 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3694 if (socket->priv->blocking &&
3695 !g_socket_condition_wait (socket,
3696 G_IO_OUT, cancellable, error))
3700 result = WSASendTo (socket->priv->fd,
3703 (const struct sockaddr *)&addr, addrlen,
3706 result = WSASend (socket->priv->fd,
3713 int errsv = get_socket_errno ();
3715 if (errsv == WSAEINTR)
3718 if (errsv == WSAEWOULDBLOCK)
3719 win32_unset_event_mask (socket, FD_WRITE);
3721 if (socket->priv->blocking &&
3722 errsv == WSAEWOULDBLOCK)
3725 g_set_error (error, G_IO_ERROR,
3726 socket_io_error_from_errno (errsv),
3727 _("Error sending message: %s"), socket_strerror (errsv));
3740 * g_socket_receive_message:
3741 * @socket: a #GSocket
3742 * @address: (out) (allow-none): a pointer to a #GSocketAddress
3744 * @vectors: (array length=num_vectors): an array of #GInputVector structs
3745 * @num_vectors: the number of elements in @vectors, or -1
3746 * @messages: (array length=num_messages) (allow-none): a pointer which
3747 * may be filled with an array of #GSocketControlMessages, or %NULL
3748 * @num_messages: a pointer which will be filled with the number of
3749 * elements in @messages, or %NULL
3750 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3751 * @cancellable: (allow-none): a %GCancellable or %NULL
3752 * @error: a #GError pointer, or %NULL
3754 * Receive data from a socket. This is the most complicated and
3755 * fully-featured version of this call. For easier use, see
3756 * g_socket_receive() and g_socket_receive_from().
3758 * If @address is non-%NULL then @address will be set equal to the
3759 * source address of the received packet.
3760 * @address is owned by the caller.
3762 * @vector must point to an array of #GInputVector structs and
3763 * @num_vectors must be the length of this array. These structs
3764 * describe the buffers that received data will be scattered into.
3765 * If @num_vectors is -1, then @vectors is assumed to be terminated
3766 * by a #GInputVector with a %NULL buffer pointer.
3768 * As a special case, if @num_vectors is 0 (in which case, @vectors
3769 * may of course be %NULL), then a single byte is received and
3770 * discarded. This is to facilitate the common practice of sending a
3771 * single '\0' byte for the purposes of transferring ancillary data.
3773 * @messages, if non-%NULL, will be set to point to a newly-allocated
3774 * array of #GSocketControlMessage instances or %NULL if no such
3775 * messages was received. These correspond to the control messages
3776 * received from the kernel, one #GSocketControlMessage per message
3777 * from the kernel. This array is %NULL-terminated and must be freed
3778 * by the caller using g_free() after calling g_object_unref() on each
3779 * element. If @messages is %NULL, any control messages received will
3782 * @num_messages, if non-%NULL, will be set to the number of control
3783 * messages received.
3785 * If both @messages and @num_messages are non-%NULL, then
3786 * @num_messages gives the number of #GSocketControlMessage instances
3787 * in @messages (ie: not including the %NULL terminator).
3789 * @flags is an in/out parameter. The commonly available arguments
3790 * for this are available in the #GSocketMsgFlags enum, but the
3791 * values there are the same as the system values, and the flags
3792 * are passed in as-is, so you can pass in system-specific flags too
3793 * (and g_socket_receive_message() may pass system-specific flags out).
3795 * As with g_socket_receive(), data may be discarded if @socket is
3796 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3797 * provide enough buffer space to read a complete message. You can pass
3798 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3799 * removing it from the receive queue, but there is no portable way to find
3800 * out the length of the message other than by reading it into a
3801 * sufficiently-large buffer.
3803 * If the socket is in blocking mode the call will block until there
3804 * is some data to receive, the connection is closed, or there is an
3805 * error. If there is no data available and the socket is in
3806 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3807 * returned. To be notified when data is available, wait for the
3808 * %G_IO_IN condition.
3810 * On error -1 is returned and @error is set accordingly.
3812 * Returns: Number of bytes read, or 0 if the connection was closed by
3813 * the peer, or -1 on error
3818 g_socket_receive_message (GSocket *socket,
3819 GSocketAddress **address,
3820 GInputVector *vectors,
3822 GSocketControlMessage ***messages,
3825 GCancellable *cancellable,
3828 GInputVector one_vector;
3831 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3833 if (!check_socket (socket, error))
3836 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3839 if (num_vectors == -1)
3841 for (num_vectors = 0;
3842 vectors[num_vectors].buffer != NULL;
3847 if (num_vectors == 0)
3849 one_vector.buffer = &one_byte;
3850 one_vector.size = 1;
3852 vectors = &one_vector;
3859 struct sockaddr_storage one_sockaddr;
3864 msg.msg_name = &one_sockaddr;
3865 msg.msg_namelen = sizeof (struct sockaddr_storage);
3869 msg.msg_name = NULL;
3870 msg.msg_namelen = 0;
3874 /* this entire expression will be evaluated at compile time */
3875 if (sizeof *msg.msg_iov == sizeof *vectors &&
3876 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3877 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3878 G_STRUCT_OFFSET (GInputVector, buffer) &&
3879 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3880 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3881 G_STRUCT_OFFSET (GInputVector, size))
3882 /* ABI is compatible */
3884 msg.msg_iov = (struct iovec *) vectors;
3885 msg.msg_iovlen = num_vectors;
3888 /* ABI is incompatible */
3892 msg.msg_iov = g_newa (struct iovec, num_vectors);
3893 for (i = 0; i < num_vectors; i++)
3895 msg.msg_iov[i].iov_base = vectors[i].buffer;
3896 msg.msg_iov[i].iov_len = vectors[i].size;
3898 msg.msg_iovlen = num_vectors;
3902 msg.msg_control = g_alloca (2048);
3903 msg.msg_controllen = 2048;
3907 msg.msg_flags = *flags;
3911 /* We always set the close-on-exec flag so we don't leak file
3912 * descriptors into child processes. Note that gunixfdmessage.c
3913 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
3915 #ifdef MSG_CMSG_CLOEXEC
3916 msg.msg_flags |= MSG_CMSG_CLOEXEC;
3922 if (socket->priv->blocking &&
3923 !g_socket_condition_wait (socket,
3924 G_IO_IN, cancellable, error))
3927 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3928 #ifdef MSG_CMSG_CLOEXEC
3929 if (result < 0 && get_socket_errno () == EINVAL)
3931 /* We must be running on an old kernel. Call without the flag. */
3932 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
3933 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3939 int errsv = get_socket_errno ();
3944 if (socket->priv->blocking &&
3945 (errsv == EWOULDBLOCK ||
3949 g_set_error (error, G_IO_ERROR,
3950 socket_io_error_from_errno (errsv),
3951 _("Error receiving message: %s"), socket_strerror (errsv));
3958 /* decode address */
3959 if (address != NULL)
3961 if (msg.msg_namelen > 0)
3962 *address = g_socket_address_new_from_native (msg.msg_name,
3968 /* decode control messages */
3970 GPtrArray *my_messages = NULL;
3971 struct cmsghdr *cmsg;
3973 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3975 GSocketControlMessage *message;
3977 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3979 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3981 if (message == NULL)
3982 /* We've already spewed about the problem in the
3983 deserialization code, so just continue */
3986 if (messages == NULL)
3988 /* we have to do it this way if the user ignores the
3989 * messages so that we will close any received fds.
3991 g_object_unref (message);
3995 if (my_messages == NULL)
3996 my_messages = g_ptr_array_new ();
3997 g_ptr_array_add (my_messages, message);
4002 *num_messages = my_messages != NULL ? my_messages->len : 0;
4006 if (my_messages == NULL)
4012 g_ptr_array_add (my_messages, NULL);
4013 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4018 g_assert (my_messages == NULL);
4022 /* capture the flags */
4024 *flags = msg.msg_flags;
4030 struct sockaddr_storage addr;
4032 DWORD bytes_received;
4039 bufs = g_newa (WSABUF, num_vectors);
4040 for (i = 0; i < num_vectors; i++)
4042 bufs[i].buf = (char *)vectors[i].buffer;
4043 bufs[i].len = (gulong)vectors[i].size;
4055 if (socket->priv->blocking &&
4056 !g_socket_condition_wait (socket,
4057 G_IO_IN, cancellable, error))
4060 addrlen = sizeof addr;
4062 result = WSARecvFrom (socket->priv->fd,
4064 &bytes_received, &win_flags,
4065 (struct sockaddr *)&addr, &addrlen,
4068 result = WSARecv (socket->priv->fd,
4070 &bytes_received, &win_flags,
4074 int errsv = get_socket_errno ();
4076 if (errsv == WSAEINTR)
4079 win32_unset_event_mask (socket, FD_READ);
4081 if (socket->priv->blocking &&
4082 errsv == WSAEWOULDBLOCK)
4085 g_set_error (error, G_IO_ERROR,
4086 socket_io_error_from_errno (errsv),
4087 _("Error receiving message: %s"), socket_strerror (errsv));
4091 win32_unset_event_mask (socket, FD_READ);
4095 /* decode address */
4096 if (address != NULL)
4099 *address = g_socket_address_new_from_native (&addr, addrlen);
4104 /* capture the flags */
4108 if (messages != NULL)
4110 if (num_messages != NULL)
4113 return bytes_received;
4119 * g_socket_get_credentials:
4120 * @socket: a #GSocket.
4121 * @error: #GError for error reporting, or %NULL to ignore.
4123 * Returns the credentials of the foreign process connected to this
4124 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4127 * If this operation isn't supported on the OS, the method fails with
4128 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4129 * by reading the %SO_PEERCRED option on the underlying socket.
4131 * Other ways to obtain credentials from a foreign peer includes the
4132 * #GUnixCredentialsMessage type and
4133 * g_unix_connection_send_credentials() /
4134 * g_unix_connection_receive_credentials() functions.
4136 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4137 * that must be freed with g_object_unref().
4142 g_socket_get_credentials (GSocket *socket,
4147 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4148 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4152 #if defined(__linux__) || defined(__OpenBSD__)
4155 #if defined(__linux__)
4156 struct ucred native_creds;
4157 optlen = sizeof (struct ucred);
4158 #elif defined(__OpenBSD__)
4159 struct sockpeercred native_creds;
4160 optlen = sizeof (struct sockpeercred);
4162 if (getsockopt (socket->priv->fd,
4165 (void *)&native_creds,
4168 int errsv = get_socket_errno ();
4171 socket_io_error_from_errno (errsv),
4172 _("Unable to get pending error: %s"),
4173 socket_strerror (errsv));
4177 ret = g_credentials_new ();
4178 g_credentials_set_native (ret,
4179 #if defined(__linux__)
4180 G_CREDENTIALS_TYPE_LINUX_UCRED,
4181 #elif defined(__OpenBSD__)
4182 G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
4188 g_set_error_literal (error,
4190 G_IO_ERROR_NOT_SUPPORTED,
4191 _("g_socket_get_credentials not implemented for this OS"));