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>
46 #include "gcancellable.h"
47 #include "gioenumtypes.h"
48 #include "ginetaddress.h"
49 #include "ginitable.h"
53 #include "gnetworkingprivate.h"
54 #include "gsocketaddress.h"
55 #include "gsocketcontrolmessage.h"
62 * @short_description: Low-level socket object
64 * @see_also: #GInitable
66 * A #GSocket is a low-level networking primitive. It is a more or less
67 * direct mapping of the BSD socket API in a portable GObject based API.
68 * It supports both the UNIX socket implementations and winsock2 on Windows.
70 * #GSocket is the platform independent base upon which the higher level
71 * network primitives are based. Applications are not typically meant to
72 * use it directly, but rather through classes like #GSocketClient,
73 * #GSocketService and #GSocketConnection. However there may be cases where
74 * direct use of #GSocket is useful.
76 * #GSocket implements the #GInitable interface, so if it is manually constructed
77 * by e.g. g_object_new() you must call g_initable_init() and check the
78 * results before using the object. This is done automatically in
79 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
82 * Sockets operate in two general modes, blocking or non-blocking. When
83 * in blocking mode all operations block until the requested operation
84 * is finished or there is an error. In non-blocking mode all calls that
85 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
86 * To know when a call would successfully run you can call g_socket_condition_check(),
87 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
88 * attach it to a #GMainContext to get callbacks when I/O is possible.
89 * Note that all sockets are always set to non blocking mode in the system, and
90 * blocking mode is emulated in GSocket.
92 * When working in non-blocking mode applications should always be able to
93 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
94 * function said that I/O was possible. This can easily happen in case
95 * of a race condition in the application, but it can also happen for other
96 * reasons. For instance, on Windows a socket is always seen as writable
97 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
99 * #GSocket<!-- -->s can be either connection oriented or datagram based.
100 * For connection oriented types you must first establish a connection by
101 * either connecting to an address or accepting a connection from another
102 * address. For connectionless socket types the target/source address is
103 * specified or received in each I/O operation.
105 * All socket file descriptors are set to be close-on-exec.
107 * Note that creating a #GSocket causes the signal %SIGPIPE to be
108 * ignored for the remainder of the program. If you are writing a
109 * command-line utility that uses #GSocket, you may need to take into
110 * account the fact that your program will not automatically be killed
111 * if it tries to write to %stdout after it has been closed.
116 static void g_socket_initable_iface_init (GInitableIface *iface);
117 static gboolean g_socket_initable_init (GInitable *initable,
118 GCancellable *cancellable,
121 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
122 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
123 g_socket_initable_iface_init));
140 struct _GSocketPrivate
142 GSocketFamily family;
144 GSocketProtocol protocol;
148 GError *construct_error;
161 GList *requested_conditions; /* list of requested GIOCondition * */
166 get_socket_errno (void)
171 return WSAGetLastError ();
176 socket_io_error_from_errno (int err)
179 return g_io_error_from_errno (err);
184 return G_IO_ERROR_ADDRESS_IN_USE;
186 return G_IO_ERROR_WOULD_BLOCK;
188 return G_IO_ERROR_PERMISSION_DENIED;
189 case WSA_INVALID_HANDLE:
190 case WSA_INVALID_PARAMETER:
193 return G_IO_ERROR_INVALID_ARGUMENT;
194 case WSAEPROTONOSUPPORT:
195 return G_IO_ERROR_NOT_SUPPORTED;
197 return G_IO_ERROR_CANCELLED;
198 case WSAESOCKTNOSUPPORT:
200 case WSAEPFNOSUPPORT:
201 case WSAEAFNOSUPPORT:
202 return G_IO_ERROR_NOT_SUPPORTED;
204 return G_IO_ERROR_FAILED;
210 socket_strerror (int err)
213 return g_strerror (err);
215 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
218 buf = g_static_private_get (&msg_private);
221 buf = g_new (gchar, 128);
222 g_static_private_set (&msg_private, buf, g_free);
225 msg = g_win32_error_message (err);
226 strncpy (buf, msg, 128);
233 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
235 _win32_unset_event_mask (GSocket *socket, int mask)
237 socket->priv->current_events &= ~mask;
238 socket->priv->current_errors &= ~mask;
241 #define win32_unset_event_mask(_socket, _mask)
245 set_fd_nonblocking (int fd)
254 if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
256 g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
260 arg = arg | O_NONBLOCK;
262 if (fcntl (fd, F_SETFL, arg) < 0)
263 g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
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 ();
380 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
381 sizeof address.ss_family <= addrlen);
382 switch (address.ss_family)
384 case G_SOCKET_FAMILY_IPV4:
385 case G_SOCKET_FAMILY_IPV6:
386 case G_SOCKET_FAMILY_UNIX:
387 socket->priv->family = address.ss_family;
391 socket->priv->family = G_SOCKET_FAMILY_INVALID;
395 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
397 addrlen = sizeof address;
398 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
399 socket->priv->connected = TRUE;
402 optlen = sizeof bool_val;
403 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
404 (void *)&bool_val, &optlen) == 0)
407 /* Experimentation indicates that the SO_KEEPALIVE value is
408 * actually a char on Windows, even if documentation claims it
409 * to be a BOOL which is a typedef for int. So this g_assert()
410 * fails. See bug #611756.
412 g_assert (optlen == sizeof bool_val);
414 socket->priv->keepalive = !!bool_val;
418 /* Can't read, maybe not supported, assume FALSE */
419 socket->priv->keepalive = FALSE;
425 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
426 socket_io_error_from_errno (errsv),
427 _("creating GSocket from fd: %s"),
428 socket_strerror (errsv));
432 g_socket_create_socket (GSocketFamily family,
442 case G_SOCKET_TYPE_STREAM:
443 native_type = SOCK_STREAM;
446 case G_SOCKET_TYPE_DATAGRAM:
447 native_type = SOCK_DGRAM;
450 case G_SOCKET_TYPE_SEQPACKET:
451 native_type = SOCK_SEQPACKET;
455 g_assert_not_reached ();
460 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
461 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
466 native_type |= SOCK_CLOEXEC;
468 fd = socket (family, native_type, protocol);
472 int errsv = get_socket_errno ();
474 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
475 _("Unable to create socket: %s"), socket_strerror (errsv));
482 /* We always want to set close-on-exec to protect users. If you
483 need to so some weird inheritance to exec you can re-enable this
484 using lower level hacks with g_socket_get_fd(). */
485 flags = fcntl (fd, F_GETFD, 0);
487 (flags & FD_CLOEXEC) == 0)
490 fcntl (fd, F_SETFD, flags);
499 g_socket_constructed (GObject *object)
501 GSocket *socket = G_SOCKET (object);
503 if (socket->priv->fd >= 0)
504 /* create socket->priv info from the fd */
505 g_socket_details_from_fd (socket);
508 /* create the fd from socket->priv info */
509 socket->priv->fd = g_socket_create_socket (socket->priv->family,
511 socket->priv->protocol,
512 &socket->priv->construct_error);
514 /* Always use native nonblocking sockets, as
515 windows sets sockets to nonblocking automatically
516 in certain operations. This way we make things work
517 the same on all platforms */
518 if (socket->priv->fd != -1)
519 set_fd_nonblocking (socket->priv->fd);
523 g_socket_get_property (GObject *object,
528 GSocket *socket = G_SOCKET (object);
529 GSocketAddress *address;
534 g_value_set_enum (value, socket->priv->family);
538 g_value_set_enum (value, socket->priv->type);
542 g_value_set_enum (value, socket->priv->protocol);
546 g_value_set_int (value, socket->priv->fd);
550 g_value_set_boolean (value, socket->priv->blocking);
553 case PROP_LISTEN_BACKLOG:
554 g_value_set_int (value, socket->priv->listen_backlog);
558 g_value_set_boolean (value, socket->priv->keepalive);
561 case PROP_LOCAL_ADDRESS:
562 address = g_socket_get_local_address (socket, NULL);
563 g_value_take_object (value, address);
566 case PROP_REMOTE_ADDRESS:
567 address = g_socket_get_remote_address (socket, NULL);
568 g_value_take_object (value, address);
572 g_value_set_uint (value, socket->priv->timeout);
576 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
581 g_socket_set_property (GObject *object,
586 GSocket *socket = G_SOCKET (object);
591 socket->priv->family = g_value_get_enum (value);
595 socket->priv->type = g_value_get_enum (value);
599 socket->priv->protocol = g_value_get_enum (value);
603 socket->priv->fd = g_value_get_int (value);
607 g_socket_set_blocking (socket, g_value_get_boolean (value));
610 case PROP_LISTEN_BACKLOG:
611 g_socket_set_listen_backlog (socket, g_value_get_int (value));
615 g_socket_set_keepalive (socket, g_value_get_boolean (value));
619 g_socket_set_timeout (socket, g_value_get_uint (value));
623 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
628 g_socket_finalize (GObject *object)
630 GSocket *socket = G_SOCKET (object);
632 g_clear_error (&socket->priv->construct_error);
634 if (socket->priv->fd != -1 &&
635 !socket->priv->closed)
636 g_socket_close (socket, NULL);
639 if (socket->priv->event != WSA_INVALID_EVENT)
641 WSACloseEvent (socket->priv->event);
642 socket->priv->event = WSA_INVALID_EVENT;
645 g_assert (socket->priv->requested_conditions == NULL);
648 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
649 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
653 g_socket_class_init (GSocketClass *klass)
655 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
658 /* Make sure winsock has been initialized */
659 type = g_inet_address_get_type ();
662 /* There is no portable, thread-safe way to avoid having the process
663 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
664 * forced to simply ignore the signal process-wide.
666 signal (SIGPIPE, SIG_IGN);
669 g_type_class_add_private (klass, sizeof (GSocketPrivate));
671 gobject_class->finalize = g_socket_finalize;
672 gobject_class->constructed = g_socket_constructed;
673 gobject_class->set_property = g_socket_set_property;
674 gobject_class->get_property = g_socket_get_property;
676 g_object_class_install_property (gobject_class, PROP_FAMILY,
677 g_param_spec_enum ("family",
679 P_("The sockets address family"),
680 G_TYPE_SOCKET_FAMILY,
681 G_SOCKET_FAMILY_INVALID,
682 G_PARAM_CONSTRUCT_ONLY |
684 G_PARAM_STATIC_STRINGS));
686 g_object_class_install_property (gobject_class, PROP_TYPE,
687 g_param_spec_enum ("type",
689 P_("The sockets type"),
691 G_SOCKET_TYPE_STREAM,
692 G_PARAM_CONSTRUCT_ONLY |
694 G_PARAM_STATIC_STRINGS));
696 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
697 g_param_spec_enum ("protocol",
698 P_("Socket protocol"),
699 P_("The id of the protocol to use, or -1 for unknown"),
700 G_TYPE_SOCKET_PROTOCOL,
701 G_SOCKET_PROTOCOL_UNKNOWN,
702 G_PARAM_CONSTRUCT_ONLY |
704 G_PARAM_STATIC_STRINGS));
706 g_object_class_install_property (gobject_class, PROP_FD,
707 g_param_spec_int ("fd",
708 P_("File descriptor"),
709 P_("The sockets file descriptor"),
713 G_PARAM_CONSTRUCT_ONLY |
715 G_PARAM_STATIC_STRINGS));
717 g_object_class_install_property (gobject_class, PROP_BLOCKING,
718 g_param_spec_boolean ("blocking",
720 P_("Whether or not I/O on this socket is blocking"),
723 G_PARAM_STATIC_STRINGS));
725 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
726 g_param_spec_int ("listen-backlog",
727 P_("Listen backlog"),
728 P_("Outstanding connections in the listen queue"),
733 G_PARAM_STATIC_STRINGS));
735 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
736 g_param_spec_boolean ("keepalive",
737 P_("Keep connection alive"),
738 P_("Keep connection alive by sending periodic pings"),
741 G_PARAM_STATIC_STRINGS));
743 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
744 g_param_spec_object ("local-address",
746 P_("The local address the socket is bound to"),
747 G_TYPE_SOCKET_ADDRESS,
749 G_PARAM_STATIC_STRINGS));
751 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
752 g_param_spec_object ("remote-address",
753 P_("Remote address"),
754 P_("The remote address the socket is connected to"),
755 G_TYPE_SOCKET_ADDRESS,
757 G_PARAM_STATIC_STRINGS));
762 * The timeout in seconds on socket I/O
766 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
767 g_param_spec_uint ("timeout",
769 P_("The timeout in seconds on socket I/O"),
774 G_PARAM_STATIC_STRINGS));
778 g_socket_initable_iface_init (GInitableIface *iface)
780 iface->init = g_socket_initable_init;
784 g_socket_init (GSocket *socket)
786 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
788 socket->priv->fd = -1;
789 socket->priv->blocking = TRUE;
790 socket->priv->listen_backlog = 10;
791 socket->priv->construct_error = NULL;
793 socket->priv->event = WSA_INVALID_EVENT;
798 g_socket_initable_init (GInitable *initable,
799 GCancellable *cancellable,
804 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
806 socket = G_SOCKET (initable);
808 if (cancellable != NULL)
810 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
811 _("Cancellable initialization not supported"));
815 socket->priv->inited = TRUE;
817 if (socket->priv->construct_error)
820 *error = g_error_copy (socket->priv->construct_error);
830 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
831 * @type: the socket type to use.
832 * @protocol: the id of the protocol to use, or 0 for default.
833 * @error: #GError for error reporting, or %NULL to ignore.
835 * Creates a new #GSocket with the defined family, type and protocol.
836 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
837 * for the family and type is used.
839 * The @protocol is a family and type specific int that specifies what
840 * kind of protocol to use. #GSocketProtocol lists several common ones.
841 * Many families only support one protocol, and use 0 for this, others
842 * support several and using 0 means to use the default protocol for
843 * the family and type.
845 * The protocol id is passed directly to the operating
846 * system, so you can use protocols not listed in #GSocketProtocol if you
847 * know the protocol number used for it.
849 * Returns: a #GSocket or %NULL on error.
850 * Free the returned object with g_object_unref().
855 g_socket_new (GSocketFamily family,
857 GSocketProtocol protocol,
860 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
864 "protocol", protocol,
869 * g_socket_new_from_fd:
870 * @fd: a native socket file descriptor.
871 * @error: #GError for error reporting, or %NULL to ignore.
873 * Creates a new #GSocket from a native file descriptor
874 * or winsock SOCKET handle.
876 * This reads all the settings from the file descriptor so that
877 * all properties should work. Note that the file descriptor
878 * will be set to non-blocking mode, independent on the blocking
879 * mode of the #GSocket.
881 * Returns: a #GSocket or %NULL on error.
882 * Free the returned object with g_object_unref().
887 g_socket_new_from_fd (gint fd,
890 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
897 * g_socket_set_blocking:
898 * @socket: a #GSocket.
899 * @blocking: Whether to use blocking I/O or not.
901 * Sets the blocking mode of the socket. In blocking mode
902 * all operations block until they succeed or there is an error. In
903 * non-blocking mode all functions return results immediately or
904 * with a %G_IO_ERROR_WOULD_BLOCK error.
906 * All sockets are created in blocking mode. However, note that the
907 * platform level socket is always non-blocking, and blocking mode
908 * is a GSocket level feature.
913 g_socket_set_blocking (GSocket *socket,
916 g_return_if_fail (G_IS_SOCKET (socket));
918 blocking = !!blocking;
920 if (socket->priv->blocking == blocking)
923 socket->priv->blocking = blocking;
924 g_object_notify (G_OBJECT (socket), "blocking");
928 * g_socket_get_blocking:
929 * @socket: a #GSocket.
931 * Gets the blocking mode of the socket. For details on blocking I/O,
932 * see g_socket_set_blocking().
934 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
939 g_socket_get_blocking (GSocket *socket)
941 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
943 return socket->priv->blocking;
947 * g_socket_set_keepalive:
948 * @socket: a #GSocket.
949 * @keepalive: Value for the keepalive flag
951 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
952 * this flag is set on a socket, the system will attempt to verify that the
953 * remote socket endpoint is still present if a sufficiently long period of
954 * time passes with no data being exchanged. If the system is unable to
955 * verify the presence of the remote endpoint, it will automatically close
958 * This option is only functional on certain kinds of sockets. (Notably,
959 * %G_SOCKET_PROTOCOL_TCP sockets.)
961 * The exact time between pings is system- and protocol-dependent, but will
962 * normally be at least two hours. Most commonly, you would set this flag
963 * on a server socket if you want to allow clients to remain idle for long
964 * periods of time, but also want to ensure that connections are eventually
965 * garbage-collected if clients crash or become unreachable.
970 g_socket_set_keepalive (GSocket *socket,
975 g_return_if_fail (G_IS_SOCKET (socket));
977 keepalive = !!keepalive;
978 if (socket->priv->keepalive == keepalive)
981 value = (gint) keepalive;
982 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
983 (gpointer) &value, sizeof (value)) < 0)
985 int errsv = get_socket_errno ();
986 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
990 socket->priv->keepalive = keepalive;
991 g_object_notify (G_OBJECT (socket), "keepalive");
995 * g_socket_get_keepalive:
996 * @socket: a #GSocket.
998 * Gets the keepalive mode of the socket. For details on this,
999 * see g_socket_set_keepalive().
1001 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1006 g_socket_get_keepalive (GSocket *socket)
1008 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1010 return socket->priv->keepalive;
1014 * g_socket_get_listen_backlog:
1015 * @socket: a #GSocket.
1017 * Gets the listen backlog setting of the socket. For details on this,
1018 * see g_socket_set_listen_backlog().
1020 * Returns: the maximum number of pending connections.
1025 g_socket_get_listen_backlog (GSocket *socket)
1027 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1029 return socket->priv->listen_backlog;
1033 * g_socket_set_listen_backlog:
1034 * @socket: a #GSocket.
1035 * @backlog: the maximum number of pending connections.
1037 * Sets the maximum number of outstanding connections allowed
1038 * when listening on this socket. If more clients than this are
1039 * connecting to the socket and the application is not handling them
1040 * on time then the new connections will be refused.
1042 * Note that this must be called before g_socket_listen() and has no
1043 * effect if called after that.
1048 g_socket_set_listen_backlog (GSocket *socket,
1051 g_return_if_fail (G_IS_SOCKET (socket));
1052 g_return_if_fail (!socket->priv->listening);
1054 if (backlog != socket->priv->listen_backlog)
1056 socket->priv->listen_backlog = backlog;
1057 g_object_notify (G_OBJECT (socket), "listen-backlog");
1062 * g_socket_get_timeout:
1063 * @socket: a #GSocket.
1065 * Gets the timeout setting of the socket. For details on this, see
1066 * g_socket_set_timeout().
1068 * Returns: the timeout in seconds
1073 g_socket_get_timeout (GSocket *socket)
1075 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1077 return socket->priv->timeout;
1081 * g_socket_set_timeout:
1082 * @socket: a #GSocket.
1083 * @timeout: the timeout for @socket, in seconds, or 0 for none
1085 * Sets the time in seconds after which I/O operations on @socket will
1086 * time out if they have not yet completed.
1088 * On a blocking socket, this means that any blocking #GSocket
1089 * operation will time out after @timeout seconds of inactivity,
1090 * returning %G_IO_ERROR_TIMED_OUT.
1092 * On a non-blocking socket, calls to g_socket_condition_wait() will
1093 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1094 * created with g_socket_create_source() will trigger after
1095 * @timeout seconds of inactivity, with the requested condition
1096 * set, at which point calling g_socket_receive(), g_socket_send(),
1097 * g_socket_check_connect_result(), etc, will fail with
1098 * %G_IO_ERROR_TIMED_OUT.
1100 * If @timeout is 0 (the default), operations will never time out
1103 * Note that if an I/O operation is interrupted by a signal, this may
1104 * cause the timeout to be reset.
1109 g_socket_set_timeout (GSocket *socket,
1112 g_return_if_fail (G_IS_SOCKET (socket));
1114 if (timeout != socket->priv->timeout)
1116 socket->priv->timeout = timeout;
1117 g_object_notify (G_OBJECT (socket), "timeout");
1122 * g_socket_get_family:
1123 * @socket: a #GSocket.
1125 * Gets the socket family of the socket.
1127 * Returns: a #GSocketFamily
1132 g_socket_get_family (GSocket *socket)
1134 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1136 return socket->priv->family;
1140 * g_socket_get_socket_type:
1141 * @socket: a #GSocket.
1143 * Gets the socket type of the socket.
1145 * Returns: a #GSocketType
1150 g_socket_get_socket_type (GSocket *socket)
1152 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1154 return socket->priv->type;
1158 * g_socket_get_protocol:
1159 * @socket: a #GSocket.
1161 * Gets the socket protocol id the socket was created with.
1162 * In case the protocol is unknown, -1 is returned.
1164 * Returns: a protocol id, or -1 if unknown
1169 g_socket_get_protocol (GSocket *socket)
1171 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1173 return socket->priv->protocol;
1178 * @socket: a #GSocket.
1180 * Returns the underlying OS socket object. On unix this
1181 * is a socket file descriptor, and on windows this is
1182 * a Winsock2 SOCKET handle. This may be useful for
1183 * doing platform specific or otherwise unusual operations
1186 * Returns: the file descriptor of the socket.
1191 g_socket_get_fd (GSocket *socket)
1193 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1195 return socket->priv->fd;
1199 * g_socket_get_local_address:
1200 * @socket: a #GSocket.
1201 * @error: #GError for error reporting, or %NULL to ignore.
1203 * Try to get the local address of a bound socket. This is only
1204 * useful if the socket has been bound to a local address,
1205 * either explicitly or implicitly when connecting.
1207 * Returns: a #GSocketAddress or %NULL on error.
1208 * Free the returned object with g_object_unref().
1213 g_socket_get_local_address (GSocket *socket,
1216 struct sockaddr_storage buffer;
1217 guint32 len = sizeof (buffer);
1219 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1221 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1223 int errsv = get_socket_errno ();
1224 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1225 _("could not get local address: %s"), socket_strerror (errsv));
1229 return g_socket_address_new_from_native (&buffer, len);
1233 * g_socket_get_remote_address:
1234 * @socket: a #GSocket.
1235 * @error: #GError for error reporting, or %NULL to ignore.
1237 * Try to get the remove address of a connected socket. This is only
1238 * useful for connection oriented sockets that have been connected.
1240 * Returns: a #GSocketAddress or %NULL on error.
1241 * Free the returned object with g_object_unref().
1246 g_socket_get_remote_address (GSocket *socket,
1249 struct sockaddr_storage buffer;
1250 guint32 len = sizeof (buffer);
1252 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1254 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1256 int errsv = get_socket_errno ();
1257 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1258 _("could not get remote address: %s"), socket_strerror (errsv));
1262 return g_socket_address_new_from_native (&buffer, len);
1266 * g_socket_is_connected:
1267 * @socket: a #GSocket.
1269 * Check whether the socket is connected. This is only useful for
1270 * connection-oriented sockets.
1272 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1277 g_socket_is_connected (GSocket *socket)
1279 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1281 return socket->priv->connected;
1286 * @socket: a #GSocket.
1287 * @error: #GError for error reporting, or %NULL to ignore.
1289 * Marks the socket as a server socket, i.e. a socket that is used
1290 * to accept incoming requests using g_socket_accept().
1292 * Before calling this the socket must be bound to a local address using
1295 * To set the maximum amount of outstanding clients, use
1296 * g_socket_set_listen_backlog().
1298 * Returns: %TRUE on success, %FALSE on error.
1303 g_socket_listen (GSocket *socket,
1306 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1308 if (!check_socket (socket, error))
1311 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1313 int errsv = get_socket_errno ();
1315 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1316 _("could not listen: %s"), socket_strerror (errsv));
1320 socket->priv->listening = TRUE;
1327 * @socket: a #GSocket.
1328 * @address: a #GSocketAddress specifying the local address.
1329 * @allow_reuse: whether to allow reusing this address
1330 * @error: #GError for error reporting, or %NULL to ignore.
1332 * When a socket is created it is attached to an address family, but it
1333 * doesn't have an address in this family. g_socket_bind() assigns the
1334 * address (sometimes called name) of the socket.
1336 * It is generally required to bind to a local address before you can
1337 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1338 * In certain situations, you may also want to bind a socket that will be
1339 * used to initiate connections, though this is not normally required.
1341 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1342 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1343 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1344 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1345 * that address was previously used by another socket that has not yet been
1346 * fully cleaned-up by the kernel. Failing to set this flag on a server
1347 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1348 * the server program is stopped and then immediately restarted.)
1350 * Returns: %TRUE on success, %FALSE on error.
1355 g_socket_bind (GSocket *socket,
1356 GSocketAddress *address,
1357 gboolean reuse_address,
1360 struct sockaddr_storage addr;
1362 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1364 if (!check_socket (socket, error))
1367 /* SO_REUSEADDR on windows means something else and is not what we want.
1368 It always allows the unix variant of SO_REUSEADDR anyway */
1373 value = (int) !!reuse_address;
1374 /* Ignore errors here, the only likely error is "not supported", and
1375 this is a "best effort" thing mainly */
1376 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1377 (gpointer) &value, sizeof (value));
1381 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1384 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1385 g_socket_address_get_native_size (address)) < 0)
1387 int errsv = get_socket_errno ();
1389 G_IO_ERROR, socket_io_error_from_errno (errsv),
1390 _("Error binding to address: %s"), socket_strerror (errsv));
1398 * g_socket_speaks_ipv4:
1399 * @socket: a #GSocket
1401 * Checks if a socket is capable of speaking IPv4.
1403 * IPv4 sockets are capable of speaking IPv4. On some operating systems
1404 * and under some combinations of circumstances IPv6 sockets are also
1405 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
1408 * No other types of sockets are currently considered as being capable
1411 * Returns: %TRUE if this socket can be used with IPv4.
1416 g_socket_speaks_ipv4 (GSocket *socket)
1418 switch (socket->priv->family)
1420 case G_SOCKET_FAMILY_IPV4:
1423 case G_SOCKET_FAMILY_IPV6:
1424 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1426 guint sizeof_int = sizeof (int);
1429 if (getsockopt (socket->priv->fd,
1430 IPPROTO_IPV6, IPV6_V6ONLY,
1431 &v6_only, &sizeof_int) != 0)
1447 * @socket: a #GSocket.
1448 * @cancellable: a %GCancellable or %NULL
1449 * @error: #GError for error reporting, or %NULL to ignore.
1451 * Accept incoming connections on a connection-based socket. This removes
1452 * the first outstanding connection request from the listening socket and
1453 * creates a #GSocket object for it.
1455 * The @socket must be bound to a local address with g_socket_bind() and
1456 * must be listening for incoming connections (g_socket_listen()).
1458 * If there are no outstanding connections then the operation will block
1459 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1460 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1462 * Returns: a new #GSocket, or %NULL on error.
1463 * Free the returned object with g_object_unref().
1468 g_socket_accept (GSocket *socket,
1469 GCancellable *cancellable,
1472 GSocket *new_socket;
1475 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1477 if (!check_socket (socket, error))
1482 if (socket->priv->blocking &&
1483 !g_socket_condition_wait (socket,
1484 G_IO_IN, cancellable, error))
1487 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1489 int errsv = get_socket_errno ();
1491 win32_unset_event_mask (socket, FD_ACCEPT);
1496 if (socket->priv->blocking)
1498 #ifdef WSAEWOULDBLOCK
1499 if (errsv == WSAEWOULDBLOCK)
1502 if (errsv == EWOULDBLOCK ||
1508 g_set_error (error, G_IO_ERROR,
1509 socket_io_error_from_errno (errsv),
1510 _("Error accepting connection: %s"), socket_strerror (errsv));
1516 win32_unset_event_mask (socket, FD_ACCEPT);
1520 /* The socket inherits the accepting sockets event mask and even object,
1521 we need to remove that */
1522 WSAEventSelect (ret, NULL, 0);
1528 /* We always want to set close-on-exec to protect users. If you
1529 need to so some weird inheritance to exec you can re-enable this
1530 using lower level hacks with g_socket_get_fd(). */
1531 flags = fcntl (ret, F_GETFD, 0);
1533 (flags & FD_CLOEXEC) == 0)
1535 flags |= FD_CLOEXEC;
1536 fcntl (ret, F_SETFD, flags);
1541 new_socket = g_socket_new_from_fd (ret, error);
1542 if (new_socket == NULL)
1551 new_socket->priv->protocol = socket->priv->protocol;
1558 * @socket: a #GSocket.
1559 * @address: a #GSocketAddress specifying the remote address.
1560 * @cancellable: a %GCancellable or %NULL
1561 * @error: #GError for error reporting, or %NULL to ignore.
1563 * Connect the socket to the specified remote address.
1565 * For connection oriented socket this generally means we attempt to make
1566 * a connection to the @address. For a connection-less socket it sets
1567 * the default address for g_socket_send() and discards all incoming datagrams
1568 * from other sources.
1570 * Generally connection oriented sockets can only connect once, but
1571 * connection-less sockets can connect multiple times to change the
1574 * If the connect call needs to do network I/O it will block, unless
1575 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1576 * and the user can be notified of the connection finishing by waiting
1577 * for the G_IO_OUT condition. The result of the connection can then be
1578 * checked with g_socket_check_connect_result().
1580 * Returns: %TRUE if connected, %FALSE on error.
1585 g_socket_connect (GSocket *socket,
1586 GSocketAddress *address,
1587 GCancellable *cancellable,
1590 struct sockaddr_storage buffer;
1592 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1594 if (!check_socket (socket, error))
1597 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1602 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1603 g_socket_address_get_native_size (address)) < 0)
1605 int errsv = get_socket_errno ();
1611 if (errsv == EINPROGRESS)
1613 if (errsv == WSAEWOULDBLOCK)
1616 if (socket->priv->blocking)
1618 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
1620 if (g_socket_check_connect_result (socket, error))
1623 g_prefix_error (error, _("Error connecting: "));
1626 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1627 _("Connection in progress"));
1630 g_set_error (error, G_IO_ERROR,
1631 socket_io_error_from_errno (errsv),
1632 _("Error connecting: %s"), socket_strerror (errsv));
1639 win32_unset_event_mask (socket, FD_CONNECT);
1641 socket->priv->connected = TRUE;
1647 * g_socket_check_connect_result:
1648 * @socket: a #GSocket
1649 * @error: #GError for error reporting, or %NULL to ignore.
1651 * Checks and resets the pending connect error for the socket.
1652 * This is used to check for errors when g_socket_connect() is
1653 * used in non-blocking mode.
1655 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1660 g_socket_check_connect_result (GSocket *socket,
1666 if (!check_socket (socket, error))
1669 optlen = sizeof (value);
1670 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1672 int errsv = get_socket_errno ();
1674 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1675 _("Unable to get pending error: %s"), socket_strerror (errsv));
1681 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1682 socket_strerror (value));
1690 * @socket: a #GSocket
1691 * @buffer: a buffer to read data into (which should be at least @size
1693 * @size: the number of bytes you want to read from the socket
1694 * @cancellable: a %GCancellable or %NULL
1695 * @error: #GError for error reporting, or %NULL to ignore.
1697 * Receive data (up to @size bytes) from a socket. This is mainly used by
1698 * connection-oriented sockets; it is identical to g_socket_receive_from()
1699 * with @address set to %NULL.
1701 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1702 * g_socket_receive() will always read either 0 or 1 complete messages from
1703 * the socket. If the received message is too large to fit in @buffer, then
1704 * the data beyond @size bytes will be discarded, without any explicit
1705 * indication that this has occurred.
1707 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1708 * number of bytes, up to @size. If more than @size bytes have been
1709 * received, the additional data will be returned in future calls to
1710 * g_socket_receive().
1712 * If the socket is in blocking mode the call will block until there is
1713 * some data to receive or there is an error. If there is no data available
1714 * and the socket is in non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error
1715 * will be returned. To be notified when data is available, wait for the
1716 * %G_IO_IN condition.
1718 * On error -1 is returned and @error is set accordingly.
1720 * Returns: Number of bytes read, or -1 on error
1725 g_socket_receive (GSocket *socket,
1728 GCancellable *cancellable,
1733 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1735 if (!check_socket (socket, error))
1738 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1743 if (socket->priv->blocking &&
1744 !g_socket_condition_wait (socket,
1745 G_IO_IN, cancellable, error))
1748 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1750 int errsv = get_socket_errno ();
1755 if (socket->priv->blocking)
1757 #ifdef WSAEWOULDBLOCK
1758 if (errsv == WSAEWOULDBLOCK)
1761 if (errsv == EWOULDBLOCK ||
1767 win32_unset_event_mask (socket, FD_READ);
1769 g_set_error (error, G_IO_ERROR,
1770 socket_io_error_from_errno (errsv),
1771 _("Error receiving data: %s"), socket_strerror (errsv));
1775 win32_unset_event_mask (socket, FD_READ);
1784 * g_socket_receive_from:
1785 * @socket: a #GSocket
1786 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1787 * @buffer: a buffer to read data into (which should be at least @size
1789 * @size: the number of bytes you want to read from the socket
1790 * @cancellable: a %GCancellable or %NULL
1791 * @error: #GError for error reporting, or %NULL to ignore.
1793 * Receive data (up to @size bytes) from a socket.
1795 * If @address is non-%NULL then @address will be set equal to the
1796 * source address of the received packet.
1797 * @address is owned by the caller.
1799 * See g_socket_receive() for additional information.
1801 * Returns: Number of bytes read, or -1 on error
1806 g_socket_receive_from (GSocket *socket,
1807 GSocketAddress **address,
1810 GCancellable *cancellable,
1818 return g_socket_receive_message (socket,
1826 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1827 * one, which can be confusing and annoying. So if possible, we want
1828 * to suppress the signal entirely.
1831 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1833 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1838 * @socket: a #GSocket
1839 * @buffer: the buffer containing the data to send.
1840 * @size: the number of bytes to send
1841 * @cancellable: a %GCancellable or %NULL
1842 * @error: #GError for error reporting, or %NULL to ignore.
1844 * Tries to send @size bytes from @buffer on the socket. This is
1845 * mainly used by connection-oriented sockets; it is identical to
1846 * g_socket_send_to() with @address set to %NULL.
1848 * If the socket is in blocking mode the call will block until there is
1849 * space for the data in the socket queue. If there is no space available
1850 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1851 * will be returned. To be notified when space is available, wait for the
1852 * %G_IO_OUT condition. Note though that you may still receive
1853 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1854 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1855 * very common due to the way the underlying APIs work.)
1857 * On error -1 is returned and @error is set accordingly.
1859 * Returns: Number of bytes written (which may be less than @size), or -1
1865 g_socket_send (GSocket *socket,
1866 const gchar *buffer,
1868 GCancellable *cancellable,
1873 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1875 if (!check_socket (socket, error))
1878 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1883 if (socket->priv->blocking &&
1884 !g_socket_condition_wait (socket,
1885 G_IO_OUT, cancellable, error))
1888 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
1890 int errsv = get_socket_errno ();
1895 #ifdef WSAEWOULDBLOCK
1896 if (errsv == WSAEWOULDBLOCK)
1897 win32_unset_event_mask (socket, FD_WRITE);
1900 if (socket->priv->blocking)
1902 #ifdef WSAEWOULDBLOCK
1903 if (errsv == WSAEWOULDBLOCK)
1906 if (errsv == EWOULDBLOCK ||
1912 g_set_error (error, G_IO_ERROR,
1913 socket_io_error_from_errno (errsv),
1914 _("Error sending data: %s"), socket_strerror (errsv));
1925 * @socket: a #GSocket
1926 * @address: a #GSocketAddress, or %NULL
1927 * @buffer: the buffer containing the data to send.
1928 * @size: the number of bytes to send
1929 * @cancellable: a %GCancellable or %NULL
1930 * @error: #GError for error reporting, or %NULL to ignore.
1932 * Tries to send @size bytes from @buffer to @address. If @address is
1933 * %NULL then the message is sent to the default receiver (set by
1934 * g_socket_connect()).
1936 * See g_socket_send() for additional information.
1938 * Returns: Number of bytes written (which may be less than @size), or -1
1944 g_socket_send_to (GSocket *socket,
1945 GSocketAddress *address,
1946 const gchar *buffer,
1948 GCancellable *cancellable,
1956 return g_socket_send_message (socket,
1966 * g_socket_shutdown:
1967 * @socket: a #GSocket
1968 * @shutdown_read: whether to shut down the read side
1969 * @shutdown_write: whether to shut down the write side
1970 * @error: #GError for error reporting, or %NULL to ignore.
1972 * Shut down part of a full-duplex connection.
1974 * If @shutdown_read is %TRUE then the recieving side of the connection
1975 * is shut down, and further reading is disallowed.
1977 * If @shutdown_write is %TRUE then the sending side of the connection
1978 * is shut down, and further writing is disallowed.
1980 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
1982 * One example where this is used is graceful disconnect for TCP connections
1983 * where you close the sending side, then wait for the other side to close
1984 * the connection, thus ensuring that the other side saw all sent data.
1986 * Returns: %TRUE on success, %FALSE on error
1991 g_socket_shutdown (GSocket *socket,
1992 gboolean shutdown_read,
1993 gboolean shutdown_write,
1998 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2000 if (!check_socket (socket, NULL))
2004 if (!shutdown_read && !shutdown_write)
2008 if (shutdown_read && shutdown_write)
2010 else if (shutdown_read)
2015 if (shutdown_read && shutdown_write)
2017 else if (shutdown_read)
2023 if (shutdown (socket->priv->fd, how) != 0)
2025 int errsv = get_socket_errno ();
2026 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2027 _("Unable to create socket: %s"), socket_strerror (errsv));
2031 if (shutdown_read && shutdown_write)
2032 socket->priv->connected = FALSE;
2039 * @socket: a #GSocket
2040 * @error: #GError for error reporting, or %NULL to ignore.
2042 * Closes the socket, shutting down any active connection.
2044 * Closing a socket does not wait for all outstanding I/O operations
2045 * to finish, so the caller should not rely on them to be guaranteed
2046 * to complete even if the close returns with no error.
2048 * Once the socket is closed, all other operations will return
2049 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2052 * Sockets will be automatically closed when the last reference
2053 * is dropped, but you might want to call this function to make sure
2054 * resources are released as early as possible.
2056 * Beware that due to the way that TCP works, it is possible for
2057 * recently-sent data to be lost if either you close a socket while the
2058 * %G_IO_IN condition is set, or else if the remote connection tries to
2059 * send something to you after you close the socket but before it has
2060 * finished reading all of the data you sent. There is no easy generic
2061 * way to avoid this problem; the easiest fix is to design the network
2062 * protocol such that the client will never send data "out of turn".
2063 * Another solution is for the server to half-close the connection by
2064 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2065 * and then wait for the client to notice this and close its side of the
2066 * connection, after which the server can safely call g_socket_close().
2067 * (This is what #GTcpConnection does if you call
2068 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2069 * only works if the client will close its connection after the server
2072 * Returns: %TRUE on success, %FALSE on error
2077 g_socket_close (GSocket *socket,
2082 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2084 if (socket->priv->closed)
2085 return TRUE; /* Multiple close not an error */
2087 if (!check_socket (socket, NULL))
2093 res = closesocket (socket->priv->fd);
2095 res = close (socket->priv->fd);
2099 int errsv = get_socket_errno ();
2104 g_set_error (error, G_IO_ERROR,
2105 socket_io_error_from_errno (errsv),
2106 _("Error closing socket: %s"),
2107 socket_strerror (errsv));
2113 socket->priv->connected = FALSE;
2114 socket->priv->closed = TRUE;
2120 * g_socket_is_closed:
2121 * @socket: a #GSocket
2123 * Checks whether a socket is closed.
2125 * Returns: %TRUE if socket is closed, %FALSE otherwise
2130 g_socket_is_closed (GSocket *socket)
2132 return socket->priv->closed;
2136 /* Broken source, used on errors */
2138 broken_prepare (GSource *source,
2145 broken_check (GSource *source)
2151 broken_dispatch (GSource *source,
2152 GSourceFunc callback,
2158 static GSourceFuncs broken_funcs =
2167 network_events_for_condition (GIOCondition condition)
2171 if (condition & G_IO_IN)
2172 event_mask |= (FD_READ | FD_ACCEPT);
2173 if (condition & G_IO_OUT)
2174 event_mask |= (FD_WRITE | FD_CONNECT);
2175 event_mask |= FD_CLOSE;
2181 ensure_event (GSocket *socket)
2183 if (socket->priv->event == WSA_INVALID_EVENT)
2184 socket->priv->event = WSACreateEvent();
2188 update_select_events (GSocket *socket)
2195 ensure_event (socket);
2198 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2201 event_mask |= network_events_for_condition (*ptr);
2204 if (event_mask != socket->priv->selected_events)
2206 /* If no events selected, disable event so we can unset
2209 if (event_mask == 0)
2212 event = socket->priv->event;
2214 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2215 socket->priv->selected_events = event_mask;
2220 add_condition_watch (GSocket *socket,
2221 GIOCondition *condition)
2223 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2225 socket->priv->requested_conditions =
2226 g_list_prepend (socket->priv->requested_conditions, condition);
2228 update_select_events (socket);
2232 remove_condition_watch (GSocket *socket,
2233 GIOCondition *condition)
2235 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2237 socket->priv->requested_conditions =
2238 g_list_remove (socket->priv->requested_conditions, condition);
2240 update_select_events (socket);
2244 update_condition (GSocket *socket)
2246 WSANETWORKEVENTS events;
2247 GIOCondition condition;
2249 if (WSAEnumNetworkEvents (socket->priv->fd,
2250 socket->priv->event,
2253 socket->priv->current_events |= events.lNetworkEvents;
2254 if (events.lNetworkEvents & FD_WRITE &&
2255 events.iErrorCode[FD_WRITE_BIT] != 0)
2256 socket->priv->current_errors |= FD_WRITE;
2257 if (events.lNetworkEvents & FD_CONNECT &&
2258 events.iErrorCode[FD_CONNECT_BIT] != 0)
2259 socket->priv->current_errors |= FD_CONNECT;
2263 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2264 condition |= G_IO_IN;
2266 if (socket->priv->current_events & FD_CLOSE ||
2267 socket->priv->closed)
2268 condition |= G_IO_HUP;
2270 /* Never report both G_IO_OUT and HUP, these are
2271 mutually exclusive (can't write to a closed socket) */
2272 if ((condition & G_IO_HUP) == 0 &&
2273 socket->priv->current_events & FD_WRITE)
2275 if (socket->priv->current_errors & FD_WRITE)
2276 condition |= G_IO_ERR;
2278 condition |= G_IO_OUT;
2282 if (socket->priv->current_events & FD_CONNECT)
2284 if (socket->priv->current_errors & FD_CONNECT)
2285 condition |= (G_IO_HUP | G_IO_ERR);
2287 condition |= G_IO_OUT;
2299 GIOCondition condition;
2300 GCancellable *cancellable;
2301 GPollFD cancel_pollfd;
2302 GTimeVal timeout_time;
2306 socket_source_prepare (GSource *source,
2309 GSocketSource *socket_source = (GSocketSource *)source;
2311 if (g_cancellable_is_cancelled (socket_source->cancellable))
2314 if (socket_source->timeout_time.tv_sec)
2318 g_source_get_current_time (source, &now);
2319 *timeout = ((socket_source->timeout_time.tv_sec - now.tv_sec) * 1000 +
2320 (socket_source->timeout_time.tv_usec - now.tv_usec) / 1000);
2323 socket_source->socket->priv->timed_out = TRUE;
2324 socket_source->pollfd.revents = socket_source->condition & (G_IO_IN | G_IO_OUT);
2332 socket_source->pollfd.revents = update_condition (socket_source->socket);
2335 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2342 socket_source_check (GSource *source)
2346 return socket_source_prepare (source, &timeout);
2350 socket_source_dispatch (GSource *source,
2351 GSourceFunc callback,
2354 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2355 GSocketSource *socket_source = (GSocketSource *)source;
2357 return (*func) (socket_source->socket,
2358 socket_source->pollfd.revents & socket_source->condition,
2363 socket_source_finalize (GSource *source)
2365 GSocketSource *socket_source = (GSocketSource *)source;
2368 socket = socket_source->socket;
2371 remove_condition_watch (socket, &socket_source->condition);
2374 g_object_unref (socket);
2376 if (socket_source->cancellable)
2378 g_cancellable_release_fd (socket_source->cancellable);
2379 g_object_unref (socket_source->cancellable);
2383 static GSourceFuncs socket_source_funcs =
2385 socket_source_prepare,
2386 socket_source_check,
2387 socket_source_dispatch,
2388 socket_source_finalize
2392 socket_source_new (GSocket *socket,
2393 GIOCondition condition,
2394 GCancellable *cancellable)
2397 GSocketSource *socket_source;
2400 ensure_event (socket);
2402 if (socket->priv->event == WSA_INVALID_EVENT)
2404 g_warning ("Failed to create WSAEvent");
2405 return g_source_new (&broken_funcs, sizeof (GSource));
2409 condition |= G_IO_HUP | G_IO_ERR;
2411 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2412 socket_source = (GSocketSource *)source;
2414 socket_source->socket = g_object_ref (socket);
2415 socket_source->condition = condition;
2417 if (g_cancellable_make_pollfd (cancellable,
2418 &socket_source->cancel_pollfd))
2420 socket_source->cancellable = g_object_ref (cancellable);
2421 g_source_add_poll (source, &socket_source->cancel_pollfd);
2425 add_condition_watch (socket, &socket_source->condition);
2426 socket_source->pollfd.fd = (gintptr) socket->priv->event;
2428 socket_source->pollfd.fd = socket->priv->fd;
2431 socket_source->pollfd.events = condition;
2432 socket_source->pollfd.revents = 0;
2433 g_source_add_poll (source, &socket_source->pollfd);
2435 if (socket->priv->timeout)
2437 g_get_current_time (&socket_source->timeout_time);
2438 socket_source->timeout_time.tv_sec += socket->priv->timeout;
2442 socket_source->timeout_time.tv_sec = 0;
2443 socket_source->timeout_time.tv_usec = 0;
2450 * g_socket_create_source:
2451 * @socket: a #GSocket
2452 * @condition: a #GIOCondition mask to monitor
2453 * @cancellable: a %GCancellable or %NULL
2455 * Creates a %GSource that can be attached to a %GMainContext to monitor
2456 * for the availibility of the specified @condition on the socket.
2458 * The callback on the source is of the #GSocketSourceFunc type.
2460 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2461 * these conditions will always be reported output if they are true.
2463 * @cancellable if not %NULL can be used to cancel the source, which will
2464 * cause the source to trigger, reporting the current condition (which
2465 * is likely 0 unless cancellation happened at the same time as a
2466 * condition change). You can check for this in the callback using
2467 * g_cancellable_is_cancelled().
2469 * If @socket has a timeout set, and it is reached before @condition
2470 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2471 * %G_IO_OUT depending on @condition. However, @socket will have been
2472 * marked as having had a timeout, and so the next #GSocket I/O method
2473 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2475 * Returns: a newly allocated %GSource, free with g_source_unref().
2480 g_socket_create_source (GSocket *socket,
2481 GIOCondition condition,
2482 GCancellable *cancellable)
2484 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2486 return socket_source_new (socket, condition, cancellable);
2490 * g_socket_condition_check:
2491 * @socket: a #GSocket
2492 * @condition: a #GIOCondition mask to check
2494 * Checks on the readiness of @socket to perform operations.
2495 * The operations specified in @condition are checked for and masked
2496 * against the currently-satisfied conditions on @socket. The result
2499 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2500 * these conditions will always be set in the output if they are true.
2502 * This call never blocks.
2504 * Returns: the @GIOCondition mask of the current state
2509 g_socket_condition_check (GSocket *socket,
2510 GIOCondition condition)
2512 if (!check_socket (socket, NULL))
2517 GIOCondition current_condition;
2519 condition |= G_IO_ERR | G_IO_HUP;
2521 add_condition_watch (socket, &condition);
2522 current_condition = update_condition (socket);
2523 remove_condition_watch (socket, &condition);
2524 return condition & current_condition;
2530 poll_fd.fd = socket->priv->fd;
2531 poll_fd.events = condition;
2534 result = g_poll (&poll_fd, 1, 0);
2535 while (result == -1 && get_socket_errno () == EINTR);
2537 return poll_fd.revents;
2543 * g_socket_condition_wait:
2544 * @socket: a #GSocket
2545 * @condition: a #GIOCondition mask to wait for
2546 * @cancellable: a #GCancellable, or %NULL
2547 * @error: a #GError pointer, or %NULL
2549 * Waits for @condition to become true on @socket. When the condition
2550 * is met, %TRUE is returned.
2552 * If @cancellable is cancelled before the condition is met, or if the
2553 * socket has a timeout set and it is reached before the condition is
2554 * met, then %FALSE is returned and @error, if non-%NULL, is set to
2555 * the appropriate value (%G_IO_ERROR_CANCELLED or
2556 * %G_IO_ERROR_TIMED_OUT).
2558 * Returns: %TRUE if the condition was met, %FALSE otherwise
2563 g_socket_condition_wait (GSocket *socket,
2564 GIOCondition condition,
2565 GCancellable *cancellable,
2568 if (!check_socket (socket, error))
2571 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2576 GIOCondition current_condition;
2582 /* Always check these */
2583 condition |= G_IO_ERR | G_IO_HUP;
2585 add_condition_watch (socket, &condition);
2588 events[num_events++] = socket->priv->event;
2590 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2591 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2593 if (socket->priv->timeout)
2594 timeout = socket->priv->timeout * 1000;
2596 timeout = WSA_INFINITE;
2598 current_condition = update_condition (socket);
2599 while ((condition & current_condition) == 0)
2601 res = WSAWaitForMultipleEvents(num_events, events,
2602 FALSE, timeout, FALSE);
2603 if (res == WSA_WAIT_FAILED)
2605 int errsv = get_socket_errno ();
2607 g_set_error (error, G_IO_ERROR,
2608 socket_io_error_from_errno (errsv),
2609 _("Waiting for socket condition: %s"),
2610 socket_strerror (errsv));
2613 else if (res == WSA_WAIT_TIMEOUT)
2615 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2616 _("Socket I/O timed out"));
2620 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2623 current_condition = update_condition (socket);
2625 remove_condition_watch (socket, &condition);
2627 g_cancellable_release_fd (cancellable);
2629 return (condition & current_condition) != 0;
2638 poll_fd[0].fd = socket->priv->fd;
2639 poll_fd[0].events = condition;
2642 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2645 if (socket->priv->timeout)
2646 timeout = socket->priv->timeout * 1000;
2651 result = g_poll (poll_fd, num, timeout);
2652 while (result == -1 && get_socket_errno () == EINTR);
2655 g_cancellable_release_fd (cancellable);
2659 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2660 _("Socket I/O timed out"));
2664 return !g_cancellable_set_error_if_cancelled (cancellable, error);
2670 * g_socket_send_message:
2671 * @socket: a #GSocket
2672 * @address: a #GSocketAddress, or %NULL
2673 * @vectors: an array of #GOutputVector structs
2674 * @num_vectors: the number of elements in @vectors, or -1
2675 * @messages: a pointer to an array of #GSocketControlMessages, or
2677 * @num_messages: number of elements in @messages, or -1.
2678 * @flags: an int containing #GSocketMsgFlags flags
2679 * @cancellable: a %GCancellable or %NULL
2680 * @error: #GError for error reporting, or %NULL to ignore.
2682 * Send data to @address on @socket. This is the most complicated and
2683 * fully-featured version of this call. For easier use, see
2684 * g_socket_send() and g_socket_send_to().
2686 * If @address is %NULL then the message is sent to the default receiver
2687 * (set by g_socket_connect()).
2689 * @vectors must point to an array of #GOutputVector structs and
2690 * @num_vectors must be the length of this array. (If @num_vectors is -1,
2691 * then @vectors is assumed to be terminated by a #GOutputVector with a
2692 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2693 * that the sent data will be gathered from. Using multiple
2694 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2695 * data from multiple sources into a single buffer, and more
2696 * network-efficient than making multiple calls to g_socket_send().
2698 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2699 * #GSocketControlMessage instances. These correspond to the control
2700 * messages to be sent on the socket.
2701 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2704 * @flags modify how the message is sent. The commonly available arguments
2705 * for this are available in the #GSocketMsgFlags enum, but the
2706 * values there are the same as the system values, and the flags
2707 * are passed in as-is, so you can pass in system-specific flags too.
2709 * If the socket is in blocking mode the call will block until there is
2710 * space for the data in the socket queue. If there is no space available
2711 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2712 * will be returned. To be notified when space is available, wait for the
2713 * %G_IO_OUT condition. Note though that you may still receive
2714 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2715 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2716 * very common due to the way the underlying APIs work.)
2718 * On error -1 is returned and @error is set accordingly.
2720 * Returns: Number of bytes written (which may be less than @size), or -1
2726 g_socket_send_message (GSocket *socket,
2727 GSocketAddress *address,
2728 GOutputVector *vectors,
2730 GSocketControlMessage **messages,
2733 GCancellable *cancellable,
2736 GOutputVector one_vector;
2739 if (!check_socket (socket, error))
2742 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2745 if (num_vectors == -1)
2747 for (num_vectors = 0;
2748 vectors[num_vectors].buffer != NULL;
2753 if (num_messages == -1)
2755 for (num_messages = 0;
2756 messages != NULL && messages[num_messages] != NULL;
2761 if (num_vectors == 0)
2765 one_vector.buffer = &zero;
2766 one_vector.size = 1;
2768 vectors = &one_vector;
2779 msg.msg_namelen = g_socket_address_get_native_size (address);
2780 msg.msg_name = g_alloca (msg.msg_namelen);
2781 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2786 msg.msg_name = NULL;
2787 msg.msg_namelen = 0;
2792 /* this entire expression will be evaluated at compile time */
2793 if (sizeof *msg.msg_iov == sizeof *vectors &&
2794 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2795 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2796 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2797 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2798 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2799 G_STRUCT_OFFSET (GOutputVector, size))
2800 /* ABI is compatible */
2802 msg.msg_iov = (struct iovec *) vectors;
2803 msg.msg_iovlen = num_vectors;
2806 /* ABI is incompatible */
2810 msg.msg_iov = g_newa (struct iovec, num_vectors);
2811 for (i = 0; i < num_vectors; i++)
2813 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2814 msg.msg_iov[i].iov_len = vectors[i].size;
2816 msg.msg_iovlen = num_vectors;
2822 struct cmsghdr *cmsg;
2825 msg.msg_controllen = 0;
2826 for (i = 0; i < num_messages; i++)
2827 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2829 msg.msg_control = g_alloca (msg.msg_controllen);
2831 cmsg = CMSG_FIRSTHDR (&msg);
2832 for (i = 0; i < num_messages; i++)
2834 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2835 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2836 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2837 g_socket_control_message_serialize (messages[i],
2839 cmsg = CMSG_NXTHDR (&msg, cmsg);
2841 g_assert (cmsg == NULL);
2846 if (socket->priv->blocking &&
2847 !g_socket_condition_wait (socket,
2848 G_IO_OUT, cancellable, error))
2851 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
2854 int errsv = get_socket_errno ();
2859 if (socket->priv->blocking &&
2860 (errsv == EWOULDBLOCK ||
2864 g_set_error (error, G_IO_ERROR,
2865 socket_io_error_from_errno (errsv),
2866 _("Error sending message: %s"), socket_strerror (errsv));
2877 struct sockaddr_storage addr;
2884 /* Win32 doesn't support control messages.
2885 Actually this is possible for raw and datagram sockets
2886 via WSASendMessage on Vista or later, but that doesn't
2888 if (num_messages != 0)
2890 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2891 _("GSocketControlMessage not supported on windows"));
2896 bufs = g_newa (WSABUF, num_vectors);
2897 for (i = 0; i < num_vectors; i++)
2899 bufs[i].buf = (char *)vectors[i].buffer;
2900 bufs[i].len = (gulong)vectors[i].size;
2904 addrlen = 0; /* Avoid warning */
2907 addrlen = g_socket_address_get_native_size (address);
2908 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2914 if (socket->priv->blocking &&
2915 !g_socket_condition_wait (socket,
2916 G_IO_OUT, cancellable, error))
2920 result = WSASendTo (socket->priv->fd,
2923 (const struct sockaddr *)&addr, addrlen,
2926 result = WSASend (socket->priv->fd,
2933 int errsv = get_socket_errno ();
2935 if (errsv == WSAEINTR)
2938 if (errsv == WSAEWOULDBLOCK)
2939 win32_unset_event_mask (socket, FD_WRITE);
2941 if (socket->priv->blocking &&
2942 errsv == WSAEWOULDBLOCK)
2945 g_set_error (error, G_IO_ERROR,
2946 socket_io_error_from_errno (errsv),
2947 _("Error sending message: %s"), socket_strerror (errsv));
2960 * g_socket_receive_message:
2961 * @socket: a #GSocket
2962 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2963 * @vectors: an array of #GInputVector structs
2964 * @num_vectors: the number of elements in @vectors, or -1
2965 * @messages: a pointer which may be filled with an array of
2966 * #GSocketControlMessages, or %NULL
2967 * @num_messages: a pointer which will be filled with the number of
2968 * elements in @messages, or %NULL
2969 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2970 * @cancellable: a %GCancellable or %NULL
2971 * @error: a #GError pointer, or %NULL
2973 * Receive data from a socket. This is the most complicated and
2974 * fully-featured version of this call. For easier use, see
2975 * g_socket_receive() and g_socket_receive_from().
2977 * If @address is non-%NULL then @address will be set equal to the
2978 * source address of the received packet.
2979 * @address is owned by the caller.
2981 * @vector must point to an array of #GInputVector structs and
2982 * @num_vectors must be the length of this array. These structs
2983 * describe the buffers that received data will be scattered into.
2984 * If @num_vectors is -1, then @vectors is assumed to be terminated
2985 * by a #GInputVector with a %NULL buffer pointer.
2987 * As a special case, if @num_vectors is 0 (in which case, @vectors
2988 * may of course be %NULL), then a single byte is received and
2989 * discarded. This is to facilitate the common practice of sending a
2990 * single '\0' byte for the purposes of transferring ancillary data.
2992 * @messages, if non-%NULL, will be set to point to a newly-allocated
2993 * array of #GSocketControlMessage instances or %NULL if no such
2994 * messages was received. These correspond to the control messages
2995 * received from the kernel, one #GSocketControlMessage per message
2996 * from the kernel. This array is %NULL-terminated and must be freed
2997 * by the caller using g_free() after calling g_object_unref() on each
2998 * element. If @messages is %NULL, any control messages received will
3001 * @num_messages, if non-%NULL, will be set to the number of control
3002 * messages received.
3004 * If both @messages and @num_messages are non-%NULL, then
3005 * @num_messages gives the number of #GSocketControlMessage instances
3006 * in @messages (ie: not including the %NULL terminator).
3008 * @flags is an in/out parameter. The commonly available arguments
3009 * for this are available in the #GSocketMsgFlags enum, but the
3010 * values there are the same as the system values, and the flags
3011 * are passed in as-is, so you can pass in system-specific flags too
3012 * (and g_socket_receive_message() may pass system-specific flags out).
3014 * As with g_socket_receive(), data may be discarded if @socket is
3015 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3016 * provide enough buffer space to read a complete message. You can pass
3017 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3018 * removing it from the receive queue, but there is no portable way to find
3019 * out the length of the message other than by reading it into a
3020 * sufficiently-large buffer.
3022 * If the socket is in blocking mode the call will block until there
3023 * is some data to receive or there is an error. If there is no data
3024 * available and the socket is in non-blocking mode, a
3025 * %G_IO_ERROR_WOULD_BLOCK error will be returned. To be notified when
3026 * data is available, wait for the %G_IO_IN condition.
3028 * On error -1 is returned and @error is set accordingly.
3030 * Returns: Number of bytes read, or -1 on error
3035 g_socket_receive_message (GSocket *socket,
3036 GSocketAddress **address,
3037 GInputVector *vectors,
3039 GSocketControlMessage ***messages,
3042 GCancellable *cancellable,
3045 GInputVector one_vector;
3048 if (!check_socket (socket, error))
3051 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3054 if (num_vectors == -1)
3056 for (num_vectors = 0;
3057 vectors[num_vectors].buffer != NULL;
3062 if (num_vectors == 0)
3064 one_vector.buffer = &one_byte;
3065 one_vector.size = 1;
3067 vectors = &one_vector;
3074 struct sockaddr_storage one_sockaddr;
3079 msg.msg_name = &one_sockaddr;
3080 msg.msg_namelen = sizeof (struct sockaddr_storage);
3084 msg.msg_name = NULL;
3085 msg.msg_namelen = 0;
3089 /* this entire expression will be evaluated at compile time */
3090 if (sizeof *msg.msg_iov == sizeof *vectors &&
3091 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3092 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3093 G_STRUCT_OFFSET (GInputVector, buffer) &&
3094 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3095 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3096 G_STRUCT_OFFSET (GInputVector, size))
3097 /* ABI is compatible */
3099 msg.msg_iov = (struct iovec *) vectors;
3100 msg.msg_iovlen = num_vectors;
3103 /* ABI is incompatible */
3107 msg.msg_iov = g_newa (struct iovec, num_vectors);
3108 for (i = 0; i < num_vectors; i++)
3110 msg.msg_iov[i].iov_base = vectors[i].buffer;
3111 msg.msg_iov[i].iov_len = vectors[i].size;
3113 msg.msg_iovlen = num_vectors;
3117 msg.msg_control = g_alloca (2048);
3118 msg.msg_controllen = 2048;
3122 msg.msg_flags = *flags;
3129 if (socket->priv->blocking &&
3130 !g_socket_condition_wait (socket,
3131 G_IO_IN, cancellable, error))
3134 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3138 int errsv = get_socket_errno ();
3143 if (socket->priv->blocking &&
3144 (errsv == EWOULDBLOCK ||
3148 g_set_error (error, G_IO_ERROR,
3149 socket_io_error_from_errno (errsv),
3150 _("Error receiving message: %s"), socket_strerror (errsv));
3157 /* decode address */
3158 if (address != NULL)
3160 if (msg.msg_namelen > 0)
3161 *address = g_socket_address_new_from_native (msg.msg_name,
3167 /* decode control messages */
3169 GPtrArray *my_messages = NULL;
3170 const gchar *scm_pointer;
3171 struct cmsghdr *cmsg;
3174 scm_pointer = (const gchar *) msg.msg_control;
3175 scm_size = msg.msg_controllen;
3177 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3179 GSocketControlMessage *message;
3181 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3183 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3185 if (message == NULL)
3186 /* We've already spewed about the problem in the
3187 deserialization code, so just continue */
3190 if (messages == NULL)
3192 /* we have to do it this way if the user ignores the
3193 * messages so that we will close any received fds.
3195 g_object_unref (message);
3199 if (my_messages == NULL)
3200 my_messages = g_ptr_array_new ();
3201 g_ptr_array_add (my_messages, message);
3206 *num_messages = my_messages != NULL ? my_messages->len : 0;
3210 if (my_messages == NULL)
3216 g_ptr_array_add (my_messages, NULL);
3217 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3222 g_assert (my_messages == NULL);
3226 /* capture the flags */
3228 *flags = msg.msg_flags;
3234 struct sockaddr_storage addr;
3236 DWORD bytes_received;
3243 bufs = g_newa (WSABUF, num_vectors);
3244 for (i = 0; i < num_vectors; i++)
3246 bufs[i].buf = (char *)vectors[i].buffer;
3247 bufs[i].len = (gulong)vectors[i].size;
3259 if (socket->priv->blocking &&
3260 !g_socket_condition_wait (socket,
3261 G_IO_IN, cancellable, error))
3264 addrlen = sizeof addr;
3266 result = WSARecvFrom (socket->priv->fd,
3268 &bytes_received, &win_flags,
3269 (struct sockaddr *)&addr, &addrlen,
3272 result = WSARecv (socket->priv->fd,
3274 &bytes_received, &win_flags,
3278 int errsv = get_socket_errno ();
3280 if (errsv == WSAEINTR)
3283 win32_unset_event_mask (socket, FD_READ);
3285 if (socket->priv->blocking &&
3286 errsv == WSAEWOULDBLOCK)
3289 g_set_error (error, G_IO_ERROR,
3290 socket_io_error_from_errno (errsv),
3291 _("Error receiving message: %s"), socket_strerror (errsv));
3295 win32_unset_event_mask (socket, FD_READ);
3299 /* decode address */
3300 if (address != NULL)
3303 *address = g_socket_address_new_from_native (&addr, addrlen);
3308 /* capture the flags */
3312 if (messages != NULL)
3314 if (n_messages != NULL)
3317 return bytes_received;
3322 #define __G_SOCKET_C__
3323 #include "gioaliasdef.c"