1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2008 Christian Kellner, Samuel Cormier-Iijima
4 * Copyright © 2009 Codethink Limited
5 * Copyright © 2009 Red Hat, Inc
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General
18 * Public License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20 * Boston, MA 02111-1307, USA.
22 * Authors: Christian Kellner <gicmo@gnome.org>
23 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
24 * Ryan Lortie <desrt@desrt.ca>
25 * Alexander Larsson <alexl@redhat.com>
33 #include "glib-unix.h"
44 # include <sys/ioctl.h>
51 #include "gcancellable.h"
52 #include "gioenumtypes.h"
53 #include "ginetaddress.h"
54 #include "ginitable.h"
58 #include "gnetworkingprivate.h"
59 #include "gsocketaddress.h"
60 #include "gsocketcontrolmessage.h"
61 #include "gcredentials.h"
66 * @short_description: Low-level socket object
68 * @see_also: #GInitable
70 * A #GSocket is a low-level networking primitive. It is a more or less
71 * direct mapping of the BSD socket API in a portable GObject based API.
72 * It supports both the UNIX socket implementations and winsock2 on Windows.
74 * #GSocket is the platform independent base upon which the higher level
75 * network primitives are based. Applications are not typically meant to
76 * use it directly, but rather through classes like #GSocketClient,
77 * #GSocketService and #GSocketConnection. However there may be cases where
78 * direct use of #GSocket is useful.
80 * #GSocket implements the #GInitable interface, so if it is manually constructed
81 * by e.g. g_object_new() you must call g_initable_init() and check the
82 * results before using the object. This is done automatically in
83 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
86 * Sockets operate in two general modes, blocking or non-blocking. When
87 * in blocking mode all operations block until the requested operation
88 * is finished or there is an error. In non-blocking mode all calls that
89 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
90 * To know when a call would successfully run you can call g_socket_condition_check(),
91 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
92 * attach it to a #GMainContext to get callbacks when I/O is possible.
93 * Note that all sockets are always set to non blocking mode in the system, and
94 * blocking mode is emulated in GSocket.
96 * When working in non-blocking mode applications should always be able to
97 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
98 * function said that I/O was possible. This can easily happen in case
99 * of a race condition in the application, but it can also happen for other
100 * reasons. For instance, on Windows a socket is always seen as writable
101 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
103 * #GSocket<!-- -->s can be either connection oriented or datagram based.
104 * For connection oriented types you must first establish a connection by
105 * either connecting to an address or accepting a connection from another
106 * address. For connectionless socket types the target/source address is
107 * specified or received in each I/O operation.
109 * All socket file descriptors are set to be close-on-exec.
111 * Note that creating a #GSocket causes the signal %SIGPIPE to be
112 * ignored for the remainder of the program. If you are writing a
113 * command-line utility that uses #GSocket, you may need to take into
114 * account the fact that your program will not automatically be killed
115 * if it tries to write to %stdout after it has been closed.
120 static void g_socket_initable_iface_init (GInitableIface *iface);
121 static gboolean g_socket_initable_init (GInitable *initable,
122 GCancellable *cancellable,
125 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
126 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
127 g_socket_initable_iface_init));
144 PROP_MULTICAST_LOOPBACK,
148 struct _GSocketPrivate
150 GSocketFamily family;
152 GSocketProtocol protocol;
156 GError *construct_error;
157 GSocketAddress *remote_address;
165 guint connect_pending : 1;
171 GList *requested_conditions; /* list of requested GIOCondition * */
176 get_socket_errno (void)
181 return WSAGetLastError ();
186 socket_io_error_from_errno (int err)
189 return g_io_error_from_errno (err);
194 return G_IO_ERROR_ADDRESS_IN_USE;
196 return G_IO_ERROR_WOULD_BLOCK;
198 return G_IO_ERROR_PERMISSION_DENIED;
199 case WSA_INVALID_HANDLE:
200 case WSA_INVALID_PARAMETER:
203 return G_IO_ERROR_INVALID_ARGUMENT;
204 case WSAEPROTONOSUPPORT:
205 return G_IO_ERROR_NOT_SUPPORTED;
207 return G_IO_ERROR_CANCELLED;
208 case WSAESOCKTNOSUPPORT:
210 case WSAEPFNOSUPPORT:
211 case WSAEAFNOSUPPORT:
212 return G_IO_ERROR_NOT_SUPPORTED;
214 return G_IO_ERROR_FAILED;
220 socket_strerror (int err)
223 return g_strerror (err);
228 msg = g_win32_error_message (err);
230 msg_ret = g_intern_string (msg);
238 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
240 _win32_unset_event_mask (GSocket *socket, int mask)
242 socket->priv->current_events &= ~mask;
243 socket->priv->current_errors &= ~mask;
246 #define win32_unset_event_mask(_socket, _mask)
250 set_fd_nonblocking (int fd)
253 GError *error = NULL;
259 if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
261 g_warning ("Error setting socket nonblocking: %s", error->message);
262 g_clear_error (&error);
267 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
269 int errsv = get_socket_errno ();
270 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
276 check_socket (GSocket *socket,
279 if (!socket->priv->inited)
281 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
282 _("Invalid socket, not initialized"));
286 if (socket->priv->construct_error)
288 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
289 _("Invalid socket, initialization failed due to: %s"),
290 socket->priv->construct_error->message);
294 if (socket->priv->closed)
296 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
297 _("Socket is already closed"));
301 if (socket->priv->timed_out)
303 socket->priv->timed_out = FALSE;
304 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
305 _("Socket I/O timed out"));
313 g_socket_details_from_fd (GSocket *socket)
315 struct sockaddr_storage address;
322 /* See bug #611756 */
323 BOOL bool_val = FALSE;
328 fd = socket->priv->fd;
329 optlen = sizeof value;
330 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
332 errsv = get_socket_errno ();
343 /* programmer error */
344 g_error ("creating GSocket from fd %d: %s\n",
345 fd, socket_strerror (errsv));
353 g_assert (optlen == sizeof value);
357 socket->priv->type = G_SOCKET_TYPE_STREAM;
361 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
365 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
369 socket->priv->type = G_SOCKET_TYPE_INVALID;
373 addrlen = sizeof address;
374 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
376 errsv = get_socket_errno ();
382 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
383 sizeof address.ss_family <= addrlen);
384 family = address.ss_family;
388 /* On Solaris, this happens if the socket is not yet connected.
389 * But we can use SO_DOMAIN as a workaround there.
392 optlen = sizeof family;
393 if (getsockopt (fd, SOL_SOCKET, SO_DOMAIN, (void *)&family, &optlen) != 0)
395 errsv = get_socket_errno ();
399 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
407 case G_SOCKET_FAMILY_IPV4:
408 case G_SOCKET_FAMILY_IPV6:
409 socket->priv->family = address.ss_family;
410 switch (socket->priv->type)
412 case G_SOCKET_TYPE_STREAM:
413 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
416 case G_SOCKET_TYPE_DATAGRAM:
417 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
420 case G_SOCKET_TYPE_SEQPACKET:
421 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
429 case G_SOCKET_FAMILY_UNIX:
430 socket->priv->family = G_SOCKET_FAMILY_UNIX;
431 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
435 socket->priv->family = G_SOCKET_FAMILY_INVALID;
439 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
441 addrlen = sizeof address;
442 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
443 socket->priv->connected = TRUE;
446 optlen = sizeof bool_val;
447 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
448 (void *)&bool_val, &optlen) == 0)
451 /* Experimentation indicates that the SO_KEEPALIVE value is
452 * actually a char on Windows, even if documentation claims it
453 * to be a BOOL which is a typedef for int. So this g_assert()
454 * fails. See bug #611756.
456 g_assert (optlen == sizeof bool_val);
458 socket->priv->keepalive = !!bool_val;
462 /* Can't read, maybe not supported, assume FALSE */
463 socket->priv->keepalive = FALSE;
469 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
470 socket_io_error_from_errno (errsv),
471 _("creating GSocket from fd: %s"),
472 socket_strerror (errsv));
476 g_socket_create_socket (GSocketFamily family,
486 case G_SOCKET_TYPE_STREAM:
487 native_type = SOCK_STREAM;
490 case G_SOCKET_TYPE_DATAGRAM:
491 native_type = SOCK_DGRAM;
494 case G_SOCKET_TYPE_SEQPACKET:
495 native_type = SOCK_SEQPACKET;
499 g_assert_not_reached ();
504 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
505 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
510 fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
511 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
512 if (fd < 0 && errno == EINVAL)
514 fd = socket (family, native_type, protocol);
518 int errsv = get_socket_errno ();
520 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
521 _("Unable to create socket: %s"), socket_strerror (errsv));
528 /* We always want to set close-on-exec to protect users. If you
529 need to so some weird inheritance to exec you can re-enable this
530 using lower level hacks with g_socket_get_fd(). */
531 flags = fcntl (fd, F_GETFD, 0);
533 (flags & FD_CLOEXEC) == 0)
536 fcntl (fd, F_SETFD, flags);
545 g_socket_constructed (GObject *object)
547 GSocket *socket = G_SOCKET (object);
549 if (socket->priv->fd >= 0)
550 /* create socket->priv info from the fd */
551 g_socket_details_from_fd (socket);
554 /* create the fd from socket->priv info */
555 socket->priv->fd = g_socket_create_socket (socket->priv->family,
557 socket->priv->protocol,
558 &socket->priv->construct_error);
560 /* Always use native nonblocking sockets, as
561 windows sets sockets to nonblocking automatically
562 in certain operations. This way we make things work
563 the same on all platforms */
564 if (socket->priv->fd != -1)
565 set_fd_nonblocking (socket->priv->fd);
569 g_socket_get_property (GObject *object,
574 GSocket *socket = G_SOCKET (object);
575 GSocketAddress *address;
580 g_value_set_enum (value, socket->priv->family);
584 g_value_set_enum (value, socket->priv->type);
588 g_value_set_enum (value, socket->priv->protocol);
592 g_value_set_int (value, socket->priv->fd);
596 g_value_set_boolean (value, socket->priv->blocking);
599 case PROP_LISTEN_BACKLOG:
600 g_value_set_int (value, socket->priv->listen_backlog);
604 g_value_set_boolean (value, socket->priv->keepalive);
607 case PROP_LOCAL_ADDRESS:
608 address = g_socket_get_local_address (socket, NULL);
609 g_value_take_object (value, address);
612 case PROP_REMOTE_ADDRESS:
613 address = g_socket_get_remote_address (socket, NULL);
614 g_value_take_object (value, address);
618 g_value_set_uint (value, socket->priv->timeout);
622 g_value_set_uint (value, g_socket_get_ttl (socket));
626 g_value_set_boolean (value, g_socket_get_broadcast (socket));
629 case PROP_MULTICAST_LOOPBACK:
630 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
633 case PROP_MULTICAST_TTL:
634 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
638 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
643 g_socket_set_property (GObject *object,
648 GSocket *socket = G_SOCKET (object);
653 socket->priv->family = g_value_get_enum (value);
657 socket->priv->type = g_value_get_enum (value);
661 socket->priv->protocol = g_value_get_enum (value);
665 socket->priv->fd = g_value_get_int (value);
669 g_socket_set_blocking (socket, g_value_get_boolean (value));
672 case PROP_LISTEN_BACKLOG:
673 g_socket_set_listen_backlog (socket, g_value_get_int (value));
677 g_socket_set_keepalive (socket, g_value_get_boolean (value));
681 g_socket_set_timeout (socket, g_value_get_uint (value));
685 g_socket_set_ttl (socket, g_value_get_uint (value));
689 g_socket_set_broadcast (socket, g_value_get_boolean (value));
692 case PROP_MULTICAST_LOOPBACK:
693 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
696 case PROP_MULTICAST_TTL:
697 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
701 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
706 g_socket_finalize (GObject *object)
708 GSocket *socket = G_SOCKET (object);
710 g_clear_error (&socket->priv->construct_error);
712 if (socket->priv->fd != -1 &&
713 !socket->priv->closed)
714 g_socket_close (socket, NULL);
716 if (socket->priv->remote_address)
717 g_object_unref (socket->priv->remote_address);
720 if (socket->priv->event != WSA_INVALID_EVENT)
722 WSACloseEvent (socket->priv->event);
723 socket->priv->event = WSA_INVALID_EVENT;
726 g_assert (socket->priv->requested_conditions == NULL);
729 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
730 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
734 g_socket_class_init (GSocketClass *klass)
736 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
739 /* Make sure winsock has been initialized */
740 type = g_inet_address_get_type ();
741 (type); /* To avoid -Wunused-but-set-variable */
744 /* There is no portable, thread-safe way to avoid having the process
745 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
746 * forced to simply ignore the signal process-wide.
748 signal (SIGPIPE, SIG_IGN);
751 g_type_class_add_private (klass, sizeof (GSocketPrivate));
753 gobject_class->finalize = g_socket_finalize;
754 gobject_class->constructed = g_socket_constructed;
755 gobject_class->set_property = g_socket_set_property;
756 gobject_class->get_property = g_socket_get_property;
758 g_object_class_install_property (gobject_class, PROP_FAMILY,
759 g_param_spec_enum ("family",
761 P_("The sockets address family"),
762 G_TYPE_SOCKET_FAMILY,
763 G_SOCKET_FAMILY_INVALID,
764 G_PARAM_CONSTRUCT_ONLY |
766 G_PARAM_STATIC_STRINGS));
768 g_object_class_install_property (gobject_class, PROP_TYPE,
769 g_param_spec_enum ("type",
771 P_("The sockets type"),
773 G_SOCKET_TYPE_STREAM,
774 G_PARAM_CONSTRUCT_ONLY |
776 G_PARAM_STATIC_STRINGS));
778 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
779 g_param_spec_enum ("protocol",
780 P_("Socket protocol"),
781 P_("The id of the protocol to use, or -1 for unknown"),
782 G_TYPE_SOCKET_PROTOCOL,
783 G_SOCKET_PROTOCOL_UNKNOWN,
784 G_PARAM_CONSTRUCT_ONLY |
786 G_PARAM_STATIC_STRINGS));
788 g_object_class_install_property (gobject_class, PROP_FD,
789 g_param_spec_int ("fd",
790 P_("File descriptor"),
791 P_("The sockets file descriptor"),
795 G_PARAM_CONSTRUCT_ONLY |
797 G_PARAM_STATIC_STRINGS));
799 g_object_class_install_property (gobject_class, PROP_BLOCKING,
800 g_param_spec_boolean ("blocking",
802 P_("Whether or not I/O on this socket is blocking"),
805 G_PARAM_STATIC_STRINGS));
807 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
808 g_param_spec_int ("listen-backlog",
809 P_("Listen backlog"),
810 P_("Outstanding connections in the listen queue"),
815 G_PARAM_STATIC_STRINGS));
817 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
818 g_param_spec_boolean ("keepalive",
819 P_("Keep connection alive"),
820 P_("Keep connection alive by sending periodic pings"),
823 G_PARAM_STATIC_STRINGS));
825 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
826 g_param_spec_object ("local-address",
828 P_("The local address the socket is bound to"),
829 G_TYPE_SOCKET_ADDRESS,
831 G_PARAM_STATIC_STRINGS));
833 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
834 g_param_spec_object ("remote-address",
835 P_("Remote address"),
836 P_("The remote address the socket is connected to"),
837 G_TYPE_SOCKET_ADDRESS,
839 G_PARAM_STATIC_STRINGS));
844 * The timeout in seconds on socket I/O
848 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
849 g_param_spec_uint ("timeout",
851 P_("The timeout in seconds on socket I/O"),
856 G_PARAM_STATIC_STRINGS));
861 * Whether the socket should allow sending to and receiving from broadcast addresses.
865 g_object_class_install_property (gobject_class, PROP_BROADCAST,
866 g_param_spec_boolean ("broadcast",
868 P_("Whether to allow sending to and receiving from broadcast addresses"),
871 G_PARAM_STATIC_STRINGS));
876 * Time-to-live for outgoing unicast packets
880 g_object_class_install_property (gobject_class, PROP_TTL,
881 g_param_spec_uint ("ttl",
883 P_("Time-to-live of outgoing unicast packets"),
886 G_PARAM_STATIC_STRINGS));
889 * GSocket:multicast-loopback:
891 * Whether outgoing multicast packets loop back to the local host.
895 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
896 g_param_spec_boolean ("multicast-loopback",
897 P_("Multicast loopback"),
898 P_("Whether outgoing multicast packets loop back to the local host"),
901 G_PARAM_STATIC_STRINGS));
904 * GSocket:multicast-ttl:
906 * Time-to-live out outgoing multicast packets
910 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
911 g_param_spec_uint ("multicast-ttl",
913 P_("Time-to-live of outgoing multicast packets"),
916 G_PARAM_STATIC_STRINGS));
920 g_socket_initable_iface_init (GInitableIface *iface)
922 iface->init = g_socket_initable_init;
926 g_socket_init (GSocket *socket)
928 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
930 socket->priv->fd = -1;
931 socket->priv->blocking = TRUE;
932 socket->priv->listen_backlog = 10;
933 socket->priv->construct_error = NULL;
935 socket->priv->event = WSA_INVALID_EVENT;
940 g_socket_initable_init (GInitable *initable,
941 GCancellable *cancellable,
946 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
948 socket = G_SOCKET (initable);
950 if (cancellable != NULL)
952 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
953 _("Cancellable initialization not supported"));
957 socket->priv->inited = TRUE;
959 if (socket->priv->construct_error)
962 *error = g_error_copy (socket->priv->construct_error);
972 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
973 * @type: the socket type to use.
974 * @protocol: the id of the protocol to use, or 0 for default.
975 * @error: #GError for error reporting, or %NULL to ignore.
977 * Creates a new #GSocket with the defined family, type and protocol.
978 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
979 * for the family and type is used.
981 * The @protocol is a family and type specific int that specifies what
982 * kind of protocol to use. #GSocketProtocol lists several common ones.
983 * Many families only support one protocol, and use 0 for this, others
984 * support several and using 0 means to use the default protocol for
985 * the family and type.
987 * The protocol id is passed directly to the operating
988 * system, so you can use protocols not listed in #GSocketProtocol if you
989 * know the protocol number used for it.
991 * Returns: a #GSocket or %NULL on error.
992 * Free the returned object with g_object_unref().
997 g_socket_new (GSocketFamily family,
999 GSocketProtocol protocol,
1002 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1006 "protocol", protocol,
1011 * g_socket_new_from_fd:
1012 * @fd: a native socket file descriptor.
1013 * @error: #GError for error reporting, or %NULL to ignore.
1015 * Creates a new #GSocket from a native file descriptor
1016 * or winsock SOCKET handle.
1018 * This reads all the settings from the file descriptor so that
1019 * all properties should work. Note that the file descriptor
1020 * will be set to non-blocking mode, independent on the blocking
1021 * mode of the #GSocket.
1023 * Returns: a #GSocket or %NULL on error.
1024 * Free the returned object with g_object_unref().
1029 g_socket_new_from_fd (gint fd,
1032 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1039 * g_socket_set_blocking:
1040 * @socket: a #GSocket.
1041 * @blocking: Whether to use blocking I/O or not.
1043 * Sets the blocking mode of the socket. In blocking mode
1044 * all operations block until they succeed or there is an error. In
1045 * non-blocking mode all functions return results immediately or
1046 * with a %G_IO_ERROR_WOULD_BLOCK error.
1048 * All sockets are created in blocking mode. However, note that the
1049 * platform level socket is always non-blocking, and blocking mode
1050 * is a GSocket level feature.
1055 g_socket_set_blocking (GSocket *socket,
1058 g_return_if_fail (G_IS_SOCKET (socket));
1060 blocking = !!blocking;
1062 if (socket->priv->blocking == blocking)
1065 socket->priv->blocking = blocking;
1066 g_object_notify (G_OBJECT (socket), "blocking");
1070 * g_socket_get_blocking:
1071 * @socket: a #GSocket.
1073 * Gets the blocking mode of the socket. For details on blocking I/O,
1074 * see g_socket_set_blocking().
1076 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1081 g_socket_get_blocking (GSocket *socket)
1083 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1085 return socket->priv->blocking;
1089 * g_socket_set_keepalive:
1090 * @socket: a #GSocket.
1091 * @keepalive: Value for the keepalive flag
1093 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1094 * this flag is set on a socket, the system will attempt to verify that the
1095 * remote socket endpoint is still present if a sufficiently long period of
1096 * time passes with no data being exchanged. If the system is unable to
1097 * verify the presence of the remote endpoint, it will automatically close
1100 * This option is only functional on certain kinds of sockets. (Notably,
1101 * %G_SOCKET_PROTOCOL_TCP sockets.)
1103 * The exact time between pings is system- and protocol-dependent, but will
1104 * normally be at least two hours. Most commonly, you would set this flag
1105 * on a server socket if you want to allow clients to remain idle for long
1106 * periods of time, but also want to ensure that connections are eventually
1107 * garbage-collected if clients crash or become unreachable.
1112 g_socket_set_keepalive (GSocket *socket,
1117 g_return_if_fail (G_IS_SOCKET (socket));
1119 keepalive = !!keepalive;
1120 if (socket->priv->keepalive == keepalive)
1123 value = (gint) keepalive;
1124 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1125 (gpointer) &value, sizeof (value)) < 0)
1127 int errsv = get_socket_errno ();
1128 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1132 socket->priv->keepalive = keepalive;
1133 g_object_notify (G_OBJECT (socket), "keepalive");
1137 * g_socket_get_keepalive:
1138 * @socket: a #GSocket.
1140 * Gets the keepalive mode of the socket. For details on this,
1141 * see g_socket_set_keepalive().
1143 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1148 g_socket_get_keepalive (GSocket *socket)
1150 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1152 return socket->priv->keepalive;
1156 * g_socket_get_listen_backlog:
1157 * @socket: a #GSocket.
1159 * Gets the listen backlog setting of the socket. For details on this,
1160 * see g_socket_set_listen_backlog().
1162 * Returns: the maximum number of pending connections.
1167 g_socket_get_listen_backlog (GSocket *socket)
1169 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1171 return socket->priv->listen_backlog;
1175 * g_socket_set_listen_backlog:
1176 * @socket: a #GSocket.
1177 * @backlog: the maximum number of pending connections.
1179 * Sets the maximum number of outstanding connections allowed
1180 * when listening on this socket. If more clients than this are
1181 * connecting to the socket and the application is not handling them
1182 * on time then the new connections will be refused.
1184 * Note that this must be called before g_socket_listen() and has no
1185 * effect if called after that.
1190 g_socket_set_listen_backlog (GSocket *socket,
1193 g_return_if_fail (G_IS_SOCKET (socket));
1194 g_return_if_fail (!socket->priv->listening);
1196 if (backlog != socket->priv->listen_backlog)
1198 socket->priv->listen_backlog = backlog;
1199 g_object_notify (G_OBJECT (socket), "listen-backlog");
1204 * g_socket_get_timeout:
1205 * @socket: a #GSocket.
1207 * Gets the timeout setting of the socket. For details on this, see
1208 * g_socket_set_timeout().
1210 * Returns: the timeout in seconds
1215 g_socket_get_timeout (GSocket *socket)
1217 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1219 return socket->priv->timeout;
1223 * g_socket_set_timeout:
1224 * @socket: a #GSocket.
1225 * @timeout: the timeout for @socket, in seconds, or 0 for none
1227 * Sets the time in seconds after which I/O operations on @socket will
1228 * time out if they have not yet completed.
1230 * On a blocking socket, this means that any blocking #GSocket
1231 * operation will time out after @timeout seconds of inactivity,
1232 * returning %G_IO_ERROR_TIMED_OUT.
1234 * On a non-blocking socket, calls to g_socket_condition_wait() will
1235 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1236 * created with g_socket_create_source() will trigger after
1237 * @timeout seconds of inactivity, with the requested condition
1238 * set, at which point calling g_socket_receive(), g_socket_send(),
1239 * g_socket_check_connect_result(), etc, will fail with
1240 * %G_IO_ERROR_TIMED_OUT.
1242 * If @timeout is 0 (the default), operations will never time out
1245 * Note that if an I/O operation is interrupted by a signal, this may
1246 * cause the timeout to be reset.
1251 g_socket_set_timeout (GSocket *socket,
1254 g_return_if_fail (G_IS_SOCKET (socket));
1256 if (timeout != socket->priv->timeout)
1258 socket->priv->timeout = timeout;
1259 g_object_notify (G_OBJECT (socket), "timeout");
1265 * @socket: a #GSocket.
1267 * Gets the unicast time-to-live setting on @socket; see
1268 * g_socket_set_ttl() for more details.
1270 * Returns: the time-to-live setting on @socket
1275 g_socket_get_ttl (GSocket *socket)
1278 guint value, optlen;
1280 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1282 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1286 optlen = sizeof (optval);
1287 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_TTL,
1291 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1293 optlen = sizeof (value);
1294 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1298 g_return_val_if_reached (FALSE);
1302 int errsv = get_socket_errno ();
1303 g_warning ("error getting unicast ttl: %s", socket_strerror (errsv));
1312 * @socket: a #GSocket.
1313 * @ttl: the time-to-live value for all unicast packets on @socket
1315 * Sets the time-to-live for outgoing unicast packets on @socket.
1316 * By default the platform-specific default value is used.
1321 g_socket_set_ttl (GSocket *socket,
1326 g_return_if_fail (G_IS_SOCKET (socket));
1328 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1330 guchar optval = (guchar)ttl;
1332 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_TTL,
1333 &optval, sizeof (optval));
1335 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1337 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1338 &ttl, sizeof (ttl));
1341 g_return_if_reached ();
1345 int errsv = get_socket_errno ();
1346 g_warning ("error setting unicast ttl: %s", socket_strerror (errsv));
1350 g_object_notify (G_OBJECT (socket), "ttl");
1354 * g_socket_get_broadcast:
1355 * @socket: a #GSocket.
1357 * Gets the broadcast setting on @socket; if %TRUE,
1358 * it is possible to send packets to broadcast
1359 * addresses or receive from broadcast addresses.
1361 * Returns: the broadcast setting on @socket
1366 g_socket_get_broadcast (GSocket *socket)
1369 guint value = 0, optlen;
1371 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1373 optlen = sizeof (guchar);
1374 result = getsockopt (socket->priv->fd, SOL_SOCKET, SO_BROADCAST,
1379 int errsv = get_socket_errno ();
1380 g_warning ("error getting broadcast: %s", socket_strerror (errsv));
1388 * g_socket_set_broadcast:
1389 * @socket: a #GSocket.
1390 * @broadcast: whether @socket should allow sending to and receiving
1391 * from broadcast addresses
1393 * Sets whether @socket should allow sending to and receiving from
1394 * broadcast addresses. This is %FALSE by default.
1399 g_socket_set_broadcast (GSocket *socket,
1405 g_return_if_fail (G_IS_SOCKET (socket));
1407 broadcast = !!broadcast;
1408 value = (guchar)broadcast;
1410 result = setsockopt (socket->priv->fd, SOL_SOCKET, SO_BROADCAST,
1411 &value, sizeof (value));
1415 int errsv = get_socket_errno ();
1416 g_warning ("error setting broadcast: %s", socket_strerror (errsv));
1420 g_object_notify (G_OBJECT (socket), "broadcast");
1424 * g_socket_get_multicast_loopback:
1425 * @socket: a #GSocket.
1427 * Gets the multicast loopback setting on @socket; if %TRUE (the
1428 * default), outgoing multicast packets will be looped back to
1429 * multicast listeners on the same host.
1431 * Returns: the multicast loopback setting on @socket
1436 g_socket_get_multicast_loopback (GSocket *socket)
1439 guint value = 0, optlen;
1441 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1443 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1445 optlen = sizeof (guchar);
1446 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1449 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1451 optlen = sizeof (guint);
1452 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1456 g_return_val_if_reached (FALSE);
1460 int errsv = get_socket_errno ();
1461 g_warning ("error getting multicast loopback: %s", socket_strerror (errsv));
1469 * g_socket_set_multicast_loopback:
1470 * @socket: a #GSocket.
1471 * @loopback: whether @socket should receive messages sent to its
1472 * multicast groups from the local host
1474 * Sets whether outgoing multicast packets will be received by sockets
1475 * listening on that multicast address on the same host. This is %TRUE
1481 g_socket_set_multicast_loopback (GSocket *socket,
1486 g_return_if_fail (G_IS_SOCKET (socket));
1488 loopback = !!loopback;
1490 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1492 guchar value = (guchar)loopback;
1494 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1495 &value, sizeof (value));
1497 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1499 guint value = (guint)loopback;
1501 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1502 &value, sizeof (value));
1505 g_return_if_reached ();
1509 int errsv = get_socket_errno ();
1510 g_warning ("error setting multicast loopback: %s", socket_strerror (errsv));
1514 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1518 * g_socket_get_multicast_ttl:
1519 * @socket: a #GSocket.
1521 * Gets the multicast time-to-live setting on @socket; see
1522 * g_socket_set_multicast_ttl() for more details.
1524 * Returns: the multicast time-to-live setting on @socket
1529 g_socket_get_multicast_ttl (GSocket *socket)
1532 guint value, optlen;
1534 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1536 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1540 optlen = sizeof (optval);
1541 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1545 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1547 optlen = sizeof (value);
1548 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1552 g_return_val_if_reached (FALSE);
1556 int errsv = get_socket_errno ();
1557 g_warning ("error getting multicast ttl: %s", socket_strerror (errsv));
1565 * g_socket_set_multicast_ttl:
1566 * @socket: a #GSocket.
1567 * @ttl: the time-to-live value for all multicast datagrams on @socket
1569 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1570 * By default, this is 1, meaning that multicast packets will not leave
1571 * the local network.
1576 g_socket_set_multicast_ttl (GSocket *socket,
1581 g_return_if_fail (G_IS_SOCKET (socket));
1583 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1585 guchar optval = (guchar)ttl;
1587 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1588 &optval, sizeof (optval));
1590 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1592 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1593 &ttl, sizeof (ttl));
1596 g_return_if_reached ();
1600 int errsv = get_socket_errno ();
1601 g_warning ("error setting multicast ttl: %s", socket_strerror (errsv));
1605 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1609 * g_socket_get_family:
1610 * @socket: a #GSocket.
1612 * Gets the socket family of the socket.
1614 * Returns: a #GSocketFamily
1619 g_socket_get_family (GSocket *socket)
1621 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1623 return socket->priv->family;
1627 * g_socket_get_socket_type:
1628 * @socket: a #GSocket.
1630 * Gets the socket type of the socket.
1632 * Returns: a #GSocketType
1637 g_socket_get_socket_type (GSocket *socket)
1639 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1641 return socket->priv->type;
1645 * g_socket_get_protocol:
1646 * @socket: a #GSocket.
1648 * Gets the socket protocol id the socket was created with.
1649 * In case the protocol is unknown, -1 is returned.
1651 * Returns: a protocol id, or -1 if unknown
1656 g_socket_get_protocol (GSocket *socket)
1658 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1660 return socket->priv->protocol;
1665 * @socket: a #GSocket.
1667 * Returns the underlying OS socket object. On unix this
1668 * is a socket file descriptor, and on windows this is
1669 * a Winsock2 SOCKET handle. This may be useful for
1670 * doing platform specific or otherwise unusual operations
1673 * Returns: the file descriptor of the socket.
1678 g_socket_get_fd (GSocket *socket)
1680 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1682 return socket->priv->fd;
1686 * g_socket_get_local_address:
1687 * @socket: a #GSocket.
1688 * @error: #GError for error reporting, or %NULL to ignore.
1690 * Try to get the local address of a bound socket. This is only
1691 * useful if the socket has been bound to a local address,
1692 * either explicitly or implicitly when connecting.
1694 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1695 * Free the returned object with g_object_unref().
1700 g_socket_get_local_address (GSocket *socket,
1703 struct sockaddr_storage buffer;
1704 guint32 len = sizeof (buffer);
1706 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1708 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1710 int errsv = get_socket_errno ();
1711 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1712 _("could not get local address: %s"), socket_strerror (errsv));
1716 return g_socket_address_new_from_native (&buffer, len);
1720 * g_socket_get_remote_address:
1721 * @socket: a #GSocket.
1722 * @error: #GError for error reporting, or %NULL to ignore.
1724 * Try to get the remove address of a connected socket. This is only
1725 * useful for connection oriented sockets that have been connected.
1727 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1728 * Free the returned object with g_object_unref().
1733 g_socket_get_remote_address (GSocket *socket,
1736 struct sockaddr_storage buffer;
1737 guint32 len = sizeof (buffer);
1739 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1741 if (socket->priv->connect_pending)
1743 if (!g_socket_check_connect_result (socket, error))
1746 socket->priv->connect_pending = FALSE;
1749 if (!socket->priv->remote_address)
1751 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1753 int errsv = get_socket_errno ();
1754 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1755 _("could not get remote address: %s"), socket_strerror (errsv));
1759 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1762 return g_object_ref (socket->priv->remote_address);
1766 * g_socket_is_connected:
1767 * @socket: a #GSocket.
1769 * Check whether the socket is connected. This is only useful for
1770 * connection-oriented sockets.
1772 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1777 g_socket_is_connected (GSocket *socket)
1779 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1781 return socket->priv->connected;
1786 * @socket: a #GSocket.
1787 * @error: #GError for error reporting, or %NULL to ignore.
1789 * Marks the socket as a server socket, i.e. a socket that is used
1790 * to accept incoming requests using g_socket_accept().
1792 * Before calling this the socket must be bound to a local address using
1795 * To set the maximum amount of outstanding clients, use
1796 * g_socket_set_listen_backlog().
1798 * Returns: %TRUE on success, %FALSE on error.
1803 g_socket_listen (GSocket *socket,
1806 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1808 if (!check_socket (socket, error))
1811 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1813 int errsv = get_socket_errno ();
1815 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1816 _("could not listen: %s"), socket_strerror (errsv));
1820 socket->priv->listening = TRUE;
1827 * @socket: a #GSocket.
1828 * @address: a #GSocketAddress specifying the local address.
1829 * @allow_reuse: whether to allow reusing this address
1830 * @error: #GError for error reporting, or %NULL to ignore.
1832 * When a socket is created it is attached to an address family, but it
1833 * doesn't have an address in this family. g_socket_bind() assigns the
1834 * address (sometimes called name) of the socket.
1836 * It is generally required to bind to a local address before you can
1837 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1838 * In certain situations, you may also want to bind a socket that will be
1839 * used to initiate connections, though this is not normally required.
1841 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1842 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1843 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1844 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1845 * that address was previously used by another socket that has not yet been
1846 * fully cleaned-up by the kernel. Failing to set this flag on a server
1847 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1848 * the server program is stopped and then immediately restarted.)
1850 * Returns: %TRUE on success, %FALSE on error.
1855 g_socket_bind (GSocket *socket,
1856 GSocketAddress *address,
1857 gboolean reuse_address,
1860 struct sockaddr_storage addr;
1862 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1864 if (!check_socket (socket, error))
1867 /* SO_REUSEADDR on windows means something else and is not what we want.
1868 It always allows the unix variant of SO_REUSEADDR anyway */
1873 value = (int) !!reuse_address;
1874 /* Ignore errors here, the only likely error is "not supported", and
1875 this is a "best effort" thing mainly */
1876 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1877 (gpointer) &value, sizeof (value));
1881 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1884 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1885 g_socket_address_get_native_size (address)) < 0)
1887 int errsv = get_socket_errno ();
1889 G_IO_ERROR, socket_io_error_from_errno (errsv),
1890 _("Error binding to address: %s"), socket_strerror (errsv));
1898 g_socket_multicast_group_operation (GSocket *socket,
1899 GInetAddress *group,
1900 gboolean source_specific,
1902 gboolean join_group,
1905 const guint8 *native_addr;
1906 gint optname, result;
1908 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1909 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
1910 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
1911 g_return_val_if_fail (g_inet_address_get_family (group) == socket->priv->family, FALSE);
1913 if (!check_socket (socket, error))
1916 native_addr = g_inet_address_to_bytes (group);
1917 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1919 #ifdef HAVE_IP_MREQN
1920 struct ip_mreqn mc_req;
1922 struct ip_mreq mc_req;
1925 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
1927 #ifdef HAVE_IP_MREQN
1929 mc_req.imr_ifindex = if_nametoindex (iface);
1931 mc_req.imr_ifindex = 0; /* Pick any. */
1933 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
1936 if (source_specific)
1938 #ifdef IP_ADD_SOURCE_MEMBERSHIP
1939 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
1941 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1943 _("Error joining multicast group: %s") :
1944 _("Error leaving multicast group: %s"),
1945 _("No support for source-specific multicast"));
1950 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
1951 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
1952 &mc_req, sizeof (mc_req));
1954 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1956 struct ipv6_mreq mc_req_ipv6;
1958 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
1959 #ifdef HAVE_IF_NAMETOINDEX
1961 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
1964 mc_req_ipv6.ipv6mr_interface = 0;
1966 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
1967 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
1968 &mc_req_ipv6, sizeof (mc_req_ipv6));
1971 g_return_val_if_reached (FALSE);
1975 int errsv = get_socket_errno ();
1977 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1979 _("Error joining multicast group: %s") :
1980 _("Error leaving multicast group: %s"),
1981 socket_strerror (errsv));
1989 * g_socket_join_multicast_group:
1990 * @socket: a #GSocket.
1991 * @group: a #GInetAddress specifying the group address to join.
1992 * @iface: (allow-none): Name of the interface to use, or %NULL
1993 * @source_specific: %TRUE if source-specific multicast should be used
1994 * @error: #GError for error reporting, or %NULL to ignore.
1996 * Registers @socket to receive multicast messages sent to @group.
1997 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
1998 * been bound to an appropriate interface and port with
2001 * If @iface is %NULL, the system will automatically pick an interface
2002 * to bind to based on @group.
2004 * If @source_specific is %TRUE, source-specific multicast as defined
2005 * in RFC 4604 is used. Note that on older platforms this may fail
2006 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2008 * Returns: %TRUE on success, %FALSE on error.
2013 g_socket_join_multicast_group (GSocket *socket,
2014 GInetAddress *group,
2015 gboolean source_specific,
2019 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2023 * g_socket_leave_multicast_group:
2024 * @socket: a #GSocket.
2025 * @group: a #GInetAddress specifying the group address to leave.
2026 * @iface: (allow-none): Interface used
2027 * @source_specific: %TRUE if source-specific multicast was used
2028 * @error: #GError for error reporting, or %NULL to ignore.
2030 * Removes @socket from the multicast group defined by @group, @iface,
2031 * and @source_specific (which must all have the same values they had
2032 * when you joined the group).
2034 * @socket remains bound to its address and port, and can still receive
2035 * unicast messages after calling this.
2037 * Returns: %TRUE on success, %FALSE on error.
2042 g_socket_leave_multicast_group (GSocket *socket,
2043 GInetAddress *group,
2044 gboolean source_specific,
2048 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2052 * g_socket_speaks_ipv4:
2053 * @socket: a #GSocket
2055 * Checks if a socket is capable of speaking IPv4.
2057 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2058 * and under some combinations of circumstances IPv6 sockets are also
2059 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2062 * No other types of sockets are currently considered as being capable
2065 * Returns: %TRUE if this socket can be used with IPv4.
2070 g_socket_speaks_ipv4 (GSocket *socket)
2072 switch (socket->priv->family)
2074 case G_SOCKET_FAMILY_IPV4:
2077 case G_SOCKET_FAMILY_IPV6:
2078 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2080 guint sizeof_int = sizeof (int);
2083 if (getsockopt (socket->priv->fd,
2084 IPPROTO_IPV6, IPV6_V6ONLY,
2085 &v6_only, &sizeof_int) != 0)
2101 * @socket: a #GSocket.
2102 * @cancellable: (allow-none): a %GCancellable or %NULL
2103 * @error: #GError for error reporting, or %NULL to ignore.
2105 * Accept incoming connections on a connection-based socket. This removes
2106 * the first outstanding connection request from the listening socket and
2107 * creates a #GSocket object for it.
2109 * The @socket must be bound to a local address with g_socket_bind() and
2110 * must be listening for incoming connections (g_socket_listen()).
2112 * If there are no outstanding connections then the operation will block
2113 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2114 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2116 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2117 * Free the returned object with g_object_unref().
2122 g_socket_accept (GSocket *socket,
2123 GCancellable *cancellable,
2126 GSocket *new_socket;
2129 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2131 if (!check_socket (socket, error))
2136 if (socket->priv->blocking &&
2137 !g_socket_condition_wait (socket,
2138 G_IO_IN, cancellable, error))
2141 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2143 int errsv = get_socket_errno ();
2145 win32_unset_event_mask (socket, FD_ACCEPT);
2150 if (socket->priv->blocking)
2152 #ifdef WSAEWOULDBLOCK
2153 if (errsv == WSAEWOULDBLOCK)
2156 if (errsv == EWOULDBLOCK ||
2162 g_set_error (error, G_IO_ERROR,
2163 socket_io_error_from_errno (errsv),
2164 _("Error accepting connection: %s"), socket_strerror (errsv));
2170 win32_unset_event_mask (socket, FD_ACCEPT);
2174 /* The socket inherits the accepting sockets event mask and even object,
2175 we need to remove that */
2176 WSAEventSelect (ret, NULL, 0);
2182 /* We always want to set close-on-exec to protect users. If you
2183 need to so some weird inheritance to exec you can re-enable this
2184 using lower level hacks with g_socket_get_fd(). */
2185 flags = fcntl (ret, F_GETFD, 0);
2187 (flags & FD_CLOEXEC) == 0)
2189 flags |= FD_CLOEXEC;
2190 fcntl (ret, F_SETFD, flags);
2195 new_socket = g_socket_new_from_fd (ret, error);
2196 if (new_socket == NULL)
2205 new_socket->priv->protocol = socket->priv->protocol;
2212 * @socket: a #GSocket.
2213 * @address: a #GSocketAddress specifying the remote address.
2214 * @cancellable: (allow-none): a %GCancellable or %NULL
2215 * @error: #GError for error reporting, or %NULL to ignore.
2217 * Connect the socket to the specified remote address.
2219 * For connection oriented socket this generally means we attempt to make
2220 * a connection to the @address. For a connection-less socket it sets
2221 * the default address for g_socket_send() and discards all incoming datagrams
2222 * from other sources.
2224 * Generally connection oriented sockets can only connect once, but
2225 * connection-less sockets can connect multiple times to change the
2228 * If the connect call needs to do network I/O it will block, unless
2229 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2230 * and the user can be notified of the connection finishing by waiting
2231 * for the G_IO_OUT condition. The result of the connection must then be
2232 * checked with g_socket_check_connect_result().
2234 * Returns: %TRUE if connected, %FALSE on error.
2239 g_socket_connect (GSocket *socket,
2240 GSocketAddress *address,
2241 GCancellable *cancellable,
2244 struct sockaddr_storage buffer;
2246 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2248 if (!check_socket (socket, error))
2251 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2254 if (socket->priv->remote_address)
2255 g_object_unref (socket->priv->remote_address);
2256 socket->priv->remote_address = g_object_ref (address);
2260 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2261 g_socket_address_get_native_size (address)) < 0)
2263 int errsv = get_socket_errno ();
2269 if (errsv == EINPROGRESS)
2271 if (errsv == WSAEWOULDBLOCK)
2274 if (socket->priv->blocking)
2276 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2278 if (g_socket_check_connect_result (socket, error))
2284 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2285 _("Connection in progress"));
2286 socket->priv->connect_pending = TRUE;
2290 g_set_error_literal (error, G_IO_ERROR,
2291 socket_io_error_from_errno (errsv),
2292 socket_strerror (errsv));
2299 win32_unset_event_mask (socket, FD_CONNECT);
2301 socket->priv->connected = TRUE;
2307 * g_socket_check_connect_result:
2308 * @socket: a #GSocket
2309 * @error: #GError for error reporting, or %NULL to ignore.
2311 * Checks and resets the pending connect error for the socket.
2312 * This is used to check for errors when g_socket_connect() is
2313 * used in non-blocking mode.
2315 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2320 g_socket_check_connect_result (GSocket *socket,
2326 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2328 if (!check_socket (socket, error))
2331 optlen = sizeof (value);
2332 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
2334 int errsv = get_socket_errno ();
2336 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2337 _("Unable to get pending error: %s"), socket_strerror (errsv));
2343 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2344 socket_strerror (value));
2345 if (socket->priv->remote_address)
2347 g_object_unref (socket->priv->remote_address);
2348 socket->priv->remote_address = NULL;
2353 socket->priv->connected = TRUE;
2358 * g_socket_get_available_bytes:
2359 * @socket: a #GSocket
2361 * Get the amount of data pending in the OS input buffer.
2363 * Returns: the number of bytes that can be read from the socket
2364 * without blocking or -1 on error.
2369 g_socket_get_available_bytes (GSocket *socket)
2377 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2380 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2383 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) == SOCKET_ERROR)
2392 * @socket: a #GSocket
2393 * @buffer: a buffer to read data into (which should be at least @size
2395 * @size: the number of bytes you want to read from the socket
2396 * @cancellable: (allow-none): a %GCancellable or %NULL
2397 * @error: #GError for error reporting, or %NULL to ignore.
2399 * Receive data (up to @size bytes) from a socket. This is mainly used by
2400 * connection-oriented sockets; it is identical to g_socket_receive_from()
2401 * with @address set to %NULL.
2403 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2404 * g_socket_receive() will always read either 0 or 1 complete messages from
2405 * the socket. If the received message is too large to fit in @buffer, then
2406 * the data beyond @size bytes will be discarded, without any explicit
2407 * indication that this has occurred.
2409 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2410 * number of bytes, up to @size. If more than @size bytes have been
2411 * received, the additional data will be returned in future calls to
2412 * g_socket_receive().
2414 * If the socket is in blocking mode the call will block until there
2415 * is some data to receive, the connection is closed, or there is an
2416 * error. If there is no data available and the socket is in
2417 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2418 * returned. To be notified when data is available, wait for the
2419 * %G_IO_IN condition.
2421 * On error -1 is returned and @error is set accordingly.
2423 * Returns: Number of bytes read, or 0 if the connection was closed by
2424 * the peer, or -1 on error
2429 g_socket_receive (GSocket *socket,
2432 GCancellable *cancellable,
2435 return g_socket_receive_with_blocking (socket, buffer, size,
2436 socket->priv->blocking,
2437 cancellable, error);
2441 * g_socket_receive_with_blocking:
2442 * @socket: a #GSocket
2443 * @buffer: a buffer to read data into (which should be at least @size
2445 * @size: the number of bytes you want to read from the socket
2446 * @blocking: whether to do blocking or non-blocking I/O
2447 * @cancellable: (allow-none): a %GCancellable or %NULL
2448 * @error: #GError for error reporting, or %NULL to ignore.
2450 * This behaves exactly the same as g_socket_receive(), except that
2451 * the choice of blocking or non-blocking behavior is determined by
2452 * the @blocking argument rather than by @socket's properties.
2454 * Returns: Number of bytes read, or 0 if the connection was closed by
2455 * the peer, or -1 on error
2460 g_socket_receive_with_blocking (GSocket *socket,
2464 GCancellable *cancellable,
2469 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2471 if (!check_socket (socket, error))
2474 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2480 !g_socket_condition_wait (socket,
2481 G_IO_IN, cancellable, error))
2484 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2486 int errsv = get_socket_errno ();
2493 #ifdef WSAEWOULDBLOCK
2494 if (errsv == WSAEWOULDBLOCK)
2497 if (errsv == EWOULDBLOCK ||
2503 win32_unset_event_mask (socket, FD_READ);
2505 g_set_error (error, G_IO_ERROR,
2506 socket_io_error_from_errno (errsv),
2507 _("Error receiving data: %s"), socket_strerror (errsv));
2511 win32_unset_event_mask (socket, FD_READ);
2520 * g_socket_receive_from:
2521 * @socket: a #GSocket
2522 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2524 * @buffer: (array length=size) (element-type guint8): a buffer to
2525 * read data into (which should be at least @size bytes long).
2526 * @size: the number of bytes you want to read from the socket
2527 * @cancellable: (allow-none): a %GCancellable or %NULL
2528 * @error: #GError for error reporting, or %NULL to ignore.
2530 * Receive data (up to @size bytes) from a socket.
2532 * If @address is non-%NULL then @address will be set equal to the
2533 * source address of the received packet.
2534 * @address is owned by the caller.
2536 * See g_socket_receive() for additional information.
2538 * Returns: Number of bytes read, or 0 if the connection was closed by
2539 * the peer, or -1 on error
2544 g_socket_receive_from (GSocket *socket,
2545 GSocketAddress **address,
2548 GCancellable *cancellable,
2556 return g_socket_receive_message (socket,
2564 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2565 * one, which can be confusing and annoying. So if possible, we want
2566 * to suppress the signal entirely.
2569 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2571 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2576 * @socket: a #GSocket
2577 * @buffer: (array length=size) (element-type guint8): the buffer
2578 * containing the data to send.
2579 * @size: the number of bytes to send
2580 * @cancellable: (allow-none): a %GCancellable or %NULL
2581 * @error: #GError for error reporting, or %NULL to ignore.
2583 * Tries to send @size bytes from @buffer on the socket. This is
2584 * mainly used by connection-oriented sockets; it is identical to
2585 * g_socket_send_to() with @address set to %NULL.
2587 * If the socket is in blocking mode the call will block until there is
2588 * space for the data in the socket queue. If there is no space available
2589 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2590 * will be returned. To be notified when space is available, wait for the
2591 * %G_IO_OUT condition. Note though that you may still receive
2592 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2593 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2594 * very common due to the way the underlying APIs work.)
2596 * On error -1 is returned and @error is set accordingly.
2598 * Returns: Number of bytes written (which may be less than @size), or -1
2604 g_socket_send (GSocket *socket,
2605 const gchar *buffer,
2607 GCancellable *cancellable,
2610 return g_socket_send_with_blocking (socket, buffer, size,
2611 socket->priv->blocking,
2612 cancellable, error);
2616 * g_socket_send_with_blocking:
2617 * @socket: a #GSocket
2618 * @buffer: (array length=size) (element-type guint8): the buffer
2619 * containing the data to send.
2620 * @size: the number of bytes to send
2621 * @blocking: whether to do blocking or non-blocking I/O
2622 * @cancellable: (allow-none): a %GCancellable or %NULL
2623 * @error: #GError for error reporting, or %NULL to ignore.
2625 * This behaves exactly the same as g_socket_send(), except that
2626 * the choice of blocking or non-blocking behavior is determined by
2627 * the @blocking argument rather than by @socket's properties.
2629 * Returns: Number of bytes written (which may be less than @size), or -1
2635 g_socket_send_with_blocking (GSocket *socket,
2636 const gchar *buffer,
2639 GCancellable *cancellable,
2644 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2646 if (!check_socket (socket, error))
2649 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2655 !g_socket_condition_wait (socket,
2656 G_IO_OUT, cancellable, error))
2659 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2661 int errsv = get_socket_errno ();
2666 #ifdef WSAEWOULDBLOCK
2667 if (errsv == WSAEWOULDBLOCK)
2668 win32_unset_event_mask (socket, FD_WRITE);
2673 #ifdef WSAEWOULDBLOCK
2674 if (errsv == WSAEWOULDBLOCK)
2677 if (errsv == EWOULDBLOCK ||
2683 g_set_error (error, G_IO_ERROR,
2684 socket_io_error_from_errno (errsv),
2685 _("Error sending data: %s"), socket_strerror (errsv));
2696 * @socket: a #GSocket
2697 * @address: a #GSocketAddress, or %NULL
2698 * @buffer: (array length=size) (element-type guint8): the buffer
2699 * containing the data to send.
2700 * @size: the number of bytes to send
2701 * @cancellable: (allow-none): a %GCancellable or %NULL
2702 * @error: #GError for error reporting, or %NULL to ignore.
2704 * Tries to send @size bytes from @buffer to @address. If @address is
2705 * %NULL then the message is sent to the default receiver (set by
2706 * g_socket_connect()).
2708 * See g_socket_send() for additional information.
2710 * Returns: Number of bytes written (which may be less than @size), or -1
2716 g_socket_send_to (GSocket *socket,
2717 GSocketAddress *address,
2718 const gchar *buffer,
2720 GCancellable *cancellable,
2728 return g_socket_send_message (socket,
2738 * g_socket_shutdown:
2739 * @socket: a #GSocket
2740 * @shutdown_read: whether to shut down the read side
2741 * @shutdown_write: whether to shut down the write side
2742 * @error: #GError for error reporting, or %NULL to ignore.
2744 * Shut down part of a full-duplex connection.
2746 * If @shutdown_read is %TRUE then the receiving side of the connection
2747 * is shut down, and further reading is disallowed.
2749 * If @shutdown_write is %TRUE then the sending side of the connection
2750 * is shut down, and further writing is disallowed.
2752 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2754 * One example where this is used is graceful disconnect for TCP connections
2755 * where you close the sending side, then wait for the other side to close
2756 * the connection, thus ensuring that the other side saw all sent data.
2758 * Returns: %TRUE on success, %FALSE on error
2763 g_socket_shutdown (GSocket *socket,
2764 gboolean shutdown_read,
2765 gboolean shutdown_write,
2770 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2772 if (!check_socket (socket, error))
2776 if (!shutdown_read && !shutdown_write)
2780 if (shutdown_read && shutdown_write)
2782 else if (shutdown_read)
2787 if (shutdown_read && shutdown_write)
2789 else if (shutdown_read)
2795 if (shutdown (socket->priv->fd, how) != 0)
2797 int errsv = get_socket_errno ();
2798 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2799 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2803 if (shutdown_read && shutdown_write)
2804 socket->priv->connected = FALSE;
2811 * @socket: a #GSocket
2812 * @error: #GError for error reporting, or %NULL to ignore.
2814 * Closes the socket, shutting down any active connection.
2816 * Closing a socket does not wait for all outstanding I/O operations
2817 * to finish, so the caller should not rely on them to be guaranteed
2818 * to complete even if the close returns with no error.
2820 * Once the socket is closed, all other operations will return
2821 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2824 * Sockets will be automatically closed when the last reference
2825 * is dropped, but you might want to call this function to make sure
2826 * resources are released as early as possible.
2828 * Beware that due to the way that TCP works, it is possible for
2829 * recently-sent data to be lost if either you close a socket while the
2830 * %G_IO_IN condition is set, or else if the remote connection tries to
2831 * send something to you after you close the socket but before it has
2832 * finished reading all of the data you sent. There is no easy generic
2833 * way to avoid this problem; the easiest fix is to design the network
2834 * protocol such that the client will never send data "out of turn".
2835 * Another solution is for the server to half-close the connection by
2836 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2837 * and then wait for the client to notice this and close its side of the
2838 * connection, after which the server can safely call g_socket_close().
2839 * (This is what #GTcpConnection does if you call
2840 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2841 * only works if the client will close its connection after the server
2844 * Returns: %TRUE on success, %FALSE on error
2849 g_socket_close (GSocket *socket,
2854 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2856 if (socket->priv->closed)
2857 return TRUE; /* Multiple close not an error */
2859 if (!check_socket (socket, error))
2865 res = closesocket (socket->priv->fd);
2867 res = close (socket->priv->fd);
2871 int errsv = get_socket_errno ();
2876 g_set_error (error, G_IO_ERROR,
2877 socket_io_error_from_errno (errsv),
2878 _("Error closing socket: %s"),
2879 socket_strerror (errsv));
2885 socket->priv->connected = FALSE;
2886 socket->priv->closed = TRUE;
2887 if (socket->priv->remote_address)
2889 g_object_unref (socket->priv->remote_address);
2890 socket->priv->remote_address = NULL;
2897 * g_socket_is_closed:
2898 * @socket: a #GSocket
2900 * Checks whether a socket is closed.
2902 * Returns: %TRUE if socket is closed, %FALSE otherwise
2907 g_socket_is_closed (GSocket *socket)
2909 return socket->priv->closed;
2913 /* Broken source, used on errors */
2915 broken_prepare (GSource *source,
2922 broken_check (GSource *source)
2928 broken_dispatch (GSource *source,
2929 GSourceFunc callback,
2935 static GSourceFuncs broken_funcs =
2944 network_events_for_condition (GIOCondition condition)
2948 if (condition & G_IO_IN)
2949 event_mask |= (FD_READ | FD_ACCEPT);
2950 if (condition & G_IO_OUT)
2951 event_mask |= (FD_WRITE | FD_CONNECT);
2952 event_mask |= FD_CLOSE;
2958 ensure_event (GSocket *socket)
2960 if (socket->priv->event == WSA_INVALID_EVENT)
2961 socket->priv->event = WSACreateEvent();
2965 update_select_events (GSocket *socket)
2972 ensure_event (socket);
2975 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2978 event_mask |= network_events_for_condition (*ptr);
2981 if (event_mask != socket->priv->selected_events)
2983 /* If no events selected, disable event so we can unset
2986 if (event_mask == 0)
2989 event = socket->priv->event;
2991 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2992 socket->priv->selected_events = event_mask;
2997 add_condition_watch (GSocket *socket,
2998 GIOCondition *condition)
3000 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3002 socket->priv->requested_conditions =
3003 g_list_prepend (socket->priv->requested_conditions, condition);
3005 update_select_events (socket);
3009 remove_condition_watch (GSocket *socket,
3010 GIOCondition *condition)
3012 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3014 socket->priv->requested_conditions =
3015 g_list_remove (socket->priv->requested_conditions, condition);
3017 update_select_events (socket);
3021 update_condition (GSocket *socket)
3023 WSANETWORKEVENTS events;
3024 GIOCondition condition;
3026 if (WSAEnumNetworkEvents (socket->priv->fd,
3027 socket->priv->event,
3030 socket->priv->current_events |= events.lNetworkEvents;
3031 if (events.lNetworkEvents & FD_WRITE &&
3032 events.iErrorCode[FD_WRITE_BIT] != 0)
3033 socket->priv->current_errors |= FD_WRITE;
3034 if (events.lNetworkEvents & FD_CONNECT &&
3035 events.iErrorCode[FD_CONNECT_BIT] != 0)
3036 socket->priv->current_errors |= FD_CONNECT;
3040 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3041 condition |= G_IO_IN;
3043 if (socket->priv->current_events & FD_CLOSE ||
3044 socket->priv->closed)
3045 condition |= G_IO_HUP;
3047 /* Never report both G_IO_OUT and HUP, these are
3048 mutually exclusive (can't write to a closed socket) */
3049 if ((condition & G_IO_HUP) == 0 &&
3050 socket->priv->current_events & FD_WRITE)
3052 if (socket->priv->current_errors & FD_WRITE)
3053 condition |= G_IO_ERR;
3055 condition |= G_IO_OUT;
3059 if (socket->priv->current_events & FD_CONNECT)
3061 if (socket->priv->current_errors & FD_CONNECT)
3062 condition |= (G_IO_HUP | G_IO_ERR);
3064 condition |= G_IO_OUT;
3076 GIOCondition condition;
3077 GCancellable *cancellable;
3078 GPollFD cancel_pollfd;
3079 gint64 timeout_time;
3083 socket_source_prepare (GSource *source,
3086 GSocketSource *socket_source = (GSocketSource *)source;
3088 if (g_cancellable_is_cancelled (socket_source->cancellable))
3091 if (socket_source->timeout_time)
3095 now = g_source_get_time (source);
3096 /* Round up to ensure that we don't try again too early */
3097 *timeout = (socket_source->timeout_time - now + 999) / 1000;
3100 socket_source->socket->priv->timed_out = TRUE;
3109 socket_source->pollfd.revents = update_condition (socket_source->socket);
3112 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
3119 socket_source_check (GSource *source)
3123 return socket_source_prepare (source, &timeout);
3127 socket_source_dispatch (GSource *source,
3128 GSourceFunc callback,
3131 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3132 GSocketSource *socket_source = (GSocketSource *)source;
3133 GSocket *socket = socket_source->socket;
3137 socket_source->pollfd.revents = update_condition (socket_source->socket);
3139 if (socket_source->socket->priv->timed_out)
3140 socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
3142 ret = (*func) (socket,
3143 socket_source->pollfd.revents & socket_source->condition,
3146 if (socket->priv->timeout)
3147 socket_source->timeout_time = g_get_monotonic_time () +
3148 socket->priv->timeout * 1000000;
3151 socket_source->timeout_time = 0;
3157 socket_source_finalize (GSource *source)
3159 GSocketSource *socket_source = (GSocketSource *)source;
3162 socket = socket_source->socket;
3165 remove_condition_watch (socket, &socket_source->condition);
3168 g_object_unref (socket);
3170 if (socket_source->cancellable)
3172 g_cancellable_release_fd (socket_source->cancellable);
3173 g_object_unref (socket_source->cancellable);
3178 socket_source_closure_callback (GSocket *socket,
3179 GIOCondition condition,
3182 GClosure *closure = data;
3184 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3185 GValue result_value = G_VALUE_INIT;
3188 g_value_init (&result_value, G_TYPE_BOOLEAN);
3190 g_value_init (¶ms[0], G_TYPE_SOCKET);
3191 g_value_set_object (¶ms[0], socket);
3192 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
3193 g_value_set_flags (¶ms[1], condition);
3195 g_closure_invoke (closure, &result_value, 2, params, NULL);
3197 result = g_value_get_boolean (&result_value);
3198 g_value_unset (&result_value);
3199 g_value_unset (¶ms[0]);
3200 g_value_unset (¶ms[1]);
3205 static GSourceFuncs socket_source_funcs =
3207 socket_source_prepare,
3208 socket_source_check,
3209 socket_source_dispatch,
3210 socket_source_finalize,
3211 (GSourceFunc)socket_source_closure_callback,
3212 (GSourceDummyMarshal)g_cclosure_marshal_generic,
3216 socket_source_new (GSocket *socket,
3217 GIOCondition condition,
3218 GCancellable *cancellable)
3221 GSocketSource *socket_source;
3224 ensure_event (socket);
3226 if (socket->priv->event == WSA_INVALID_EVENT)
3228 g_warning ("Failed to create WSAEvent");
3229 return g_source_new (&broken_funcs, sizeof (GSource));
3233 condition |= G_IO_HUP | G_IO_ERR;
3235 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3236 g_source_set_name (source, "GSocket");
3237 socket_source = (GSocketSource *)source;
3239 socket_source->socket = g_object_ref (socket);
3240 socket_source->condition = condition;
3242 if (g_cancellable_make_pollfd (cancellable,
3243 &socket_source->cancel_pollfd))
3245 socket_source->cancellable = g_object_ref (cancellable);
3246 g_source_add_poll (source, &socket_source->cancel_pollfd);
3250 add_condition_watch (socket, &socket_source->condition);
3251 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3253 socket_source->pollfd.fd = socket->priv->fd;
3256 socket_source->pollfd.events = condition;
3257 socket_source->pollfd.revents = 0;
3258 g_source_add_poll (source, &socket_source->pollfd);
3260 if (socket->priv->timeout)
3261 socket_source->timeout_time = g_get_monotonic_time () +
3262 socket->priv->timeout * 1000000;
3265 socket_source->timeout_time = 0;
3271 * g_socket_create_source: (skip)
3272 * @socket: a #GSocket
3273 * @condition: a #GIOCondition mask to monitor
3274 * @cancellable: (allow-none): a %GCancellable or %NULL
3276 * Creates a %GSource that can be attached to a %GMainContext to monitor
3277 * for the availibility of the specified @condition on the socket.
3279 * The callback on the source is of the #GSocketSourceFunc type.
3281 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3282 * these conditions will always be reported output if they are true.
3284 * @cancellable if not %NULL can be used to cancel the source, which will
3285 * cause the source to trigger, reporting the current condition (which
3286 * is likely 0 unless cancellation happened at the same time as a
3287 * condition change). You can check for this in the callback using
3288 * g_cancellable_is_cancelled().
3290 * If @socket has a timeout set, and it is reached before @condition
3291 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3292 * %G_IO_OUT depending on @condition. However, @socket will have been
3293 * marked as having had a timeout, and so the next #GSocket I/O method
3294 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3296 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3301 g_socket_create_source (GSocket *socket,
3302 GIOCondition condition,
3303 GCancellable *cancellable)
3305 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3307 return socket_source_new (socket, condition, cancellable);
3311 * g_socket_condition_check:
3312 * @socket: a #GSocket
3313 * @condition: a #GIOCondition mask to check
3315 * Checks on the readiness of @socket to perform operations.
3316 * The operations specified in @condition are checked for and masked
3317 * against the currently-satisfied conditions on @socket. The result
3320 * Note that on Windows, it is possible for an operation to return
3321 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3322 * g_socket_condition_check() has claimed that the socket is ready for
3323 * writing. Rather than calling g_socket_condition_check() and then
3324 * writing to the socket if it succeeds, it is generally better to
3325 * simply try writing to the socket right away, and try again later if
3326 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3328 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3329 * these conditions will always be set in the output if they are true.
3331 * This call never blocks.
3333 * Returns: the @GIOCondition mask of the current state
3338 g_socket_condition_check (GSocket *socket,
3339 GIOCondition condition)
3341 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3343 if (!check_socket (socket, NULL))
3348 GIOCondition current_condition;
3350 condition |= G_IO_ERR | G_IO_HUP;
3352 add_condition_watch (socket, &condition);
3353 current_condition = update_condition (socket);
3354 remove_condition_watch (socket, &condition);
3355 return condition & current_condition;
3361 poll_fd.fd = socket->priv->fd;
3362 poll_fd.events = condition;
3365 result = g_poll (&poll_fd, 1, 0);
3366 while (result == -1 && get_socket_errno () == EINTR);
3368 return poll_fd.revents;
3374 * g_socket_condition_wait:
3375 * @socket: a #GSocket
3376 * @condition: a #GIOCondition mask to wait for
3377 * @cancellable: (allow-none): a #GCancellable, or %NULL
3378 * @error: a #GError pointer, or %NULL
3380 * Waits for @condition to become true on @socket. When the condition
3381 * is met, %TRUE is returned.
3383 * If @cancellable is cancelled before the condition is met, or if the
3384 * socket has a timeout set and it is reached before the condition is
3385 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3386 * the appropriate value (%G_IO_ERROR_CANCELLED or
3387 * %G_IO_ERROR_TIMED_OUT).
3389 * Returns: %TRUE if the condition was met, %FALSE otherwise
3394 g_socket_condition_wait (GSocket *socket,
3395 GIOCondition condition,
3396 GCancellable *cancellable,
3399 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3401 if (!check_socket (socket, error))
3404 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3409 GIOCondition current_condition;
3415 /* Always check these */
3416 condition |= G_IO_ERR | G_IO_HUP;
3418 add_condition_watch (socket, &condition);
3421 events[num_events++] = socket->priv->event;
3423 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3424 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3426 if (socket->priv->timeout)
3427 timeout = socket->priv->timeout * 1000;
3429 timeout = WSA_INFINITE;
3431 current_condition = update_condition (socket);
3432 while ((condition & current_condition) == 0)
3434 res = WSAWaitForMultipleEvents(num_events, events,
3435 FALSE, timeout, FALSE);
3436 if (res == WSA_WAIT_FAILED)
3438 int errsv = get_socket_errno ();
3440 g_set_error (error, G_IO_ERROR,
3441 socket_io_error_from_errno (errsv),
3442 _("Waiting for socket condition: %s"),
3443 socket_strerror (errsv));
3446 else if (res == WSA_WAIT_TIMEOUT)
3448 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3449 _("Socket I/O timed out"));
3453 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3456 current_condition = update_condition (socket);
3458 remove_condition_watch (socket, &condition);
3460 g_cancellable_release_fd (cancellable);
3462 return (condition & current_condition) != 0;
3471 poll_fd[0].fd = socket->priv->fd;
3472 poll_fd[0].events = condition;
3475 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3478 if (socket->priv->timeout)
3479 timeout = socket->priv->timeout * 1000;
3484 result = g_poll (poll_fd, num, timeout);
3485 while (result == -1 && get_socket_errno () == EINTR);
3488 g_cancellable_release_fd (cancellable);
3492 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3493 _("Socket I/O timed out"));
3497 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3503 * g_socket_send_message:
3504 * @socket: a #GSocket
3505 * @address: a #GSocketAddress, or %NULL
3506 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3507 * @num_vectors: the number of elements in @vectors, or -1
3508 * @messages: (array length=num_messages) (allow-none): a pointer to an
3509 * array of #GSocketControlMessages, or %NULL.
3510 * @num_messages: number of elements in @messages, or -1.
3511 * @flags: an int containing #GSocketMsgFlags flags
3512 * @cancellable: (allow-none): a %GCancellable or %NULL
3513 * @error: #GError for error reporting, or %NULL to ignore.
3515 * Send data to @address on @socket. This is the most complicated and
3516 * fully-featured version of this call. For easier use, see
3517 * g_socket_send() and g_socket_send_to().
3519 * If @address is %NULL then the message is sent to the default receiver
3520 * (set by g_socket_connect()).
3522 * @vectors must point to an array of #GOutputVector structs and
3523 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3524 * then @vectors is assumed to be terminated by a #GOutputVector with a
3525 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3526 * that the sent data will be gathered from. Using multiple
3527 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3528 * data from multiple sources into a single buffer, and more
3529 * network-efficient than making multiple calls to g_socket_send().
3531 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3532 * #GSocketControlMessage instances. These correspond to the control
3533 * messages to be sent on the socket.
3534 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3537 * @flags modify how the message is sent. The commonly available arguments
3538 * for this are available in the #GSocketMsgFlags enum, but the
3539 * values there are the same as the system values, and the flags
3540 * are passed in as-is, so you can pass in system-specific flags too.
3542 * If the socket is in blocking mode the call will block until there is
3543 * space for the data in the socket queue. If there is no space available
3544 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3545 * will be returned. To be notified when space is available, wait for the
3546 * %G_IO_OUT condition. Note though that you may still receive
3547 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3548 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3549 * very common due to the way the underlying APIs work.)
3551 * On error -1 is returned and @error is set accordingly.
3553 * Returns: Number of bytes written (which may be less than @size), or -1
3559 g_socket_send_message (GSocket *socket,
3560 GSocketAddress *address,
3561 GOutputVector *vectors,
3563 GSocketControlMessage **messages,
3566 GCancellable *cancellable,
3569 GOutputVector one_vector;
3572 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3574 if (!check_socket (socket, error))
3577 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3580 if (num_vectors == -1)
3582 for (num_vectors = 0;
3583 vectors[num_vectors].buffer != NULL;
3588 if (num_messages == -1)
3590 for (num_messages = 0;
3591 messages != NULL && messages[num_messages] != NULL;
3596 if (num_vectors == 0)
3600 one_vector.buffer = &zero;
3601 one_vector.size = 1;
3603 vectors = &one_vector;
3616 msg.msg_namelen = g_socket_address_get_native_size (address);
3617 msg.msg_name = g_alloca (msg.msg_namelen);
3618 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3623 msg.msg_name = NULL;
3624 msg.msg_namelen = 0;
3629 /* this entire expression will be evaluated at compile time */
3630 if (sizeof *msg.msg_iov == sizeof *vectors &&
3631 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3632 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3633 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3634 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3635 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3636 G_STRUCT_OFFSET (GOutputVector, size))
3637 /* ABI is compatible */
3639 msg.msg_iov = (struct iovec *) vectors;
3640 msg.msg_iovlen = num_vectors;
3643 /* ABI is incompatible */
3647 msg.msg_iov = g_newa (struct iovec, num_vectors);
3648 for (i = 0; i < num_vectors; i++)
3650 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3651 msg.msg_iov[i].iov_len = vectors[i].size;
3653 msg.msg_iovlen = num_vectors;
3659 struct cmsghdr *cmsg;
3662 msg.msg_controllen = 0;
3663 for (i = 0; i < num_messages; i++)
3664 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3666 if (msg.msg_controllen == 0)
3667 msg.msg_control = NULL;
3670 msg.msg_control = g_alloca (msg.msg_controllen);
3671 memset (msg.msg_control, '\0', msg.msg_controllen);
3674 cmsg = CMSG_FIRSTHDR (&msg);
3675 for (i = 0; i < num_messages; i++)
3677 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3678 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3679 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3680 g_socket_control_message_serialize (messages[i],
3682 cmsg = CMSG_NXTHDR (&msg, cmsg);
3684 g_assert (cmsg == NULL);
3689 if (socket->priv->blocking &&
3690 !g_socket_condition_wait (socket,
3691 G_IO_OUT, cancellable, error))
3694 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3697 int errsv = get_socket_errno ();
3702 if (socket->priv->blocking &&
3703 (errsv == EWOULDBLOCK ||
3707 g_set_error (error, G_IO_ERROR,
3708 socket_io_error_from_errno (errsv),
3709 _("Error sending message: %s"), socket_strerror (errsv));
3720 struct sockaddr_storage addr;
3727 /* Win32 doesn't support control messages.
3728 Actually this is possible for raw and datagram sockets
3729 via WSASendMessage on Vista or later, but that doesn't
3731 if (num_messages != 0)
3733 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3734 _("GSocketControlMessage not supported on windows"));
3739 bufs = g_newa (WSABUF, num_vectors);
3740 for (i = 0; i < num_vectors; i++)
3742 bufs[i].buf = (char *)vectors[i].buffer;
3743 bufs[i].len = (gulong)vectors[i].size;
3747 addrlen = 0; /* Avoid warning */
3750 addrlen = g_socket_address_get_native_size (address);
3751 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3757 if (socket->priv->blocking &&
3758 !g_socket_condition_wait (socket,
3759 G_IO_OUT, cancellable, error))
3763 result = WSASendTo (socket->priv->fd,
3766 (const struct sockaddr *)&addr, addrlen,
3769 result = WSASend (socket->priv->fd,
3776 int errsv = get_socket_errno ();
3778 if (errsv == WSAEINTR)
3781 if (errsv == WSAEWOULDBLOCK)
3782 win32_unset_event_mask (socket, FD_WRITE);
3784 if (socket->priv->blocking &&
3785 errsv == WSAEWOULDBLOCK)
3788 g_set_error (error, G_IO_ERROR,
3789 socket_io_error_from_errno (errsv),
3790 _("Error sending message: %s"), socket_strerror (errsv));
3803 * g_socket_receive_message:
3804 * @socket: a #GSocket
3805 * @address: (out) (allow-none): a pointer to a #GSocketAddress
3807 * @vectors: (array length=num_vectors): an array of #GInputVector structs
3808 * @num_vectors: the number of elements in @vectors, or -1
3809 * @messages: (array length=num_messages) (allow-none): a pointer which
3810 * may be filled with an array of #GSocketControlMessages, or %NULL
3811 * @num_messages: a pointer which will be filled with the number of
3812 * elements in @messages, or %NULL
3813 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3814 * @cancellable: (allow-none): a %GCancellable or %NULL
3815 * @error: a #GError pointer, or %NULL
3817 * Receive data from a socket. This is the most complicated and
3818 * fully-featured version of this call. For easier use, see
3819 * g_socket_receive() and g_socket_receive_from().
3821 * If @address is non-%NULL then @address will be set equal to the
3822 * source address of the received packet.
3823 * @address is owned by the caller.
3825 * @vector must point to an array of #GInputVector structs and
3826 * @num_vectors must be the length of this array. These structs
3827 * describe the buffers that received data will be scattered into.
3828 * If @num_vectors is -1, then @vectors is assumed to be terminated
3829 * by a #GInputVector with a %NULL buffer pointer.
3831 * As a special case, if @num_vectors is 0 (in which case, @vectors
3832 * may of course be %NULL), then a single byte is received and
3833 * discarded. This is to facilitate the common practice of sending a
3834 * single '\0' byte for the purposes of transferring ancillary data.
3836 * @messages, if non-%NULL, will be set to point to a newly-allocated
3837 * array of #GSocketControlMessage instances or %NULL if no such
3838 * messages was received. These correspond to the control messages
3839 * received from the kernel, one #GSocketControlMessage per message
3840 * from the kernel. This array is %NULL-terminated and must be freed
3841 * by the caller using g_free() after calling g_object_unref() on each
3842 * element. If @messages is %NULL, any control messages received will
3845 * @num_messages, if non-%NULL, will be set to the number of control
3846 * messages received.
3848 * If both @messages and @num_messages are non-%NULL, then
3849 * @num_messages gives the number of #GSocketControlMessage instances
3850 * in @messages (ie: not including the %NULL terminator).
3852 * @flags is an in/out parameter. The commonly available arguments
3853 * for this are available in the #GSocketMsgFlags enum, but the
3854 * values there are the same as the system values, and the flags
3855 * are passed in as-is, so you can pass in system-specific flags too
3856 * (and g_socket_receive_message() may pass system-specific flags out).
3858 * As with g_socket_receive(), data may be discarded if @socket is
3859 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3860 * provide enough buffer space to read a complete message. You can pass
3861 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3862 * removing it from the receive queue, but there is no portable way to find
3863 * out the length of the message other than by reading it into a
3864 * sufficiently-large buffer.
3866 * If the socket is in blocking mode the call will block until there
3867 * is some data to receive, the connection is closed, or there is an
3868 * error. If there is no data available and the socket is in
3869 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3870 * returned. To be notified when data is available, wait for the
3871 * %G_IO_IN condition.
3873 * On error -1 is returned and @error is set accordingly.
3875 * Returns: Number of bytes read, or 0 if the connection was closed by
3876 * the peer, or -1 on error
3881 g_socket_receive_message (GSocket *socket,
3882 GSocketAddress **address,
3883 GInputVector *vectors,
3885 GSocketControlMessage ***messages,
3888 GCancellable *cancellable,
3891 GInputVector one_vector;
3894 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3896 if (!check_socket (socket, error))
3899 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3902 if (num_vectors == -1)
3904 for (num_vectors = 0;
3905 vectors[num_vectors].buffer != NULL;
3910 if (num_vectors == 0)
3912 one_vector.buffer = &one_byte;
3913 one_vector.size = 1;
3915 vectors = &one_vector;
3922 struct sockaddr_storage one_sockaddr;
3927 msg.msg_name = &one_sockaddr;
3928 msg.msg_namelen = sizeof (struct sockaddr_storage);
3932 msg.msg_name = NULL;
3933 msg.msg_namelen = 0;
3937 /* this entire expression will be evaluated at compile time */
3938 if (sizeof *msg.msg_iov == sizeof *vectors &&
3939 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3940 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3941 G_STRUCT_OFFSET (GInputVector, buffer) &&
3942 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3943 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3944 G_STRUCT_OFFSET (GInputVector, size))
3945 /* ABI is compatible */
3947 msg.msg_iov = (struct iovec *) vectors;
3948 msg.msg_iovlen = num_vectors;
3951 /* ABI is incompatible */
3955 msg.msg_iov = g_newa (struct iovec, num_vectors);
3956 for (i = 0; i < num_vectors; i++)
3958 msg.msg_iov[i].iov_base = vectors[i].buffer;
3959 msg.msg_iov[i].iov_len = vectors[i].size;
3961 msg.msg_iovlen = num_vectors;
3965 msg.msg_control = g_alloca (2048);
3966 msg.msg_controllen = 2048;
3970 msg.msg_flags = *flags;
3974 /* We always set the close-on-exec flag so we don't leak file
3975 * descriptors into child processes. Note that gunixfdmessage.c
3976 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
3978 #ifdef MSG_CMSG_CLOEXEC
3979 msg.msg_flags |= MSG_CMSG_CLOEXEC;
3985 if (socket->priv->blocking &&
3986 !g_socket_condition_wait (socket,
3987 G_IO_IN, cancellable, error))
3990 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3991 #ifdef MSG_CMSG_CLOEXEC
3992 if (result < 0 && get_socket_errno () == EINVAL)
3994 /* We must be running on an old kernel. Call without the flag. */
3995 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
3996 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4002 int errsv = get_socket_errno ();
4007 if (socket->priv->blocking &&
4008 (errsv == EWOULDBLOCK ||
4012 g_set_error (error, G_IO_ERROR,
4013 socket_io_error_from_errno (errsv),
4014 _("Error receiving message: %s"), socket_strerror (errsv));
4021 /* decode address */
4022 if (address != NULL)
4024 if (msg.msg_namelen > 0)
4025 *address = g_socket_address_new_from_native (msg.msg_name,
4031 /* decode control messages */
4033 GPtrArray *my_messages = NULL;
4034 struct cmsghdr *cmsg;
4036 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4038 GSocketControlMessage *message;
4040 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4042 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4044 if (message == NULL)
4045 /* We've already spewed about the problem in the
4046 deserialization code, so just continue */
4049 if (messages == NULL)
4051 /* we have to do it this way if the user ignores the
4052 * messages so that we will close any received fds.
4054 g_object_unref (message);
4058 if (my_messages == NULL)
4059 my_messages = g_ptr_array_new ();
4060 g_ptr_array_add (my_messages, message);
4065 *num_messages = my_messages != NULL ? my_messages->len : 0;
4069 if (my_messages == NULL)
4075 g_ptr_array_add (my_messages, NULL);
4076 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4081 g_assert (my_messages == NULL);
4085 /* capture the flags */
4087 *flags = msg.msg_flags;
4093 struct sockaddr_storage addr;
4095 DWORD bytes_received;
4102 bufs = g_newa (WSABUF, num_vectors);
4103 for (i = 0; i < num_vectors; i++)
4105 bufs[i].buf = (char *)vectors[i].buffer;
4106 bufs[i].len = (gulong)vectors[i].size;
4118 if (socket->priv->blocking &&
4119 !g_socket_condition_wait (socket,
4120 G_IO_IN, cancellable, error))
4123 addrlen = sizeof addr;
4125 result = WSARecvFrom (socket->priv->fd,
4127 &bytes_received, &win_flags,
4128 (struct sockaddr *)&addr, &addrlen,
4131 result = WSARecv (socket->priv->fd,
4133 &bytes_received, &win_flags,
4137 int errsv = get_socket_errno ();
4139 if (errsv == WSAEINTR)
4142 win32_unset_event_mask (socket, FD_READ);
4144 if (socket->priv->blocking &&
4145 errsv == WSAEWOULDBLOCK)
4148 g_set_error (error, G_IO_ERROR,
4149 socket_io_error_from_errno (errsv),
4150 _("Error receiving message: %s"), socket_strerror (errsv));
4154 win32_unset_event_mask (socket, FD_READ);
4158 /* decode address */
4159 if (address != NULL)
4162 *address = g_socket_address_new_from_native (&addr, addrlen);
4167 /* capture the flags */
4171 if (messages != NULL)
4173 if (num_messages != NULL)
4176 return bytes_received;
4182 * g_socket_get_credentials:
4183 * @socket: a #GSocket.
4184 * @error: #GError for error reporting, or %NULL to ignore.
4186 * Returns the credentials of the foreign process connected to this
4187 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4190 * If this operation isn't supported on the OS, the method fails with
4191 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4192 * by reading the %SO_PEERCRED option on the underlying socket.
4194 * Other ways to obtain credentials from a foreign peer includes the
4195 * #GUnixCredentialsMessage type and
4196 * g_unix_connection_send_credentials() /
4197 * g_unix_connection_receive_credentials() functions.
4199 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4200 * that must be freed with g_object_unref().
4205 g_socket_get_credentials (GSocket *socket,
4210 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4211 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4215 #if defined(__linux__) || defined(__OpenBSD__)
4218 #if defined(__linux__)
4219 struct ucred native_creds;
4220 optlen = sizeof (struct ucred);
4221 #elif defined(__OpenBSD__)
4222 struct sockpeercred native_creds;
4223 optlen = sizeof (struct sockpeercred);
4225 if (getsockopt (socket->priv->fd,
4228 (void *)&native_creds,
4231 int errsv = get_socket_errno ();
4234 socket_io_error_from_errno (errsv),
4235 _("Unable to get pending error: %s"),
4236 socket_strerror (errsv));
4240 ret = g_credentials_new ();
4241 g_credentials_set_native (ret,
4242 #if defined(__linux__)
4243 G_CREDENTIALS_TYPE_LINUX_UCRED,
4244 #elif defined(__OpenBSD__)
4245 G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
4251 g_set_error_literal (error,
4253 G_IO_ERROR_NOT_SUPPORTED,
4254 _("g_socket_get_credentials not implemented for this OS"));