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"
61 * @short_description: Low-level socket object
63 * @see_also: #GInitable
65 * A #GSocket is a low-level networking primitive. It is a more or less
66 * direct mapping of the BSD socket API in a portable GObject based API.
67 * It supports both the UNIX socket implementations and winsock2 on Windows.
69 * #GSocket is the platform independent base upon which the higher level
70 * network primitives are based. Applications are not typically meant to
71 * use it directly, but rather through classes like #GSocketClient,
72 * #GSocketService and #GSocketConnection. However there may be cases where
73 * direct use of #GSocket is useful.
75 * #GSocket implements the #GInitable interface, so if it is manually constructed
76 * by e.g. g_object_new() you must call g_initable_init() and check the
77 * results before using the object. This is done automatically in
78 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
81 * Sockets operate in two general modes, blocking or non-blocking. When
82 * in blocking mode all operations block until the requested operation
83 * is finished or there is an error. In non-blocking mode all calls that
84 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
85 * To know when a call would successfully run you can call g_socket_condition_check(),
86 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
87 * attach it to a #GMainContext to get callbacks when I/O is possible.
88 * Note that all sockets are always set to non blocking mode in the system, and
89 * blocking mode is emulated in GSocket.
91 * When working in non-blocking mode applications should always be able to
92 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
93 * function said that I/O was possible. This can easily happen in case
94 * of a race condition in the application, but it can also happen for other
95 * reasons. For instance, on Windows a socket is always seen as writable
96 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
98 * #GSocket<!-- -->s can be either connection oriented or datagram based.
99 * For connection oriented types you must first establish a connection by
100 * either connecting to an address or accepting a connection from another
101 * address. For connectionless socket types the target/source address is
102 * specified or received in each I/O operation.
104 * All socket file descriptors are set to be close-on-exec.
106 * Note that creating a #GSocket causes the signal %SIGPIPE to be
107 * ignored for the remainder of the program. If you are writing a
108 * command-line utility that uses #GSocket, you may need to take into
109 * account the fact that your program will not automatically be killed
110 * if it tries to write to %stdout after it has been closed.
115 static void g_socket_initable_iface_init (GInitableIface *iface);
116 static gboolean g_socket_initable_init (GInitable *initable,
117 GCancellable *cancellable,
120 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
121 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
122 g_socket_initable_iface_init));
139 struct _GSocketPrivate
141 GSocketFamily family;
143 GSocketProtocol protocol;
147 GError *construct_error;
160 GList *requested_conditions; /* list of requested GIOCondition * */
165 get_socket_errno (void)
170 return WSAGetLastError ();
175 socket_io_error_from_errno (int err)
178 return g_io_error_from_errno (err);
183 return G_IO_ERROR_ADDRESS_IN_USE;
185 return G_IO_ERROR_WOULD_BLOCK;
187 return G_IO_ERROR_PERMISSION_DENIED;
188 case WSA_INVALID_HANDLE:
189 case WSA_INVALID_PARAMETER:
192 return G_IO_ERROR_INVALID_ARGUMENT;
193 case WSAEPROTONOSUPPORT:
194 return G_IO_ERROR_NOT_SUPPORTED;
196 return G_IO_ERROR_CANCELLED;
197 case WSAESOCKTNOSUPPORT:
199 case WSAEPFNOSUPPORT:
200 case WSAEAFNOSUPPORT:
201 return G_IO_ERROR_NOT_SUPPORTED;
203 return G_IO_ERROR_FAILED;
209 socket_strerror (int err)
212 return g_strerror (err);
214 static GStaticPrivate last_msg = G_STATIC_PRIVATE_INIT;
217 msg = g_win32_error_message (err);
218 g_static_private_set (&last_msg, msg, g_free);
225 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
227 _win32_unset_event_mask (GSocket *socket, int mask)
229 socket->priv->current_events &= ~mask;
230 socket->priv->current_errors &= ~mask;
233 #define win32_unset_event_mask(_socket, _mask)
237 set_fd_nonblocking (int fd)
246 if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
248 g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
252 arg = arg | O_NONBLOCK;
254 if (fcntl (fd, F_SETFL, arg) < 0)
255 g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
259 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
261 int errsv = get_socket_errno ();
262 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
268 check_socket (GSocket *socket,
271 if (!socket->priv->inited)
273 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
274 _("Invalid socket, not initialized"));
278 if (socket->priv->construct_error)
280 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
281 _("Invalid socket, initialization failed due to: %s"),
282 socket->priv->construct_error->message);
286 if (socket->priv->closed)
288 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
289 _("Socket is already closed"));
293 if (socket->priv->timed_out)
295 socket->priv->timed_out = FALSE;
296 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
297 _("Socket I/O timed out"));
305 g_socket_details_from_fd (GSocket *socket)
307 struct sockaddr_storage address;
314 /* See bug #611756 */
315 BOOL bool_val = FALSE;
320 fd = socket->priv->fd;
321 optlen = sizeof value;
322 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
324 errsv = get_socket_errno ();
335 /* programmer error */
336 g_error ("creating GSocket from fd %d: %s\n",
337 fd, socket_strerror (errsv));
345 g_assert (optlen == sizeof value);
349 socket->priv->type = G_SOCKET_TYPE_STREAM;
353 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
357 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
361 socket->priv->type = G_SOCKET_TYPE_INVALID;
365 addrlen = sizeof address;
366 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
368 errsv = get_socket_errno ();
372 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
373 sizeof address.ss_family <= addrlen);
374 switch (address.ss_family)
376 case G_SOCKET_FAMILY_IPV4:
377 case G_SOCKET_FAMILY_IPV6:
378 case G_SOCKET_FAMILY_UNIX:
379 socket->priv->family = address.ss_family;
383 socket->priv->family = G_SOCKET_FAMILY_INVALID;
387 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
389 addrlen = sizeof address;
390 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
391 socket->priv->connected = TRUE;
394 optlen = sizeof bool_val;
395 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
396 (void *)&bool_val, &optlen) == 0)
399 /* Experimentation indicates that the SO_KEEPALIVE value is
400 * actually a char on Windows, even if documentation claims it
401 * to be a BOOL which is a typedef for int. So this g_assert()
402 * fails. See bug #611756.
404 g_assert (optlen == sizeof bool_val);
406 socket->priv->keepalive = !!bool_val;
410 /* Can't read, maybe not supported, assume FALSE */
411 socket->priv->keepalive = FALSE;
417 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
418 socket_io_error_from_errno (errsv),
419 _("creating GSocket from fd: %s"),
420 socket_strerror (errsv));
424 g_socket_create_socket (GSocketFamily family,
434 case G_SOCKET_TYPE_STREAM:
435 native_type = SOCK_STREAM;
438 case G_SOCKET_TYPE_DATAGRAM:
439 native_type = SOCK_DGRAM;
442 case G_SOCKET_TYPE_SEQPACKET:
443 native_type = SOCK_SEQPACKET;
447 g_assert_not_reached ();
452 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
453 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
458 native_type |= SOCK_CLOEXEC;
460 fd = socket (family, native_type, protocol);
464 int errsv = get_socket_errno ();
466 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
467 _("Unable to create socket: %s"), socket_strerror (errsv));
474 /* We always want to set close-on-exec to protect users. If you
475 need to so some weird inheritance to exec you can re-enable this
476 using lower level hacks with g_socket_get_fd(). */
477 flags = fcntl (fd, F_GETFD, 0);
479 (flags & FD_CLOEXEC) == 0)
482 fcntl (fd, F_SETFD, flags);
491 g_socket_constructed (GObject *object)
493 GSocket *socket = G_SOCKET (object);
495 if (socket->priv->fd >= 0)
496 /* create socket->priv info from the fd */
497 g_socket_details_from_fd (socket);
500 /* create the fd from socket->priv info */
501 socket->priv->fd = g_socket_create_socket (socket->priv->family,
503 socket->priv->protocol,
504 &socket->priv->construct_error);
506 /* Always use native nonblocking sockets, as
507 windows sets sockets to nonblocking automatically
508 in certain operations. This way we make things work
509 the same on all platforms */
510 if (socket->priv->fd != -1)
511 set_fd_nonblocking (socket->priv->fd);
515 g_socket_get_property (GObject *object,
520 GSocket *socket = G_SOCKET (object);
521 GSocketAddress *address;
526 g_value_set_enum (value, socket->priv->family);
530 g_value_set_enum (value, socket->priv->type);
534 g_value_set_enum (value, socket->priv->protocol);
538 g_value_set_int (value, socket->priv->fd);
542 g_value_set_boolean (value, socket->priv->blocking);
545 case PROP_LISTEN_BACKLOG:
546 g_value_set_int (value, socket->priv->listen_backlog);
550 g_value_set_boolean (value, socket->priv->keepalive);
553 case PROP_LOCAL_ADDRESS:
554 address = g_socket_get_local_address (socket, NULL);
555 g_value_take_object (value, address);
558 case PROP_REMOTE_ADDRESS:
559 address = g_socket_get_remote_address (socket, NULL);
560 g_value_take_object (value, address);
564 g_value_set_uint (value, socket->priv->timeout);
568 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
573 g_socket_set_property (GObject *object,
578 GSocket *socket = G_SOCKET (object);
583 socket->priv->family = g_value_get_enum (value);
587 socket->priv->type = g_value_get_enum (value);
591 socket->priv->protocol = g_value_get_enum (value);
595 socket->priv->fd = g_value_get_int (value);
599 g_socket_set_blocking (socket, g_value_get_boolean (value));
602 case PROP_LISTEN_BACKLOG:
603 g_socket_set_listen_backlog (socket, g_value_get_int (value));
607 g_socket_set_keepalive (socket, g_value_get_boolean (value));
611 g_socket_set_timeout (socket, g_value_get_uint (value));
615 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
620 g_socket_finalize (GObject *object)
622 GSocket *socket = G_SOCKET (object);
624 g_clear_error (&socket->priv->construct_error);
626 if (socket->priv->fd != -1 &&
627 !socket->priv->closed)
628 g_socket_close (socket, NULL);
631 if (socket->priv->event != WSA_INVALID_EVENT)
633 WSACloseEvent (socket->priv->event);
634 socket->priv->event = WSA_INVALID_EVENT;
637 g_assert (socket->priv->requested_conditions == NULL);
640 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
641 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
645 g_socket_class_init (GSocketClass *klass)
647 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
650 /* Make sure winsock has been initialized */
651 type = g_inet_address_get_type ();
654 /* There is no portable, thread-safe way to avoid having the process
655 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
656 * forced to simply ignore the signal process-wide.
658 signal (SIGPIPE, SIG_IGN);
661 g_type_class_add_private (klass, sizeof (GSocketPrivate));
663 gobject_class->finalize = g_socket_finalize;
664 gobject_class->constructed = g_socket_constructed;
665 gobject_class->set_property = g_socket_set_property;
666 gobject_class->get_property = g_socket_get_property;
668 g_object_class_install_property (gobject_class, PROP_FAMILY,
669 g_param_spec_enum ("family",
671 P_("The sockets address family"),
672 G_TYPE_SOCKET_FAMILY,
673 G_SOCKET_FAMILY_INVALID,
674 G_PARAM_CONSTRUCT_ONLY |
676 G_PARAM_STATIC_STRINGS));
678 g_object_class_install_property (gobject_class, PROP_TYPE,
679 g_param_spec_enum ("type",
681 P_("The sockets type"),
683 G_SOCKET_TYPE_STREAM,
684 G_PARAM_CONSTRUCT_ONLY |
686 G_PARAM_STATIC_STRINGS));
688 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
689 g_param_spec_enum ("protocol",
690 P_("Socket protocol"),
691 P_("The id of the protocol to use, or -1 for unknown"),
692 G_TYPE_SOCKET_PROTOCOL,
693 G_SOCKET_PROTOCOL_UNKNOWN,
694 G_PARAM_CONSTRUCT_ONLY |
696 G_PARAM_STATIC_STRINGS));
698 g_object_class_install_property (gobject_class, PROP_FD,
699 g_param_spec_int ("fd",
700 P_("File descriptor"),
701 P_("The sockets file descriptor"),
705 G_PARAM_CONSTRUCT_ONLY |
707 G_PARAM_STATIC_STRINGS));
709 g_object_class_install_property (gobject_class, PROP_BLOCKING,
710 g_param_spec_boolean ("blocking",
712 P_("Whether or not I/O on this socket is blocking"),
715 G_PARAM_STATIC_STRINGS));
717 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
718 g_param_spec_int ("listen-backlog",
719 P_("Listen backlog"),
720 P_("Outstanding connections in the listen queue"),
725 G_PARAM_STATIC_STRINGS));
727 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
728 g_param_spec_boolean ("keepalive",
729 P_("Keep connection alive"),
730 P_("Keep connection alive by sending periodic pings"),
733 G_PARAM_STATIC_STRINGS));
735 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
736 g_param_spec_object ("local-address",
738 P_("The local address the socket is bound to"),
739 G_TYPE_SOCKET_ADDRESS,
741 G_PARAM_STATIC_STRINGS));
743 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
744 g_param_spec_object ("remote-address",
745 P_("Remote address"),
746 P_("The remote address the socket is connected to"),
747 G_TYPE_SOCKET_ADDRESS,
749 G_PARAM_STATIC_STRINGS));
754 * The timeout in seconds on socket I/O
758 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
759 g_param_spec_uint ("timeout",
761 P_("The timeout in seconds on socket I/O"),
766 G_PARAM_STATIC_STRINGS));
770 g_socket_initable_iface_init (GInitableIface *iface)
772 iface->init = g_socket_initable_init;
776 g_socket_init (GSocket *socket)
778 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
780 socket->priv->fd = -1;
781 socket->priv->blocking = TRUE;
782 socket->priv->listen_backlog = 10;
783 socket->priv->construct_error = NULL;
785 socket->priv->event = WSA_INVALID_EVENT;
790 g_socket_initable_init (GInitable *initable,
791 GCancellable *cancellable,
796 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
798 socket = G_SOCKET (initable);
800 if (cancellable != NULL)
802 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
803 _("Cancellable initialization not supported"));
807 socket->priv->inited = TRUE;
809 if (socket->priv->construct_error)
812 *error = g_error_copy (socket->priv->construct_error);
822 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
823 * @type: the socket type to use.
824 * @protocol: the id of the protocol to use, or 0 for default.
825 * @error: #GError for error reporting, or %NULL to ignore.
827 * Creates a new #GSocket with the defined family, type and protocol.
828 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
829 * for the family and type is used.
831 * The @protocol is a family and type specific int that specifies what
832 * kind of protocol to use. #GSocketProtocol lists several common ones.
833 * Many families only support one protocol, and use 0 for this, others
834 * support several and using 0 means to use the default protocol for
835 * the family and type.
837 * The protocol id is passed directly to the operating
838 * system, so you can use protocols not listed in #GSocketProtocol if you
839 * know the protocol number used for it.
841 * Returns: a #GSocket or %NULL on error.
842 * Free the returned object with g_object_unref().
847 g_socket_new (GSocketFamily family,
849 GSocketProtocol protocol,
852 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
856 "protocol", protocol,
861 * g_socket_new_from_fd:
862 * @fd: a native socket file descriptor.
863 * @error: #GError for error reporting, or %NULL to ignore.
865 * Creates a new #GSocket from a native file descriptor
866 * or winsock SOCKET handle.
868 * This reads all the settings from the file descriptor so that
869 * all properties should work. Note that the file descriptor
870 * will be set to non-blocking mode, independent on the blocking
871 * mode of the #GSocket.
873 * Returns: a #GSocket or %NULL on error.
874 * Free the returned object with g_object_unref().
879 g_socket_new_from_fd (gint fd,
882 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
889 * g_socket_set_blocking:
890 * @socket: a #GSocket.
891 * @blocking: Whether to use blocking I/O or not.
893 * Sets the blocking mode of the socket. In blocking mode
894 * all operations block until they succeed or there is an error. In
895 * non-blocking mode all functions return results immediately or
896 * with a %G_IO_ERROR_WOULD_BLOCK error.
898 * All sockets are created in blocking mode. However, note that the
899 * platform level socket is always non-blocking, and blocking mode
900 * is a GSocket level feature.
905 g_socket_set_blocking (GSocket *socket,
908 g_return_if_fail (G_IS_SOCKET (socket));
910 blocking = !!blocking;
912 if (socket->priv->blocking == blocking)
915 socket->priv->blocking = blocking;
916 g_object_notify (G_OBJECT (socket), "blocking");
920 * g_socket_get_blocking:
921 * @socket: a #GSocket.
923 * Gets the blocking mode of the socket. For details on blocking I/O,
924 * see g_socket_set_blocking().
926 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
931 g_socket_get_blocking (GSocket *socket)
933 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
935 return socket->priv->blocking;
939 * g_socket_set_keepalive:
940 * @socket: a #GSocket.
941 * @keepalive: Value for the keepalive flag
943 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
944 * this flag is set on a socket, the system will attempt to verify that the
945 * remote socket endpoint is still present if a sufficiently long period of
946 * time passes with no data being exchanged. If the system is unable to
947 * verify the presence of the remote endpoint, it will automatically close
950 * This option is only functional on certain kinds of sockets. (Notably,
951 * %G_SOCKET_PROTOCOL_TCP sockets.)
953 * The exact time between pings is system- and protocol-dependent, but will
954 * normally be at least two hours. Most commonly, you would set this flag
955 * on a server socket if you want to allow clients to remain idle for long
956 * periods of time, but also want to ensure that connections are eventually
957 * garbage-collected if clients crash or become unreachable.
962 g_socket_set_keepalive (GSocket *socket,
967 g_return_if_fail (G_IS_SOCKET (socket));
969 keepalive = !!keepalive;
970 if (socket->priv->keepalive == keepalive)
973 value = (gint) keepalive;
974 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
975 (gpointer) &value, sizeof (value)) < 0)
977 int errsv = get_socket_errno ();
978 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
982 socket->priv->keepalive = keepalive;
983 g_object_notify (G_OBJECT (socket), "keepalive");
987 * g_socket_get_keepalive:
988 * @socket: a #GSocket.
990 * Gets the keepalive mode of the socket. For details on this,
991 * see g_socket_set_keepalive().
993 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
998 g_socket_get_keepalive (GSocket *socket)
1000 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1002 return socket->priv->keepalive;
1006 * g_socket_get_listen_backlog:
1007 * @socket: a #GSocket.
1009 * Gets the listen backlog setting of the socket. For details on this,
1010 * see g_socket_set_listen_backlog().
1012 * Returns: the maximum number of pending connections.
1017 g_socket_get_listen_backlog (GSocket *socket)
1019 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1021 return socket->priv->listen_backlog;
1025 * g_socket_set_listen_backlog:
1026 * @socket: a #GSocket.
1027 * @backlog: the maximum number of pending connections.
1029 * Sets the maximum number of outstanding connections allowed
1030 * when listening on this socket. If more clients than this are
1031 * connecting to the socket and the application is not handling them
1032 * on time then the new connections will be refused.
1034 * Note that this must be called before g_socket_listen() and has no
1035 * effect if called after that.
1040 g_socket_set_listen_backlog (GSocket *socket,
1043 g_return_if_fail (G_IS_SOCKET (socket));
1044 g_return_if_fail (!socket->priv->listening);
1046 if (backlog != socket->priv->listen_backlog)
1048 socket->priv->listen_backlog = backlog;
1049 g_object_notify (G_OBJECT (socket), "listen-backlog");
1054 * g_socket_get_timeout:
1055 * @socket: a #GSocket.
1057 * Gets the timeout setting of the socket. For details on this, see
1058 * g_socket_set_timeout().
1060 * Returns: the timeout in seconds
1065 g_socket_get_timeout (GSocket *socket)
1067 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1069 return socket->priv->timeout;
1073 * g_socket_set_timeout:
1074 * @socket: a #GSocket.
1075 * @timeout: the timeout for @socket, in seconds, or 0 for none
1077 * Sets the time in seconds after which I/O operations on @socket will
1078 * time out if they have not yet completed.
1080 * On a blocking socket, this means that any blocking #GSocket
1081 * operation will time out after @timeout seconds of inactivity,
1082 * returning %G_IO_ERROR_TIMED_OUT.
1084 * On a non-blocking socket, calls to g_socket_condition_wait() will
1085 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1086 * created with g_socket_create_source() will trigger after
1087 * @timeout seconds of inactivity, with the requested condition
1088 * set, at which point calling g_socket_receive(), g_socket_send(),
1089 * g_socket_check_connect_result(), etc, will fail with
1090 * %G_IO_ERROR_TIMED_OUT.
1092 * If @timeout is 0 (the default), operations will never time out
1095 * Note that if an I/O operation is interrupted by a signal, this may
1096 * cause the timeout to be reset.
1101 g_socket_set_timeout (GSocket *socket,
1104 g_return_if_fail (G_IS_SOCKET (socket));
1106 if (timeout != socket->priv->timeout)
1108 socket->priv->timeout = timeout;
1109 g_object_notify (G_OBJECT (socket), "timeout");
1114 * g_socket_get_family:
1115 * @socket: a #GSocket.
1117 * Gets the socket family of the socket.
1119 * Returns: a #GSocketFamily
1124 g_socket_get_family (GSocket *socket)
1126 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1128 return socket->priv->family;
1132 * g_socket_get_socket_type:
1133 * @socket: a #GSocket.
1135 * Gets the socket type of the socket.
1137 * Returns: a #GSocketType
1142 g_socket_get_socket_type (GSocket *socket)
1144 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1146 return socket->priv->type;
1150 * g_socket_get_protocol:
1151 * @socket: a #GSocket.
1153 * Gets the socket protocol id the socket was created with.
1154 * In case the protocol is unknown, -1 is returned.
1156 * Returns: a protocol id, or -1 if unknown
1161 g_socket_get_protocol (GSocket *socket)
1163 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1165 return socket->priv->protocol;
1170 * @socket: a #GSocket.
1172 * Returns the underlying OS socket object. On unix this
1173 * is a socket file descriptor, and on windows this is
1174 * a Winsock2 SOCKET handle. This may be useful for
1175 * doing platform specific or otherwise unusual operations
1178 * Returns: the file descriptor of the socket.
1183 g_socket_get_fd (GSocket *socket)
1185 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1187 return socket->priv->fd;
1191 * g_socket_get_local_address:
1192 * @socket: a #GSocket.
1193 * @error: #GError for error reporting, or %NULL to ignore.
1195 * Try to get the local address of a bound socket. This is only
1196 * useful if the socket has been bound to a local address,
1197 * either explicitly or implicitly when connecting.
1199 * Returns: a #GSocketAddress or %NULL on error.
1200 * Free the returned object with g_object_unref().
1205 g_socket_get_local_address (GSocket *socket,
1208 struct sockaddr_storage buffer;
1209 guint32 len = sizeof (buffer);
1211 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1213 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1215 int errsv = get_socket_errno ();
1216 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1217 _("could not get local address: %s"), socket_strerror (errsv));
1221 return g_socket_address_new_from_native (&buffer, len);
1225 * g_socket_get_remote_address:
1226 * @socket: a #GSocket.
1227 * @error: #GError for error reporting, or %NULL to ignore.
1229 * Try to get the remove address of a connected socket. This is only
1230 * useful for connection oriented sockets that have been connected.
1232 * Returns: a #GSocketAddress or %NULL on error.
1233 * Free the returned object with g_object_unref().
1238 g_socket_get_remote_address (GSocket *socket,
1241 struct sockaddr_storage buffer;
1242 guint32 len = sizeof (buffer);
1244 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1246 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1248 int errsv = get_socket_errno ();
1249 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1250 _("could not get remote address: %s"), socket_strerror (errsv));
1254 return g_socket_address_new_from_native (&buffer, len);
1258 * g_socket_is_connected:
1259 * @socket: a #GSocket.
1261 * Check whether the socket is connected. This is only useful for
1262 * connection-oriented sockets.
1264 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1269 g_socket_is_connected (GSocket *socket)
1271 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1273 return socket->priv->connected;
1278 * @socket: a #GSocket.
1279 * @error: #GError for error reporting, or %NULL to ignore.
1281 * Marks the socket as a server socket, i.e. a socket that is used
1282 * to accept incoming requests using g_socket_accept().
1284 * Before calling this the socket must be bound to a local address using
1287 * To set the maximum amount of outstanding clients, use
1288 * g_socket_set_listen_backlog().
1290 * Returns: %TRUE on success, %FALSE on error.
1295 g_socket_listen (GSocket *socket,
1298 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1300 if (!check_socket (socket, error))
1303 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1305 int errsv = get_socket_errno ();
1307 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1308 _("could not listen: %s"), socket_strerror (errsv));
1312 socket->priv->listening = TRUE;
1319 * @socket: a #GSocket.
1320 * @address: a #GSocketAddress specifying the local address.
1321 * @allow_reuse: whether to allow reusing this address
1322 * @error: #GError for error reporting, or %NULL to ignore.
1324 * When a socket is created it is attached to an address family, but it
1325 * doesn't have an address in this family. g_socket_bind() assigns the
1326 * address (sometimes called name) of the socket.
1328 * It is generally required to bind to a local address before you can
1329 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1330 * In certain situations, you may also want to bind a socket that will be
1331 * used to initiate connections, though this is not normally required.
1333 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1334 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1335 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1336 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1337 * that address was previously used by another socket that has not yet been
1338 * fully cleaned-up by the kernel. Failing to set this flag on a server
1339 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1340 * the server program is stopped and then immediately restarted.)
1342 * Returns: %TRUE on success, %FALSE on error.
1347 g_socket_bind (GSocket *socket,
1348 GSocketAddress *address,
1349 gboolean reuse_address,
1352 struct sockaddr_storage addr;
1354 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1356 if (!check_socket (socket, error))
1359 /* SO_REUSEADDR on windows means something else and is not what we want.
1360 It always allows the unix variant of SO_REUSEADDR anyway */
1365 value = (int) !!reuse_address;
1366 /* Ignore errors here, the only likely error is "not supported", and
1367 this is a "best effort" thing mainly */
1368 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1369 (gpointer) &value, sizeof (value));
1373 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1376 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1377 g_socket_address_get_native_size (address)) < 0)
1379 int errsv = get_socket_errno ();
1381 G_IO_ERROR, socket_io_error_from_errno (errsv),
1382 _("Error binding to address: %s"), socket_strerror (errsv));
1390 * g_socket_speaks_ipv4:
1391 * @socket: a #GSocket
1393 * Checks if a socket is capable of speaking IPv4.
1395 * IPv4 sockets are capable of speaking IPv4. On some operating systems
1396 * and under some combinations of circumstances IPv6 sockets are also
1397 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
1400 * No other types of sockets are currently considered as being capable
1403 * Returns: %TRUE if this socket can be used with IPv4.
1408 g_socket_speaks_ipv4 (GSocket *socket)
1410 switch (socket->priv->family)
1412 case G_SOCKET_FAMILY_IPV4:
1415 case G_SOCKET_FAMILY_IPV6:
1416 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1418 guint sizeof_int = sizeof (int);
1421 if (getsockopt (socket->priv->fd,
1422 IPPROTO_IPV6, IPV6_V6ONLY,
1423 &v6_only, &sizeof_int) != 0)
1439 * @socket: a #GSocket.
1440 * @cancellable: a %GCancellable or %NULL
1441 * @error: #GError for error reporting, or %NULL to ignore.
1443 * Accept incoming connections on a connection-based socket. This removes
1444 * the first outstanding connection request from the listening socket and
1445 * creates a #GSocket object for it.
1447 * The @socket must be bound to a local address with g_socket_bind() and
1448 * must be listening for incoming connections (g_socket_listen()).
1450 * If there are no outstanding connections then the operation will block
1451 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1452 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1454 * Returns: a new #GSocket, or %NULL on error.
1455 * Free the returned object with g_object_unref().
1460 g_socket_accept (GSocket *socket,
1461 GCancellable *cancellable,
1464 GSocket *new_socket;
1467 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1469 if (!check_socket (socket, error))
1474 if (socket->priv->blocking &&
1475 !g_socket_condition_wait (socket,
1476 G_IO_IN, cancellable, error))
1479 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1481 int errsv = get_socket_errno ();
1483 win32_unset_event_mask (socket, FD_ACCEPT);
1488 if (socket->priv->blocking)
1490 #ifdef WSAEWOULDBLOCK
1491 if (errsv == WSAEWOULDBLOCK)
1494 if (errsv == EWOULDBLOCK ||
1500 g_set_error (error, G_IO_ERROR,
1501 socket_io_error_from_errno (errsv),
1502 _("Error accepting connection: %s"), socket_strerror (errsv));
1508 win32_unset_event_mask (socket, FD_ACCEPT);
1512 /* The socket inherits the accepting sockets event mask and even object,
1513 we need to remove that */
1514 WSAEventSelect (ret, NULL, 0);
1520 /* We always want to set close-on-exec to protect users. If you
1521 need to so some weird inheritance to exec you can re-enable this
1522 using lower level hacks with g_socket_get_fd(). */
1523 flags = fcntl (ret, F_GETFD, 0);
1525 (flags & FD_CLOEXEC) == 0)
1527 flags |= FD_CLOEXEC;
1528 fcntl (ret, F_SETFD, flags);
1533 new_socket = g_socket_new_from_fd (ret, error);
1534 if (new_socket == NULL)
1543 new_socket->priv->protocol = socket->priv->protocol;
1550 * @socket: a #GSocket.
1551 * @address: a #GSocketAddress specifying the remote address.
1552 * @cancellable: a %GCancellable or %NULL
1553 * @error: #GError for error reporting, or %NULL to ignore.
1555 * Connect the socket to the specified remote address.
1557 * For connection oriented socket this generally means we attempt to make
1558 * a connection to the @address. For a connection-less socket it sets
1559 * the default address for g_socket_send() and discards all incoming datagrams
1560 * from other sources.
1562 * Generally connection oriented sockets can only connect once, but
1563 * connection-less sockets can connect multiple times to change the
1566 * If the connect call needs to do network I/O it will block, unless
1567 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1568 * and the user can be notified of the connection finishing by waiting
1569 * for the G_IO_OUT condition. The result of the connection can then be
1570 * checked with g_socket_check_connect_result().
1572 * Returns: %TRUE if connected, %FALSE on error.
1577 g_socket_connect (GSocket *socket,
1578 GSocketAddress *address,
1579 GCancellable *cancellable,
1582 struct sockaddr_storage buffer;
1584 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1586 if (!check_socket (socket, error))
1589 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1594 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1595 g_socket_address_get_native_size (address)) < 0)
1597 int errsv = get_socket_errno ();
1603 if (errsv == EINPROGRESS)
1605 if (errsv == WSAEWOULDBLOCK)
1608 if (socket->priv->blocking)
1610 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
1612 if (g_socket_check_connect_result (socket, error))
1615 g_prefix_error (error, _("Error connecting: "));
1618 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1619 _("Connection in progress"));
1622 g_set_error (error, G_IO_ERROR,
1623 socket_io_error_from_errno (errsv),
1624 _("Error connecting: %s"), socket_strerror (errsv));
1631 win32_unset_event_mask (socket, FD_CONNECT);
1633 socket->priv->connected = TRUE;
1639 * g_socket_check_connect_result:
1640 * @socket: a #GSocket
1641 * @error: #GError for error reporting, or %NULL to ignore.
1643 * Checks and resets the pending connect error for the socket.
1644 * This is used to check for errors when g_socket_connect() is
1645 * used in non-blocking mode.
1647 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1652 g_socket_check_connect_result (GSocket *socket,
1658 if (!check_socket (socket, error))
1661 optlen = sizeof (value);
1662 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1664 int errsv = get_socket_errno ();
1666 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1667 _("Unable to get pending error: %s"), socket_strerror (errsv));
1673 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1674 socket_strerror (value));
1682 * @socket: a #GSocket
1683 * @buffer: a buffer to read data into (which should be at least @size
1685 * @size: the number of bytes you want to read from the socket
1686 * @cancellable: a %GCancellable or %NULL
1687 * @error: #GError for error reporting, or %NULL to ignore.
1689 * Receive data (up to @size bytes) from a socket. This is mainly used by
1690 * connection-oriented sockets; it is identical to g_socket_receive_from()
1691 * with @address set to %NULL.
1693 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1694 * g_socket_receive() will always read either 0 or 1 complete messages from
1695 * the socket. If the received message is too large to fit in @buffer, then
1696 * the data beyond @size bytes will be discarded, without any explicit
1697 * indication that this has occurred.
1699 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1700 * number of bytes, up to @size. If more than @size bytes have been
1701 * received, the additional data will be returned in future calls to
1702 * g_socket_receive().
1704 * If the socket is in blocking mode the call will block until there is
1705 * some data to receive or there is an error. If there is no data available
1706 * and the socket is in non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error
1707 * will be returned. To be notified when data is available, wait for the
1708 * %G_IO_IN condition.
1710 * On error -1 is returned and @error is set accordingly.
1712 * Returns: Number of bytes read, or -1 on error
1717 g_socket_receive (GSocket *socket,
1720 GCancellable *cancellable,
1725 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1727 if (!check_socket (socket, error))
1730 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1735 if (socket->priv->blocking &&
1736 !g_socket_condition_wait (socket,
1737 G_IO_IN, cancellable, error))
1740 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1742 int errsv = get_socket_errno ();
1747 if (socket->priv->blocking)
1749 #ifdef WSAEWOULDBLOCK
1750 if (errsv == WSAEWOULDBLOCK)
1753 if (errsv == EWOULDBLOCK ||
1759 win32_unset_event_mask (socket, FD_READ);
1761 g_set_error (error, G_IO_ERROR,
1762 socket_io_error_from_errno (errsv),
1763 _("Error receiving data: %s"), socket_strerror (errsv));
1767 win32_unset_event_mask (socket, FD_READ);
1776 * g_socket_receive_from:
1777 * @socket: a #GSocket
1778 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1779 * @buffer: a buffer to read data into (which should be at least @size
1781 * @size: the number of bytes you want to read from the socket
1782 * @cancellable: a %GCancellable or %NULL
1783 * @error: #GError for error reporting, or %NULL to ignore.
1785 * Receive data (up to @size bytes) from a socket.
1787 * If @address is non-%NULL then @address will be set equal to the
1788 * source address of the received packet.
1789 * @address is owned by the caller.
1791 * See g_socket_receive() for additional information.
1793 * Returns: Number of bytes read, or -1 on error
1798 g_socket_receive_from (GSocket *socket,
1799 GSocketAddress **address,
1802 GCancellable *cancellable,
1810 return g_socket_receive_message (socket,
1818 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1819 * one, which can be confusing and annoying. So if possible, we want
1820 * to suppress the signal entirely.
1823 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1825 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1830 * @socket: a #GSocket
1831 * @buffer: the buffer containing the data to send.
1832 * @size: the number of bytes to send
1833 * @cancellable: a %GCancellable or %NULL
1834 * @error: #GError for error reporting, or %NULL to ignore.
1836 * Tries to send @size bytes from @buffer on the socket. This is
1837 * mainly used by connection-oriented sockets; it is identical to
1838 * g_socket_send_to() with @address set to %NULL.
1840 * If the socket is in blocking mode the call will block until there is
1841 * space for the data in the socket queue. If there is no space available
1842 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1843 * will be returned. To be notified when space is available, wait for the
1844 * %G_IO_OUT condition. Note though that you may still receive
1845 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1846 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1847 * very common due to the way the underlying APIs work.)
1849 * On error -1 is returned and @error is set accordingly.
1851 * Returns: Number of bytes written (which may be less than @size), or -1
1857 g_socket_send (GSocket *socket,
1858 const gchar *buffer,
1860 GCancellable *cancellable,
1865 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1867 if (!check_socket (socket, error))
1870 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1875 if (socket->priv->blocking &&
1876 !g_socket_condition_wait (socket,
1877 G_IO_OUT, cancellable, error))
1880 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
1882 int errsv = get_socket_errno ();
1887 #ifdef WSAEWOULDBLOCK
1888 if (errsv == WSAEWOULDBLOCK)
1889 win32_unset_event_mask (socket, FD_WRITE);
1892 if (socket->priv->blocking)
1894 #ifdef WSAEWOULDBLOCK
1895 if (errsv == WSAEWOULDBLOCK)
1898 if (errsv == EWOULDBLOCK ||
1904 g_set_error (error, G_IO_ERROR,
1905 socket_io_error_from_errno (errsv),
1906 _("Error sending data: %s"), socket_strerror (errsv));
1917 * @socket: a #GSocket
1918 * @address: a #GSocketAddress, or %NULL
1919 * @buffer: the buffer containing the data to send.
1920 * @size: the number of bytes to send
1921 * @cancellable: a %GCancellable or %NULL
1922 * @error: #GError for error reporting, or %NULL to ignore.
1924 * Tries to send @size bytes from @buffer to @address. If @address is
1925 * %NULL then the message is sent to the default receiver (set by
1926 * g_socket_connect()).
1928 * See g_socket_send() for additional information.
1930 * Returns: Number of bytes written (which may be less than @size), or -1
1936 g_socket_send_to (GSocket *socket,
1937 GSocketAddress *address,
1938 const gchar *buffer,
1940 GCancellable *cancellable,
1948 return g_socket_send_message (socket,
1958 * g_socket_shutdown:
1959 * @socket: a #GSocket
1960 * @shutdown_read: whether to shut down the read side
1961 * @shutdown_write: whether to shut down the write side
1962 * @error: #GError for error reporting, or %NULL to ignore.
1964 * Shut down part of a full-duplex connection.
1966 * If @shutdown_read is %TRUE then the recieving side of the connection
1967 * is shut down, and further reading is disallowed.
1969 * If @shutdown_write is %TRUE then the sending side of the connection
1970 * is shut down, and further writing is disallowed.
1972 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
1974 * One example where this is used is graceful disconnect for TCP connections
1975 * where you close the sending side, then wait for the other side to close
1976 * the connection, thus ensuring that the other side saw all sent data.
1978 * Returns: %TRUE on success, %FALSE on error
1983 g_socket_shutdown (GSocket *socket,
1984 gboolean shutdown_read,
1985 gboolean shutdown_write,
1990 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1992 if (!check_socket (socket, NULL))
1996 if (!shutdown_read && !shutdown_write)
2000 if (shutdown_read && shutdown_write)
2002 else if (shutdown_read)
2007 if (shutdown_read && shutdown_write)
2009 else if (shutdown_read)
2015 if (shutdown (socket->priv->fd, how) != 0)
2017 int errsv = get_socket_errno ();
2018 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2019 _("Unable to create socket: %s"), socket_strerror (errsv));
2023 if (shutdown_read && shutdown_write)
2024 socket->priv->connected = FALSE;
2031 * @socket: a #GSocket
2032 * @error: #GError for error reporting, or %NULL to ignore.
2034 * Closes the socket, shutting down any active connection.
2036 * Closing a socket does not wait for all outstanding I/O operations
2037 * to finish, so the caller should not rely on them to be guaranteed
2038 * to complete even if the close returns with no error.
2040 * Once the socket is closed, all other operations will return
2041 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2044 * Sockets will be automatically closed when the last reference
2045 * is dropped, but you might want to call this function to make sure
2046 * resources are released as early as possible.
2048 * Beware that due to the way that TCP works, it is possible for
2049 * recently-sent data to be lost if either you close a socket while the
2050 * %G_IO_IN condition is set, or else if the remote connection tries to
2051 * send something to you after you close the socket but before it has
2052 * finished reading all of the data you sent. There is no easy generic
2053 * way to avoid this problem; the easiest fix is to design the network
2054 * protocol such that the client will never send data "out of turn".
2055 * Another solution is for the server to half-close the connection by
2056 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2057 * and then wait for the client to notice this and close its side of the
2058 * connection, after which the server can safely call g_socket_close().
2059 * (This is what #GTcpConnection does if you call
2060 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2061 * only works if the client will close its connection after the server
2064 * Returns: %TRUE on success, %FALSE on error
2069 g_socket_close (GSocket *socket,
2074 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2076 if (socket->priv->closed)
2077 return TRUE; /* Multiple close not an error */
2079 if (!check_socket (socket, NULL))
2085 res = closesocket (socket->priv->fd);
2087 res = close (socket->priv->fd);
2091 int errsv = get_socket_errno ();
2096 g_set_error (error, G_IO_ERROR,
2097 socket_io_error_from_errno (errsv),
2098 _("Error closing socket: %s"),
2099 socket_strerror (errsv));
2105 socket->priv->connected = FALSE;
2106 socket->priv->closed = TRUE;
2112 * g_socket_is_closed:
2113 * @socket: a #GSocket
2115 * Checks whether a socket is closed.
2117 * Returns: %TRUE if socket is closed, %FALSE otherwise
2122 g_socket_is_closed (GSocket *socket)
2124 return socket->priv->closed;
2128 /* Broken source, used on errors */
2130 broken_prepare (GSource *source,
2137 broken_check (GSource *source)
2143 broken_dispatch (GSource *source,
2144 GSourceFunc callback,
2150 static GSourceFuncs broken_funcs =
2159 network_events_for_condition (GIOCondition condition)
2163 if (condition & G_IO_IN)
2164 event_mask |= (FD_READ | FD_ACCEPT);
2165 if (condition & G_IO_OUT)
2166 event_mask |= (FD_WRITE | FD_CONNECT);
2167 event_mask |= FD_CLOSE;
2173 ensure_event (GSocket *socket)
2175 if (socket->priv->event == WSA_INVALID_EVENT)
2176 socket->priv->event = WSACreateEvent();
2180 update_select_events (GSocket *socket)
2187 ensure_event (socket);
2190 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2193 event_mask |= network_events_for_condition (*ptr);
2196 if (event_mask != socket->priv->selected_events)
2198 /* If no events selected, disable event so we can unset
2201 if (event_mask == 0)
2204 event = socket->priv->event;
2206 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2207 socket->priv->selected_events = event_mask;
2212 add_condition_watch (GSocket *socket,
2213 GIOCondition *condition)
2215 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2217 socket->priv->requested_conditions =
2218 g_list_prepend (socket->priv->requested_conditions, condition);
2220 update_select_events (socket);
2224 remove_condition_watch (GSocket *socket,
2225 GIOCondition *condition)
2227 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2229 socket->priv->requested_conditions =
2230 g_list_remove (socket->priv->requested_conditions, condition);
2232 update_select_events (socket);
2236 update_condition (GSocket *socket)
2238 WSANETWORKEVENTS events;
2239 GIOCondition condition;
2241 if (WSAEnumNetworkEvents (socket->priv->fd,
2242 socket->priv->event,
2245 socket->priv->current_events |= events.lNetworkEvents;
2246 if (events.lNetworkEvents & FD_WRITE &&
2247 events.iErrorCode[FD_WRITE_BIT] != 0)
2248 socket->priv->current_errors |= FD_WRITE;
2249 if (events.lNetworkEvents & FD_CONNECT &&
2250 events.iErrorCode[FD_CONNECT_BIT] != 0)
2251 socket->priv->current_errors |= FD_CONNECT;
2255 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2256 condition |= G_IO_IN;
2258 if (socket->priv->current_events & FD_CLOSE ||
2259 socket->priv->closed)
2260 condition |= G_IO_HUP;
2262 /* Never report both G_IO_OUT and HUP, these are
2263 mutually exclusive (can't write to a closed socket) */
2264 if ((condition & G_IO_HUP) == 0 &&
2265 socket->priv->current_events & FD_WRITE)
2267 if (socket->priv->current_errors & FD_WRITE)
2268 condition |= G_IO_ERR;
2270 condition |= G_IO_OUT;
2274 if (socket->priv->current_events & FD_CONNECT)
2276 if (socket->priv->current_errors & FD_CONNECT)
2277 condition |= (G_IO_HUP | G_IO_ERR);
2279 condition |= G_IO_OUT;
2291 GIOCondition condition;
2292 GCancellable *cancellable;
2293 GPollFD cancel_pollfd;
2294 GTimeVal timeout_time;
2298 socket_source_prepare (GSource *source,
2301 GSocketSource *socket_source = (GSocketSource *)source;
2303 if (g_cancellable_is_cancelled (socket_source->cancellable))
2306 if (socket_source->timeout_time.tv_sec)
2310 g_source_get_current_time (source, &now);
2311 *timeout = ((socket_source->timeout_time.tv_sec - now.tv_sec) * 1000 +
2312 (socket_source->timeout_time.tv_usec - now.tv_usec) / 1000);
2315 socket_source->socket->priv->timed_out = TRUE;
2316 socket_source->pollfd.revents = socket_source->condition & (G_IO_IN | G_IO_OUT);
2324 socket_source->pollfd.revents = update_condition (socket_source->socket);
2327 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2334 socket_source_check (GSource *source)
2338 return socket_source_prepare (source, &timeout);
2342 socket_source_dispatch (GSource *source,
2343 GSourceFunc callback,
2346 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2347 GSocketSource *socket_source = (GSocketSource *)source;
2349 return (*func) (socket_source->socket,
2350 socket_source->pollfd.revents & socket_source->condition,
2355 socket_source_finalize (GSource *source)
2357 GSocketSource *socket_source = (GSocketSource *)source;
2360 socket = socket_source->socket;
2363 remove_condition_watch (socket, &socket_source->condition);
2366 g_object_unref (socket);
2368 if (socket_source->cancellable)
2370 g_cancellable_release_fd (socket_source->cancellable);
2371 g_object_unref (socket_source->cancellable);
2375 static GSourceFuncs socket_source_funcs =
2377 socket_source_prepare,
2378 socket_source_check,
2379 socket_source_dispatch,
2380 socket_source_finalize
2384 socket_source_new (GSocket *socket,
2385 GIOCondition condition,
2386 GCancellable *cancellable)
2389 GSocketSource *socket_source;
2392 ensure_event (socket);
2394 if (socket->priv->event == WSA_INVALID_EVENT)
2396 g_warning ("Failed to create WSAEvent");
2397 return g_source_new (&broken_funcs, sizeof (GSource));
2401 condition |= G_IO_HUP | G_IO_ERR;
2403 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2404 g_source_set_name (source, "GSocket");
2405 socket_source = (GSocketSource *)source;
2407 socket_source->socket = g_object_ref (socket);
2408 socket_source->condition = condition;
2410 if (g_cancellable_make_pollfd (cancellable,
2411 &socket_source->cancel_pollfd))
2413 socket_source->cancellable = g_object_ref (cancellable);
2414 g_source_add_poll (source, &socket_source->cancel_pollfd);
2418 add_condition_watch (socket, &socket_source->condition);
2419 socket_source->pollfd.fd = (gintptr) socket->priv->event;
2421 socket_source->pollfd.fd = socket->priv->fd;
2424 socket_source->pollfd.events = condition;
2425 socket_source->pollfd.revents = 0;
2426 g_source_add_poll (source, &socket_source->pollfd);
2428 if (socket->priv->timeout)
2430 g_get_current_time (&socket_source->timeout_time);
2431 socket_source->timeout_time.tv_sec += socket->priv->timeout;
2435 socket_source->timeout_time.tv_sec = 0;
2436 socket_source->timeout_time.tv_usec = 0;
2443 * g_socket_create_source:
2444 * @socket: a #GSocket
2445 * @condition: a #GIOCondition mask to monitor
2446 * @cancellable: a %GCancellable or %NULL
2448 * Creates a %GSource that can be attached to a %GMainContext to monitor
2449 * for the availibility of the specified @condition on the socket.
2451 * The callback on the source is of the #GSocketSourceFunc type.
2453 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2454 * these conditions will always be reported output if they are true.
2456 * @cancellable if not %NULL can be used to cancel the source, which will
2457 * cause the source to trigger, reporting the current condition (which
2458 * is likely 0 unless cancellation happened at the same time as a
2459 * condition change). You can check for this in the callback using
2460 * g_cancellable_is_cancelled().
2462 * If @socket has a timeout set, and it is reached before @condition
2463 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2464 * %G_IO_OUT depending on @condition. However, @socket will have been
2465 * marked as having had a timeout, and so the next #GSocket I/O method
2466 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2468 * Returns: a newly allocated %GSource, free with g_source_unref().
2473 g_socket_create_source (GSocket *socket,
2474 GIOCondition condition,
2475 GCancellable *cancellable)
2477 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2479 return socket_source_new (socket, condition, cancellable);
2483 * g_socket_condition_check:
2484 * @socket: a #GSocket
2485 * @condition: a #GIOCondition mask to check
2487 * Checks on the readiness of @socket to perform operations.
2488 * The operations specified in @condition are checked for and masked
2489 * against the currently-satisfied conditions on @socket. The result
2492 * Note that on Windows, it is possible for an operation to return
2493 * %G_IO_ERROR_WOULD_BLOCK even immediately after
2494 * g_socket_condition_check() has claimed that the socket is ready for
2495 * writing. Rather than calling g_socket_condition_check() and then
2496 * writing to the socket if it succeeds, it is generally better to
2497 * simply try writing to the socket right away, and try again later if
2498 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
2500 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2501 * these conditions will always be set in the output if they are true.
2503 * This call never blocks.
2505 * Returns: the @GIOCondition mask of the current state
2510 g_socket_condition_check (GSocket *socket,
2511 GIOCondition condition)
2513 if (!check_socket (socket, NULL))
2518 GIOCondition current_condition;
2520 condition |= G_IO_ERR | G_IO_HUP;
2522 add_condition_watch (socket, &condition);
2523 current_condition = update_condition (socket);
2524 remove_condition_watch (socket, &condition);
2525 return condition & current_condition;
2531 poll_fd.fd = socket->priv->fd;
2532 poll_fd.events = condition;
2535 result = g_poll (&poll_fd, 1, 0);
2536 while (result == -1 && get_socket_errno () == EINTR);
2538 return poll_fd.revents;
2544 * g_socket_condition_wait:
2545 * @socket: a #GSocket
2546 * @condition: a #GIOCondition mask to wait for
2547 * @cancellable: a #GCancellable, or %NULL
2548 * @error: a #GError pointer, or %NULL
2550 * Waits for @condition to become true on @socket. When the condition
2551 * is met, %TRUE is returned.
2553 * If @cancellable is cancelled before the condition is met, or if the
2554 * socket has a timeout set and it is reached before the condition is
2555 * met, then %FALSE is returned and @error, if non-%NULL, is set to
2556 * the appropriate value (%G_IO_ERROR_CANCELLED or
2557 * %G_IO_ERROR_TIMED_OUT).
2559 * Returns: %TRUE if the condition was met, %FALSE otherwise
2564 g_socket_condition_wait (GSocket *socket,
2565 GIOCondition condition,
2566 GCancellable *cancellable,
2569 if (!check_socket (socket, error))
2572 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2577 GIOCondition current_condition;
2583 /* Always check these */
2584 condition |= G_IO_ERR | G_IO_HUP;
2586 add_condition_watch (socket, &condition);
2589 events[num_events++] = socket->priv->event;
2591 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2592 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2594 if (socket->priv->timeout)
2595 timeout = socket->priv->timeout * 1000;
2597 timeout = WSA_INFINITE;
2599 current_condition = update_condition (socket);
2600 while ((condition & current_condition) == 0)
2602 res = WSAWaitForMultipleEvents(num_events, events,
2603 FALSE, timeout, FALSE);
2604 if (res == WSA_WAIT_FAILED)
2606 int errsv = get_socket_errno ();
2608 g_set_error (error, G_IO_ERROR,
2609 socket_io_error_from_errno (errsv),
2610 _("Waiting for socket condition: %s"),
2611 socket_strerror (errsv));
2614 else if (res == WSA_WAIT_TIMEOUT)
2616 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2617 _("Socket I/O timed out"));
2621 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2624 current_condition = update_condition (socket);
2626 remove_condition_watch (socket, &condition);
2628 g_cancellable_release_fd (cancellable);
2630 return (condition & current_condition) != 0;
2639 poll_fd[0].fd = socket->priv->fd;
2640 poll_fd[0].events = condition;
2643 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2646 if (socket->priv->timeout)
2647 timeout = socket->priv->timeout * 1000;
2652 result = g_poll (poll_fd, num, timeout);
2653 while (result == -1 && get_socket_errno () == EINTR);
2656 g_cancellable_release_fd (cancellable);
2660 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2661 _("Socket I/O timed out"));
2665 return !g_cancellable_set_error_if_cancelled (cancellable, error);
2671 * g_socket_send_message:
2672 * @socket: a #GSocket
2673 * @address: a #GSocketAddress, or %NULL
2674 * @vectors: an array of #GOutputVector structs
2675 * @num_vectors: the number of elements in @vectors, or -1
2676 * @messages: a pointer to an array of #GSocketControlMessages, or
2678 * @num_messages: number of elements in @messages, or -1.
2679 * @flags: an int containing #GSocketMsgFlags flags
2680 * @cancellable: a %GCancellable or %NULL
2681 * @error: #GError for error reporting, or %NULL to ignore.
2683 * Send data to @address on @socket. This is the most complicated and
2684 * fully-featured version of this call. For easier use, see
2685 * g_socket_send() and g_socket_send_to().
2687 * If @address is %NULL then the message is sent to the default receiver
2688 * (set by g_socket_connect()).
2690 * @vectors must point to an array of #GOutputVector structs and
2691 * @num_vectors must be the length of this array. (If @num_vectors is -1,
2692 * then @vectors is assumed to be terminated by a #GOutputVector with a
2693 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2694 * that the sent data will be gathered from. Using multiple
2695 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2696 * data from multiple sources into a single buffer, and more
2697 * network-efficient than making multiple calls to g_socket_send().
2699 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2700 * #GSocketControlMessage instances. These correspond to the control
2701 * messages to be sent on the socket.
2702 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2705 * @flags modify how the message is sent. The commonly available arguments
2706 * for this are available in the #GSocketMsgFlags enum, but the
2707 * values there are the same as the system values, and the flags
2708 * are passed in as-is, so you can pass in system-specific flags too.
2710 * If the socket is in blocking mode the call will block until there is
2711 * space for the data in the socket queue. If there is no space available
2712 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2713 * will be returned. To be notified when space is available, wait for the
2714 * %G_IO_OUT condition. Note though that you may still receive
2715 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2716 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2717 * very common due to the way the underlying APIs work.)
2719 * On error -1 is returned and @error is set accordingly.
2721 * Returns: Number of bytes written (which may be less than @size), or -1
2727 g_socket_send_message (GSocket *socket,
2728 GSocketAddress *address,
2729 GOutputVector *vectors,
2731 GSocketControlMessage **messages,
2734 GCancellable *cancellable,
2737 GOutputVector one_vector;
2740 if (!check_socket (socket, error))
2743 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2746 if (num_vectors == -1)
2748 for (num_vectors = 0;
2749 vectors[num_vectors].buffer != NULL;
2754 if (num_messages == -1)
2756 for (num_messages = 0;
2757 messages != NULL && messages[num_messages] != NULL;
2762 if (num_vectors == 0)
2766 one_vector.buffer = &zero;
2767 one_vector.size = 1;
2769 vectors = &one_vector;
2780 msg.msg_namelen = g_socket_address_get_native_size (address);
2781 msg.msg_name = g_alloca (msg.msg_namelen);
2782 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2787 msg.msg_name = NULL;
2788 msg.msg_namelen = 0;
2793 /* this entire expression will be evaluated at compile time */
2794 if (sizeof *msg.msg_iov == sizeof *vectors &&
2795 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2796 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2797 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2798 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2799 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2800 G_STRUCT_OFFSET (GOutputVector, size))
2801 /* ABI is compatible */
2803 msg.msg_iov = (struct iovec *) vectors;
2804 msg.msg_iovlen = num_vectors;
2807 /* ABI is incompatible */
2811 msg.msg_iov = g_newa (struct iovec, num_vectors);
2812 for (i = 0; i < num_vectors; i++)
2814 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2815 msg.msg_iov[i].iov_len = vectors[i].size;
2817 msg.msg_iovlen = num_vectors;
2823 struct cmsghdr *cmsg;
2826 msg.msg_controllen = 0;
2827 for (i = 0; i < num_messages; i++)
2828 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2830 msg.msg_control = g_alloca (msg.msg_controllen);
2832 cmsg = CMSG_FIRSTHDR (&msg);
2833 for (i = 0; i < num_messages; i++)
2835 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2836 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2837 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2838 g_socket_control_message_serialize (messages[i],
2840 cmsg = CMSG_NXTHDR (&msg, cmsg);
2842 g_assert (cmsg == NULL);
2847 if (socket->priv->blocking &&
2848 !g_socket_condition_wait (socket,
2849 G_IO_OUT, cancellable, error))
2852 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
2855 int errsv = get_socket_errno ();
2860 if (socket->priv->blocking &&
2861 (errsv == EWOULDBLOCK ||
2865 g_set_error (error, G_IO_ERROR,
2866 socket_io_error_from_errno (errsv),
2867 _("Error sending message: %s"), socket_strerror (errsv));
2878 struct sockaddr_storage addr;
2885 /* Win32 doesn't support control messages.
2886 Actually this is possible for raw and datagram sockets
2887 via WSASendMessage on Vista or later, but that doesn't
2889 if (num_messages != 0)
2891 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2892 _("GSocketControlMessage not supported on windows"));
2897 bufs = g_newa (WSABUF, num_vectors);
2898 for (i = 0; i < num_vectors; i++)
2900 bufs[i].buf = (char *)vectors[i].buffer;
2901 bufs[i].len = (gulong)vectors[i].size;
2905 addrlen = 0; /* Avoid warning */
2908 addrlen = g_socket_address_get_native_size (address);
2909 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2915 if (socket->priv->blocking &&
2916 !g_socket_condition_wait (socket,
2917 G_IO_OUT, cancellable, error))
2921 result = WSASendTo (socket->priv->fd,
2924 (const struct sockaddr *)&addr, addrlen,
2927 result = WSASend (socket->priv->fd,
2934 int errsv = get_socket_errno ();
2936 if (errsv == WSAEINTR)
2939 if (errsv == WSAEWOULDBLOCK)
2940 win32_unset_event_mask (socket, FD_WRITE);
2942 if (socket->priv->blocking &&
2943 errsv == WSAEWOULDBLOCK)
2946 g_set_error (error, G_IO_ERROR,
2947 socket_io_error_from_errno (errsv),
2948 _("Error sending message: %s"), socket_strerror (errsv));
2961 * g_socket_receive_message:
2962 * @socket: a #GSocket
2963 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2964 * @vectors: an array of #GInputVector structs
2965 * @num_vectors: the number of elements in @vectors, or -1
2966 * @messages: a pointer which may be filled with an array of
2967 * #GSocketControlMessages, or %NULL
2968 * @num_messages: a pointer which will be filled with the number of
2969 * elements in @messages, or %NULL
2970 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2971 * @cancellable: a %GCancellable or %NULL
2972 * @error: a #GError pointer, or %NULL
2974 * Receive data from a socket. This is the most complicated and
2975 * fully-featured version of this call. For easier use, see
2976 * g_socket_receive() and g_socket_receive_from().
2978 * If @address is non-%NULL then @address will be set equal to the
2979 * source address of the received packet.
2980 * @address is owned by the caller.
2982 * @vector must point to an array of #GInputVector structs and
2983 * @num_vectors must be the length of this array. These structs
2984 * describe the buffers that received data will be scattered into.
2985 * If @num_vectors is -1, then @vectors is assumed to be terminated
2986 * by a #GInputVector with a %NULL buffer pointer.
2988 * As a special case, if @num_vectors is 0 (in which case, @vectors
2989 * may of course be %NULL), then a single byte is received and
2990 * discarded. This is to facilitate the common practice of sending a
2991 * single '\0' byte for the purposes of transferring ancillary data.
2993 * @messages, if non-%NULL, will be set to point to a newly-allocated
2994 * array of #GSocketControlMessage instances or %NULL if no such
2995 * messages was received. These correspond to the control messages
2996 * received from the kernel, one #GSocketControlMessage per message
2997 * from the kernel. This array is %NULL-terminated and must be freed
2998 * by the caller using g_free() after calling g_object_unref() on each
2999 * element. If @messages is %NULL, any control messages received will
3002 * @num_messages, if non-%NULL, will be set to the number of control
3003 * messages received.
3005 * If both @messages and @num_messages are non-%NULL, then
3006 * @num_messages gives the number of #GSocketControlMessage instances
3007 * in @messages (ie: not including the %NULL terminator).
3009 * @flags is an in/out parameter. The commonly available arguments
3010 * for this are available in the #GSocketMsgFlags enum, but the
3011 * values there are the same as the system values, and the flags
3012 * are passed in as-is, so you can pass in system-specific flags too
3013 * (and g_socket_receive_message() may pass system-specific flags out).
3015 * As with g_socket_receive(), data may be discarded if @socket is
3016 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3017 * provide enough buffer space to read a complete message. You can pass
3018 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3019 * removing it from the receive queue, but there is no portable way to find
3020 * out the length of the message other than by reading it into a
3021 * sufficiently-large buffer.
3023 * If the socket is in blocking mode the call will block until there
3024 * is some data to receive or there is an error. If there is no data
3025 * available and the socket is in non-blocking mode, a
3026 * %G_IO_ERROR_WOULD_BLOCK error will be returned. To be notified when
3027 * data is available, wait for the %G_IO_IN condition.
3029 * On error -1 is returned and @error is set accordingly.
3031 * Returns: Number of bytes read, or -1 on error
3036 g_socket_receive_message (GSocket *socket,
3037 GSocketAddress **address,
3038 GInputVector *vectors,
3040 GSocketControlMessage ***messages,
3043 GCancellable *cancellable,
3046 GInputVector one_vector;
3049 if (!check_socket (socket, error))
3052 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3055 if (num_vectors == -1)
3057 for (num_vectors = 0;
3058 vectors[num_vectors].buffer != NULL;
3063 if (num_vectors == 0)
3065 one_vector.buffer = &one_byte;
3066 one_vector.size = 1;
3068 vectors = &one_vector;
3075 struct sockaddr_storage one_sockaddr;
3080 msg.msg_name = &one_sockaddr;
3081 msg.msg_namelen = sizeof (struct sockaddr_storage);
3085 msg.msg_name = NULL;
3086 msg.msg_namelen = 0;
3090 /* this entire expression will be evaluated at compile time */
3091 if (sizeof *msg.msg_iov == sizeof *vectors &&
3092 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3093 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3094 G_STRUCT_OFFSET (GInputVector, buffer) &&
3095 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3096 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3097 G_STRUCT_OFFSET (GInputVector, size))
3098 /* ABI is compatible */
3100 msg.msg_iov = (struct iovec *) vectors;
3101 msg.msg_iovlen = num_vectors;
3104 /* ABI is incompatible */
3108 msg.msg_iov = g_newa (struct iovec, num_vectors);
3109 for (i = 0; i < num_vectors; i++)
3111 msg.msg_iov[i].iov_base = vectors[i].buffer;
3112 msg.msg_iov[i].iov_len = vectors[i].size;
3114 msg.msg_iovlen = num_vectors;
3118 msg.msg_control = g_alloca (2048);
3119 msg.msg_controllen = 2048;
3123 msg.msg_flags = *flags;
3130 if (socket->priv->blocking &&
3131 !g_socket_condition_wait (socket,
3132 G_IO_IN, cancellable, error))
3135 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3139 int errsv = get_socket_errno ();
3144 if (socket->priv->blocking &&
3145 (errsv == EWOULDBLOCK ||
3149 g_set_error (error, G_IO_ERROR,
3150 socket_io_error_from_errno (errsv),
3151 _("Error receiving message: %s"), socket_strerror (errsv));
3158 /* decode address */
3159 if (address != NULL)
3161 if (msg.msg_namelen > 0)
3162 *address = g_socket_address_new_from_native (msg.msg_name,
3168 /* decode control messages */
3170 GPtrArray *my_messages = NULL;
3171 const gchar *scm_pointer;
3172 struct cmsghdr *cmsg;
3175 scm_pointer = (const gchar *) msg.msg_control;
3176 scm_size = msg.msg_controllen;
3178 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3180 GSocketControlMessage *message;
3182 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3184 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3186 if (message == NULL)
3187 /* We've already spewed about the problem in the
3188 deserialization code, so just continue */
3191 if (messages == NULL)
3193 /* we have to do it this way if the user ignores the
3194 * messages so that we will close any received fds.
3196 g_object_unref (message);
3200 if (my_messages == NULL)
3201 my_messages = g_ptr_array_new ();
3202 g_ptr_array_add (my_messages, message);
3207 *num_messages = my_messages != NULL ? my_messages->len : 0;
3211 if (my_messages == NULL)
3217 g_ptr_array_add (my_messages, NULL);
3218 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3223 g_assert (my_messages == NULL);
3227 /* capture the flags */
3229 *flags = msg.msg_flags;
3235 struct sockaddr_storage addr;
3237 DWORD bytes_received;
3244 bufs = g_newa (WSABUF, num_vectors);
3245 for (i = 0; i < num_vectors; i++)
3247 bufs[i].buf = (char *)vectors[i].buffer;
3248 bufs[i].len = (gulong)vectors[i].size;
3260 if (socket->priv->blocking &&
3261 !g_socket_condition_wait (socket,
3262 G_IO_IN, cancellable, error))
3265 addrlen = sizeof addr;
3267 result = WSARecvFrom (socket->priv->fd,
3269 &bytes_received, &win_flags,
3270 (struct sockaddr *)&addr, &addrlen,
3273 result = WSARecv (socket->priv->fd,
3275 &bytes_received, &win_flags,
3279 int errsv = get_socket_errno ();
3281 if (errsv == WSAEINTR)
3284 win32_unset_event_mask (socket, FD_READ);
3286 if (socket->priv->blocking &&
3287 errsv == WSAEWOULDBLOCK)
3290 g_set_error (error, G_IO_ERROR,
3291 socket_io_error_from_errno (errsv),
3292 _("Error receiving message: %s"), socket_strerror (errsv));
3296 win32_unset_event_mask (socket, FD_READ);
3300 /* decode address */
3301 if (address != NULL)
3304 *address = g_socket_address_new_from_native (&addr, addrlen);
3309 /* capture the flags */
3313 if (messages != NULL)
3315 if (num_messages != NULL)
3318 return bytes_received;