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 last_msg = G_STATIC_PRIVATE_INIT;
218 msg = g_win32_error_message (err);
219 g_static_private_set (&last_msg, msg, g_free);
226 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
228 _win32_unset_event_mask (GSocket *socket, int mask)
230 socket->priv->current_events &= ~mask;
231 socket->priv->current_errors &= ~mask;
234 #define win32_unset_event_mask(_socket, _mask)
238 set_fd_nonblocking (int fd)
247 if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
249 g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
253 arg = arg | O_NONBLOCK;
255 if (fcntl (fd, F_SETFL, arg) < 0)
256 g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
260 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
262 int errsv = get_socket_errno ();
263 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
269 check_socket (GSocket *socket,
272 if (!socket->priv->inited)
274 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
275 _("Invalid socket, not initialized"));
279 if (socket->priv->construct_error)
281 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
282 _("Invalid socket, initialization failed due to: %s"),
283 socket->priv->construct_error->message);
287 if (socket->priv->closed)
289 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
290 _("Socket is already closed"));
294 if (socket->priv->timed_out)
296 socket->priv->timed_out = FALSE;
297 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
298 _("Socket I/O timed out"));
306 g_socket_details_from_fd (GSocket *socket)
308 struct sockaddr_storage address;
315 /* See bug #611756 */
316 BOOL bool_val = FALSE;
321 fd = socket->priv->fd;
322 optlen = sizeof value;
323 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
325 errsv = get_socket_errno ();
336 /* programmer error */
337 g_error ("creating GSocket from fd %d: %s\n",
338 fd, socket_strerror (errsv));
346 g_assert (optlen == sizeof value);
350 socket->priv->type = G_SOCKET_TYPE_STREAM;
354 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
358 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
362 socket->priv->type = G_SOCKET_TYPE_INVALID;
366 addrlen = sizeof address;
367 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
369 errsv = get_socket_errno ();
373 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
374 sizeof address.ss_family <= addrlen);
375 switch (address.ss_family)
377 case G_SOCKET_FAMILY_IPV4:
378 case G_SOCKET_FAMILY_IPV6:
379 case G_SOCKET_FAMILY_UNIX:
380 socket->priv->family = address.ss_family;
384 socket->priv->family = G_SOCKET_FAMILY_INVALID;
388 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
390 addrlen = sizeof address;
391 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
392 socket->priv->connected = TRUE;
395 optlen = sizeof bool_val;
396 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
397 (void *)&bool_val, &optlen) == 0)
400 /* Experimentation indicates that the SO_KEEPALIVE value is
401 * actually a char on Windows, even if documentation claims it
402 * to be a BOOL which is a typedef for int. So this g_assert()
403 * fails. See bug #611756.
405 g_assert (optlen == sizeof bool_val);
407 socket->priv->keepalive = !!bool_val;
411 /* Can't read, maybe not supported, assume FALSE */
412 socket->priv->keepalive = FALSE;
418 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
419 socket_io_error_from_errno (errsv),
420 _("creating GSocket from fd: %s"),
421 socket_strerror (errsv));
425 g_socket_create_socket (GSocketFamily family,
435 case G_SOCKET_TYPE_STREAM:
436 native_type = SOCK_STREAM;
439 case G_SOCKET_TYPE_DATAGRAM:
440 native_type = SOCK_DGRAM;
443 case G_SOCKET_TYPE_SEQPACKET:
444 native_type = SOCK_SEQPACKET;
448 g_assert_not_reached ();
453 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
454 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
459 native_type |= SOCK_CLOEXEC;
461 fd = socket (family, native_type, protocol);
465 int errsv = get_socket_errno ();
467 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
468 _("Unable to create socket: %s"), socket_strerror (errsv));
475 /* We always want to set close-on-exec to protect users. If you
476 need to so some weird inheritance to exec you can re-enable this
477 using lower level hacks with g_socket_get_fd(). */
478 flags = fcntl (fd, F_GETFD, 0);
480 (flags & FD_CLOEXEC) == 0)
483 fcntl (fd, F_SETFD, flags);
492 g_socket_constructed (GObject *object)
494 GSocket *socket = G_SOCKET (object);
496 if (socket->priv->fd >= 0)
497 /* create socket->priv info from the fd */
498 g_socket_details_from_fd (socket);
501 /* create the fd from socket->priv info */
502 socket->priv->fd = g_socket_create_socket (socket->priv->family,
504 socket->priv->protocol,
505 &socket->priv->construct_error);
507 /* Always use native nonblocking sockets, as
508 windows sets sockets to nonblocking automatically
509 in certain operations. This way we make things work
510 the same on all platforms */
511 if (socket->priv->fd != -1)
512 set_fd_nonblocking (socket->priv->fd);
516 g_socket_get_property (GObject *object,
521 GSocket *socket = G_SOCKET (object);
522 GSocketAddress *address;
527 g_value_set_enum (value, socket->priv->family);
531 g_value_set_enum (value, socket->priv->type);
535 g_value_set_enum (value, socket->priv->protocol);
539 g_value_set_int (value, socket->priv->fd);
543 g_value_set_boolean (value, socket->priv->blocking);
546 case PROP_LISTEN_BACKLOG:
547 g_value_set_int (value, socket->priv->listen_backlog);
551 g_value_set_boolean (value, socket->priv->keepalive);
554 case PROP_LOCAL_ADDRESS:
555 address = g_socket_get_local_address (socket, NULL);
556 g_value_take_object (value, address);
559 case PROP_REMOTE_ADDRESS:
560 address = g_socket_get_remote_address (socket, NULL);
561 g_value_take_object (value, address);
565 g_value_set_uint (value, socket->priv->timeout);
569 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
574 g_socket_set_property (GObject *object,
579 GSocket *socket = G_SOCKET (object);
584 socket->priv->family = g_value_get_enum (value);
588 socket->priv->type = g_value_get_enum (value);
592 socket->priv->protocol = g_value_get_enum (value);
596 socket->priv->fd = g_value_get_int (value);
600 g_socket_set_blocking (socket, g_value_get_boolean (value));
603 case PROP_LISTEN_BACKLOG:
604 g_socket_set_listen_backlog (socket, g_value_get_int (value));
608 g_socket_set_keepalive (socket, g_value_get_boolean (value));
612 g_socket_set_timeout (socket, g_value_get_uint (value));
616 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
621 g_socket_finalize (GObject *object)
623 GSocket *socket = G_SOCKET (object);
625 g_clear_error (&socket->priv->construct_error);
627 if (socket->priv->fd != -1 &&
628 !socket->priv->closed)
629 g_socket_close (socket, NULL);
632 if (socket->priv->event != WSA_INVALID_EVENT)
634 WSACloseEvent (socket->priv->event);
635 socket->priv->event = WSA_INVALID_EVENT;
638 g_assert (socket->priv->requested_conditions == NULL);
641 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
642 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
646 g_socket_class_init (GSocketClass *klass)
648 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
651 /* Make sure winsock has been initialized */
652 type = g_inet_address_get_type ();
655 /* There is no portable, thread-safe way to avoid having the process
656 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
657 * forced to simply ignore the signal process-wide.
659 signal (SIGPIPE, SIG_IGN);
662 g_type_class_add_private (klass, sizeof (GSocketPrivate));
664 gobject_class->finalize = g_socket_finalize;
665 gobject_class->constructed = g_socket_constructed;
666 gobject_class->set_property = g_socket_set_property;
667 gobject_class->get_property = g_socket_get_property;
669 g_object_class_install_property (gobject_class, PROP_FAMILY,
670 g_param_spec_enum ("family",
672 P_("The sockets address family"),
673 G_TYPE_SOCKET_FAMILY,
674 G_SOCKET_FAMILY_INVALID,
675 G_PARAM_CONSTRUCT_ONLY |
677 G_PARAM_STATIC_STRINGS));
679 g_object_class_install_property (gobject_class, PROP_TYPE,
680 g_param_spec_enum ("type",
682 P_("The sockets type"),
684 G_SOCKET_TYPE_STREAM,
685 G_PARAM_CONSTRUCT_ONLY |
687 G_PARAM_STATIC_STRINGS));
689 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
690 g_param_spec_enum ("protocol",
691 P_("Socket protocol"),
692 P_("The id of the protocol to use, or -1 for unknown"),
693 G_TYPE_SOCKET_PROTOCOL,
694 G_SOCKET_PROTOCOL_UNKNOWN,
695 G_PARAM_CONSTRUCT_ONLY |
697 G_PARAM_STATIC_STRINGS));
699 g_object_class_install_property (gobject_class, PROP_FD,
700 g_param_spec_int ("fd",
701 P_("File descriptor"),
702 P_("The sockets file descriptor"),
706 G_PARAM_CONSTRUCT_ONLY |
708 G_PARAM_STATIC_STRINGS));
710 g_object_class_install_property (gobject_class, PROP_BLOCKING,
711 g_param_spec_boolean ("blocking",
713 P_("Whether or not I/O on this socket is blocking"),
716 G_PARAM_STATIC_STRINGS));
718 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
719 g_param_spec_int ("listen-backlog",
720 P_("Listen backlog"),
721 P_("Outstanding connections in the listen queue"),
726 G_PARAM_STATIC_STRINGS));
728 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
729 g_param_spec_boolean ("keepalive",
730 P_("Keep connection alive"),
731 P_("Keep connection alive by sending periodic pings"),
734 G_PARAM_STATIC_STRINGS));
736 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
737 g_param_spec_object ("local-address",
739 P_("The local address the socket is bound to"),
740 G_TYPE_SOCKET_ADDRESS,
742 G_PARAM_STATIC_STRINGS));
744 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
745 g_param_spec_object ("remote-address",
746 P_("Remote address"),
747 P_("The remote address the socket is connected to"),
748 G_TYPE_SOCKET_ADDRESS,
750 G_PARAM_STATIC_STRINGS));
755 * The timeout in seconds on socket I/O
759 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
760 g_param_spec_uint ("timeout",
762 P_("The timeout in seconds on socket I/O"),
767 G_PARAM_STATIC_STRINGS));
771 g_socket_initable_iface_init (GInitableIface *iface)
773 iface->init = g_socket_initable_init;
777 g_socket_init (GSocket *socket)
779 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
781 socket->priv->fd = -1;
782 socket->priv->blocking = TRUE;
783 socket->priv->listen_backlog = 10;
784 socket->priv->construct_error = NULL;
786 socket->priv->event = WSA_INVALID_EVENT;
791 g_socket_initable_init (GInitable *initable,
792 GCancellable *cancellable,
797 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
799 socket = G_SOCKET (initable);
801 if (cancellable != NULL)
803 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
804 _("Cancellable initialization not supported"));
808 socket->priv->inited = TRUE;
810 if (socket->priv->construct_error)
813 *error = g_error_copy (socket->priv->construct_error);
823 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
824 * @type: the socket type to use.
825 * @protocol: the id of the protocol to use, or 0 for default.
826 * @error: #GError for error reporting, or %NULL to ignore.
828 * Creates a new #GSocket with the defined family, type and protocol.
829 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
830 * for the family and type is used.
832 * The @protocol is a family and type specific int that specifies what
833 * kind of protocol to use. #GSocketProtocol lists several common ones.
834 * Many families only support one protocol, and use 0 for this, others
835 * support several and using 0 means to use the default protocol for
836 * the family and type.
838 * The protocol id is passed directly to the operating
839 * system, so you can use protocols not listed in #GSocketProtocol if you
840 * know the protocol number used for it.
842 * Returns: a #GSocket or %NULL on error.
843 * Free the returned object with g_object_unref().
848 g_socket_new (GSocketFamily family,
850 GSocketProtocol protocol,
853 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
857 "protocol", protocol,
862 * g_socket_new_from_fd:
863 * @fd: a native socket file descriptor.
864 * @error: #GError for error reporting, or %NULL to ignore.
866 * Creates a new #GSocket from a native file descriptor
867 * or winsock SOCKET handle.
869 * This reads all the settings from the file descriptor so that
870 * all properties should work. Note that the file descriptor
871 * will be set to non-blocking mode, independent on the blocking
872 * mode of the #GSocket.
874 * Returns: a #GSocket or %NULL on error.
875 * Free the returned object with g_object_unref().
880 g_socket_new_from_fd (gint fd,
883 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
890 * g_socket_set_blocking:
891 * @socket: a #GSocket.
892 * @blocking: Whether to use blocking I/O or not.
894 * Sets the blocking mode of the socket. In blocking mode
895 * all operations block until they succeed or there is an error. In
896 * non-blocking mode all functions return results immediately or
897 * with a %G_IO_ERROR_WOULD_BLOCK error.
899 * All sockets are created in blocking mode. However, note that the
900 * platform level socket is always non-blocking, and blocking mode
901 * is a GSocket level feature.
906 g_socket_set_blocking (GSocket *socket,
909 g_return_if_fail (G_IS_SOCKET (socket));
911 blocking = !!blocking;
913 if (socket->priv->blocking == blocking)
916 socket->priv->blocking = blocking;
917 g_object_notify (G_OBJECT (socket), "blocking");
921 * g_socket_get_blocking:
922 * @socket: a #GSocket.
924 * Gets the blocking mode of the socket. For details on blocking I/O,
925 * see g_socket_set_blocking().
927 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
932 g_socket_get_blocking (GSocket *socket)
934 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
936 return socket->priv->blocking;
940 * g_socket_set_keepalive:
941 * @socket: a #GSocket.
942 * @keepalive: Value for the keepalive flag
944 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
945 * this flag is set on a socket, the system will attempt to verify that the
946 * remote socket endpoint is still present if a sufficiently long period of
947 * time passes with no data being exchanged. If the system is unable to
948 * verify the presence of the remote endpoint, it will automatically close
951 * This option is only functional on certain kinds of sockets. (Notably,
952 * %G_SOCKET_PROTOCOL_TCP sockets.)
954 * The exact time between pings is system- and protocol-dependent, but will
955 * normally be at least two hours. Most commonly, you would set this flag
956 * on a server socket if you want to allow clients to remain idle for long
957 * periods of time, but also want to ensure that connections are eventually
958 * garbage-collected if clients crash or become unreachable.
963 g_socket_set_keepalive (GSocket *socket,
968 g_return_if_fail (G_IS_SOCKET (socket));
970 keepalive = !!keepalive;
971 if (socket->priv->keepalive == keepalive)
974 value = (gint) keepalive;
975 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
976 (gpointer) &value, sizeof (value)) < 0)
978 int errsv = get_socket_errno ();
979 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
983 socket->priv->keepalive = keepalive;
984 g_object_notify (G_OBJECT (socket), "keepalive");
988 * g_socket_get_keepalive:
989 * @socket: a #GSocket.
991 * Gets the keepalive mode of the socket. For details on this,
992 * see g_socket_set_keepalive().
994 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
999 g_socket_get_keepalive (GSocket *socket)
1001 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1003 return socket->priv->keepalive;
1007 * g_socket_get_listen_backlog:
1008 * @socket: a #GSocket.
1010 * Gets the listen backlog setting of the socket. For details on this,
1011 * see g_socket_set_listen_backlog().
1013 * Returns: the maximum number of pending connections.
1018 g_socket_get_listen_backlog (GSocket *socket)
1020 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1022 return socket->priv->listen_backlog;
1026 * g_socket_set_listen_backlog:
1027 * @socket: a #GSocket.
1028 * @backlog: the maximum number of pending connections.
1030 * Sets the maximum number of outstanding connections allowed
1031 * when listening on this socket. If more clients than this are
1032 * connecting to the socket and the application is not handling them
1033 * on time then the new connections will be refused.
1035 * Note that this must be called before g_socket_listen() and has no
1036 * effect if called after that.
1041 g_socket_set_listen_backlog (GSocket *socket,
1044 g_return_if_fail (G_IS_SOCKET (socket));
1045 g_return_if_fail (!socket->priv->listening);
1047 if (backlog != socket->priv->listen_backlog)
1049 socket->priv->listen_backlog = backlog;
1050 g_object_notify (G_OBJECT (socket), "listen-backlog");
1055 * g_socket_get_timeout:
1056 * @socket: a #GSocket.
1058 * Gets the timeout setting of the socket. For details on this, see
1059 * g_socket_set_timeout().
1061 * Returns: the timeout in seconds
1066 g_socket_get_timeout (GSocket *socket)
1068 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1070 return socket->priv->timeout;
1074 * g_socket_set_timeout:
1075 * @socket: a #GSocket.
1076 * @timeout: the timeout for @socket, in seconds, or 0 for none
1078 * Sets the time in seconds after which I/O operations on @socket will
1079 * time out if they have not yet completed.
1081 * On a blocking socket, this means that any blocking #GSocket
1082 * operation will time out after @timeout seconds of inactivity,
1083 * returning %G_IO_ERROR_TIMED_OUT.
1085 * On a non-blocking socket, calls to g_socket_condition_wait() will
1086 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1087 * created with g_socket_create_source() will trigger after
1088 * @timeout seconds of inactivity, with the requested condition
1089 * set, at which point calling g_socket_receive(), g_socket_send(),
1090 * g_socket_check_connect_result(), etc, will fail with
1091 * %G_IO_ERROR_TIMED_OUT.
1093 * If @timeout is 0 (the default), operations will never time out
1096 * Note that if an I/O operation is interrupted by a signal, this may
1097 * cause the timeout to be reset.
1102 g_socket_set_timeout (GSocket *socket,
1105 g_return_if_fail (G_IS_SOCKET (socket));
1107 if (timeout != socket->priv->timeout)
1109 socket->priv->timeout = timeout;
1110 g_object_notify (G_OBJECT (socket), "timeout");
1115 * g_socket_get_family:
1116 * @socket: a #GSocket.
1118 * Gets the socket family of the socket.
1120 * Returns: a #GSocketFamily
1125 g_socket_get_family (GSocket *socket)
1127 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1129 return socket->priv->family;
1133 * g_socket_get_socket_type:
1134 * @socket: a #GSocket.
1136 * Gets the socket type of the socket.
1138 * Returns: a #GSocketType
1143 g_socket_get_socket_type (GSocket *socket)
1145 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1147 return socket->priv->type;
1151 * g_socket_get_protocol:
1152 * @socket: a #GSocket.
1154 * Gets the socket protocol id the socket was created with.
1155 * In case the protocol is unknown, -1 is returned.
1157 * Returns: a protocol id, or -1 if unknown
1162 g_socket_get_protocol (GSocket *socket)
1164 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1166 return socket->priv->protocol;
1171 * @socket: a #GSocket.
1173 * Returns the underlying OS socket object. On unix this
1174 * is a socket file descriptor, and on windows this is
1175 * a Winsock2 SOCKET handle. This may be useful for
1176 * doing platform specific or otherwise unusual operations
1179 * Returns: the file descriptor of the socket.
1184 g_socket_get_fd (GSocket *socket)
1186 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1188 return socket->priv->fd;
1192 * g_socket_get_local_address:
1193 * @socket: a #GSocket.
1194 * @error: #GError for error reporting, or %NULL to ignore.
1196 * Try to get the local address of a bound socket. This is only
1197 * useful if the socket has been bound to a local address,
1198 * either explicitly or implicitly when connecting.
1200 * Returns: a #GSocketAddress or %NULL on error.
1201 * Free the returned object with g_object_unref().
1206 g_socket_get_local_address (GSocket *socket,
1209 struct sockaddr_storage buffer;
1210 guint32 len = sizeof (buffer);
1212 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1214 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1216 int errsv = get_socket_errno ();
1217 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1218 _("could not get local address: %s"), socket_strerror (errsv));
1222 return g_socket_address_new_from_native (&buffer, len);
1226 * g_socket_get_remote_address:
1227 * @socket: a #GSocket.
1228 * @error: #GError for error reporting, or %NULL to ignore.
1230 * Try to get the remove address of a connected socket. This is only
1231 * useful for connection oriented sockets that have been connected.
1233 * Returns: a #GSocketAddress or %NULL on error.
1234 * Free the returned object with g_object_unref().
1239 g_socket_get_remote_address (GSocket *socket,
1242 struct sockaddr_storage buffer;
1243 guint32 len = sizeof (buffer);
1245 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1247 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1249 int errsv = get_socket_errno ();
1250 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1251 _("could not get remote address: %s"), socket_strerror (errsv));
1255 return g_socket_address_new_from_native (&buffer, len);
1259 * g_socket_is_connected:
1260 * @socket: a #GSocket.
1262 * Check whether the socket is connected. This is only useful for
1263 * connection-oriented sockets.
1265 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1270 g_socket_is_connected (GSocket *socket)
1272 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1274 return socket->priv->connected;
1279 * @socket: a #GSocket.
1280 * @error: #GError for error reporting, or %NULL to ignore.
1282 * Marks the socket as a server socket, i.e. a socket that is used
1283 * to accept incoming requests using g_socket_accept().
1285 * Before calling this the socket must be bound to a local address using
1288 * To set the maximum amount of outstanding clients, use
1289 * g_socket_set_listen_backlog().
1291 * Returns: %TRUE on success, %FALSE on error.
1296 g_socket_listen (GSocket *socket,
1299 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1301 if (!check_socket (socket, error))
1304 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1306 int errsv = get_socket_errno ();
1308 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1309 _("could not listen: %s"), socket_strerror (errsv));
1313 socket->priv->listening = TRUE;
1320 * @socket: a #GSocket.
1321 * @address: a #GSocketAddress specifying the local address.
1322 * @allow_reuse: whether to allow reusing this address
1323 * @error: #GError for error reporting, or %NULL to ignore.
1325 * When a socket is created it is attached to an address family, but it
1326 * doesn't have an address in this family. g_socket_bind() assigns the
1327 * address (sometimes called name) of the socket.
1329 * It is generally required to bind to a local address before you can
1330 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1331 * In certain situations, you may also want to bind a socket that will be
1332 * used to initiate connections, though this is not normally required.
1334 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1335 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1336 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1337 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1338 * that address was previously used by another socket that has not yet been
1339 * fully cleaned-up by the kernel. Failing to set this flag on a server
1340 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1341 * the server program is stopped and then immediately restarted.)
1343 * Returns: %TRUE on success, %FALSE on error.
1348 g_socket_bind (GSocket *socket,
1349 GSocketAddress *address,
1350 gboolean reuse_address,
1353 struct sockaddr_storage addr;
1355 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1357 if (!check_socket (socket, error))
1360 /* SO_REUSEADDR on windows means something else and is not what we want.
1361 It always allows the unix variant of SO_REUSEADDR anyway */
1366 value = (int) !!reuse_address;
1367 /* Ignore errors here, the only likely error is "not supported", and
1368 this is a "best effort" thing mainly */
1369 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1370 (gpointer) &value, sizeof (value));
1374 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1377 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1378 g_socket_address_get_native_size (address)) < 0)
1380 int errsv = get_socket_errno ();
1382 G_IO_ERROR, socket_io_error_from_errno (errsv),
1383 _("Error binding to address: %s"), socket_strerror (errsv));
1391 * g_socket_speaks_ipv4:
1392 * @socket: a #GSocket
1394 * Checks if a socket is capable of speaking IPv4.
1396 * IPv4 sockets are capable of speaking IPv4. On some operating systems
1397 * and under some combinations of circumstances IPv6 sockets are also
1398 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
1401 * No other types of sockets are currently considered as being capable
1404 * Returns: %TRUE if this socket can be used with IPv4.
1409 g_socket_speaks_ipv4 (GSocket *socket)
1411 switch (socket->priv->family)
1413 case G_SOCKET_FAMILY_IPV4:
1416 case G_SOCKET_FAMILY_IPV6:
1417 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1419 guint sizeof_int = sizeof (int);
1422 if (getsockopt (socket->priv->fd,
1423 IPPROTO_IPV6, IPV6_V6ONLY,
1424 &v6_only, &sizeof_int) != 0)
1440 * @socket: a #GSocket.
1441 * @cancellable: a %GCancellable or %NULL
1442 * @error: #GError for error reporting, or %NULL to ignore.
1444 * Accept incoming connections on a connection-based socket. This removes
1445 * the first outstanding connection request from the listening socket and
1446 * creates a #GSocket object for it.
1448 * The @socket must be bound to a local address with g_socket_bind() and
1449 * must be listening for incoming connections (g_socket_listen()).
1451 * If there are no outstanding connections then the operation will block
1452 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1453 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1455 * Returns: a new #GSocket, or %NULL on error.
1456 * Free the returned object with g_object_unref().
1461 g_socket_accept (GSocket *socket,
1462 GCancellable *cancellable,
1465 GSocket *new_socket;
1468 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1470 if (!check_socket (socket, error))
1475 if (socket->priv->blocking &&
1476 !g_socket_condition_wait (socket,
1477 G_IO_IN, cancellable, error))
1480 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1482 int errsv = get_socket_errno ();
1484 win32_unset_event_mask (socket, FD_ACCEPT);
1489 if (socket->priv->blocking)
1491 #ifdef WSAEWOULDBLOCK
1492 if (errsv == WSAEWOULDBLOCK)
1495 if (errsv == EWOULDBLOCK ||
1501 g_set_error (error, G_IO_ERROR,
1502 socket_io_error_from_errno (errsv),
1503 _("Error accepting connection: %s"), socket_strerror (errsv));
1509 win32_unset_event_mask (socket, FD_ACCEPT);
1513 /* The socket inherits the accepting sockets event mask and even object,
1514 we need to remove that */
1515 WSAEventSelect (ret, NULL, 0);
1521 /* We always want to set close-on-exec to protect users. If you
1522 need to so some weird inheritance to exec you can re-enable this
1523 using lower level hacks with g_socket_get_fd(). */
1524 flags = fcntl (ret, F_GETFD, 0);
1526 (flags & FD_CLOEXEC) == 0)
1528 flags |= FD_CLOEXEC;
1529 fcntl (ret, F_SETFD, flags);
1534 new_socket = g_socket_new_from_fd (ret, error);
1535 if (new_socket == NULL)
1544 new_socket->priv->protocol = socket->priv->protocol;
1551 * @socket: a #GSocket.
1552 * @address: a #GSocketAddress specifying the remote address.
1553 * @cancellable: a %GCancellable or %NULL
1554 * @error: #GError for error reporting, or %NULL to ignore.
1556 * Connect the socket to the specified remote address.
1558 * For connection oriented socket this generally means we attempt to make
1559 * a connection to the @address. For a connection-less socket it sets
1560 * the default address for g_socket_send() and discards all incoming datagrams
1561 * from other sources.
1563 * Generally connection oriented sockets can only connect once, but
1564 * connection-less sockets can connect multiple times to change the
1567 * If the connect call needs to do network I/O it will block, unless
1568 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1569 * and the user can be notified of the connection finishing by waiting
1570 * for the G_IO_OUT condition. The result of the connection can then be
1571 * checked with g_socket_check_connect_result().
1573 * Returns: %TRUE if connected, %FALSE on error.
1578 g_socket_connect (GSocket *socket,
1579 GSocketAddress *address,
1580 GCancellable *cancellable,
1583 struct sockaddr_storage buffer;
1585 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1587 if (!check_socket (socket, error))
1590 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1595 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1596 g_socket_address_get_native_size (address)) < 0)
1598 int errsv = get_socket_errno ();
1604 if (errsv == EINPROGRESS)
1606 if (errsv == WSAEWOULDBLOCK)
1609 if (socket->priv->blocking)
1611 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
1613 if (g_socket_check_connect_result (socket, error))
1616 g_prefix_error (error, _("Error connecting: "));
1619 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1620 _("Connection in progress"));
1623 g_set_error (error, G_IO_ERROR,
1624 socket_io_error_from_errno (errsv),
1625 _("Error connecting: %s"), socket_strerror (errsv));
1632 win32_unset_event_mask (socket, FD_CONNECT);
1634 socket->priv->connected = TRUE;
1640 * g_socket_check_connect_result:
1641 * @socket: a #GSocket
1642 * @error: #GError for error reporting, or %NULL to ignore.
1644 * Checks and resets the pending connect error for the socket.
1645 * This is used to check for errors when g_socket_connect() is
1646 * used in non-blocking mode.
1648 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1653 g_socket_check_connect_result (GSocket *socket,
1659 if (!check_socket (socket, error))
1662 optlen = sizeof (value);
1663 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1665 int errsv = get_socket_errno ();
1667 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1668 _("Unable to get pending error: %s"), socket_strerror (errsv));
1674 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1675 socket_strerror (value));
1683 * @socket: a #GSocket
1684 * @buffer: a buffer to read data into (which should be at least @size
1686 * @size: the number of bytes you want to read from the socket
1687 * @cancellable: a %GCancellable or %NULL
1688 * @error: #GError for error reporting, or %NULL to ignore.
1690 * Receive data (up to @size bytes) from a socket. This is mainly used by
1691 * connection-oriented sockets; it is identical to g_socket_receive_from()
1692 * with @address set to %NULL.
1694 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1695 * g_socket_receive() will always read either 0 or 1 complete messages from
1696 * the socket. If the received message is too large to fit in @buffer, then
1697 * the data beyond @size bytes will be discarded, without any explicit
1698 * indication that this has occurred.
1700 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1701 * number of bytes, up to @size. If more than @size bytes have been
1702 * received, the additional data will be returned in future calls to
1703 * g_socket_receive().
1705 * If the socket is in blocking mode the call will block until there is
1706 * some data to receive or there is an error. If there is no data available
1707 * and the socket is in non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error
1708 * will be returned. To be notified when data is available, wait for the
1709 * %G_IO_IN condition.
1711 * On error -1 is returned and @error is set accordingly.
1713 * Returns: Number of bytes read, or -1 on error
1718 g_socket_receive (GSocket *socket,
1721 GCancellable *cancellable,
1726 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1728 if (!check_socket (socket, error))
1731 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1736 if (socket->priv->blocking &&
1737 !g_socket_condition_wait (socket,
1738 G_IO_IN, cancellable, error))
1741 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1743 int errsv = get_socket_errno ();
1748 if (socket->priv->blocking)
1750 #ifdef WSAEWOULDBLOCK
1751 if (errsv == WSAEWOULDBLOCK)
1754 if (errsv == EWOULDBLOCK ||
1760 win32_unset_event_mask (socket, FD_READ);
1762 g_set_error (error, G_IO_ERROR,
1763 socket_io_error_from_errno (errsv),
1764 _("Error receiving data: %s"), socket_strerror (errsv));
1768 win32_unset_event_mask (socket, FD_READ);
1777 * g_socket_receive_from:
1778 * @socket: a #GSocket
1779 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1780 * @buffer: a buffer to read data into (which should be at least @size
1782 * @size: the number of bytes you want to read from the socket
1783 * @cancellable: a %GCancellable or %NULL
1784 * @error: #GError for error reporting, or %NULL to ignore.
1786 * Receive data (up to @size bytes) from a socket.
1788 * If @address is non-%NULL then @address will be set equal to the
1789 * source address of the received packet.
1790 * @address is owned by the caller.
1792 * See g_socket_receive() for additional information.
1794 * Returns: Number of bytes read, or -1 on error
1799 g_socket_receive_from (GSocket *socket,
1800 GSocketAddress **address,
1803 GCancellable *cancellable,
1811 return g_socket_receive_message (socket,
1819 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1820 * one, which can be confusing and annoying. So if possible, we want
1821 * to suppress the signal entirely.
1824 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1826 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1831 * @socket: a #GSocket
1832 * @buffer: the buffer containing the data to send.
1833 * @size: the number of bytes to send
1834 * @cancellable: a %GCancellable or %NULL
1835 * @error: #GError for error reporting, or %NULL to ignore.
1837 * Tries to send @size bytes from @buffer on the socket. This is
1838 * mainly used by connection-oriented sockets; it is identical to
1839 * g_socket_send_to() with @address set to %NULL.
1841 * If the socket is in blocking mode the call will block until there is
1842 * space for the data in the socket queue. If there is no space available
1843 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1844 * will be returned. To be notified when space is available, wait for the
1845 * %G_IO_OUT condition. Note though that you may still receive
1846 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1847 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1848 * very common due to the way the underlying APIs work.)
1850 * On error -1 is returned and @error is set accordingly.
1852 * Returns: Number of bytes written (which may be less than @size), or -1
1858 g_socket_send (GSocket *socket,
1859 const gchar *buffer,
1861 GCancellable *cancellable,
1866 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1868 if (!check_socket (socket, error))
1871 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1876 if (socket->priv->blocking &&
1877 !g_socket_condition_wait (socket,
1878 G_IO_OUT, cancellable, error))
1881 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
1883 int errsv = get_socket_errno ();
1888 #ifdef WSAEWOULDBLOCK
1889 if (errsv == WSAEWOULDBLOCK)
1890 win32_unset_event_mask (socket, FD_WRITE);
1893 if (socket->priv->blocking)
1895 #ifdef WSAEWOULDBLOCK
1896 if (errsv == WSAEWOULDBLOCK)
1899 if (errsv == EWOULDBLOCK ||
1905 g_set_error (error, G_IO_ERROR,
1906 socket_io_error_from_errno (errsv),
1907 _("Error sending data: %s"), socket_strerror (errsv));
1918 * @socket: a #GSocket
1919 * @address: a #GSocketAddress, or %NULL
1920 * @buffer: the buffer containing the data to send.
1921 * @size: the number of bytes to send
1922 * @cancellable: a %GCancellable or %NULL
1923 * @error: #GError for error reporting, or %NULL to ignore.
1925 * Tries to send @size bytes from @buffer to @address. If @address is
1926 * %NULL then the message is sent to the default receiver (set by
1927 * g_socket_connect()).
1929 * See g_socket_send() for additional information.
1931 * Returns: Number of bytes written (which may be less than @size), or -1
1937 g_socket_send_to (GSocket *socket,
1938 GSocketAddress *address,
1939 const gchar *buffer,
1941 GCancellable *cancellable,
1949 return g_socket_send_message (socket,
1959 * g_socket_shutdown:
1960 * @socket: a #GSocket
1961 * @shutdown_read: whether to shut down the read side
1962 * @shutdown_write: whether to shut down the write side
1963 * @error: #GError for error reporting, or %NULL to ignore.
1965 * Shut down part of a full-duplex connection.
1967 * If @shutdown_read is %TRUE then the recieving side of the connection
1968 * is shut down, and further reading is disallowed.
1970 * If @shutdown_write is %TRUE then the sending side of the connection
1971 * is shut down, and further writing is disallowed.
1973 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
1975 * One example where this is used is graceful disconnect for TCP connections
1976 * where you close the sending side, then wait for the other side to close
1977 * the connection, thus ensuring that the other side saw all sent data.
1979 * Returns: %TRUE on success, %FALSE on error
1984 g_socket_shutdown (GSocket *socket,
1985 gboolean shutdown_read,
1986 gboolean shutdown_write,
1991 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1993 if (!check_socket (socket, NULL))
1997 if (!shutdown_read && !shutdown_write)
2001 if (shutdown_read && shutdown_write)
2003 else if (shutdown_read)
2008 if (shutdown_read && shutdown_write)
2010 else if (shutdown_read)
2016 if (shutdown (socket->priv->fd, how) != 0)
2018 int errsv = get_socket_errno ();
2019 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2020 _("Unable to create socket: %s"), socket_strerror (errsv));
2024 if (shutdown_read && shutdown_write)
2025 socket->priv->connected = FALSE;
2032 * @socket: a #GSocket
2033 * @error: #GError for error reporting, or %NULL to ignore.
2035 * Closes the socket, shutting down any active connection.
2037 * Closing a socket does not wait for all outstanding I/O operations
2038 * to finish, so the caller should not rely on them to be guaranteed
2039 * to complete even if the close returns with no error.
2041 * Once the socket is closed, all other operations will return
2042 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2045 * Sockets will be automatically closed when the last reference
2046 * is dropped, but you might want to call this function to make sure
2047 * resources are released as early as possible.
2049 * Beware that due to the way that TCP works, it is possible for
2050 * recently-sent data to be lost if either you close a socket while the
2051 * %G_IO_IN condition is set, or else if the remote connection tries to
2052 * send something to you after you close the socket but before it has
2053 * finished reading all of the data you sent. There is no easy generic
2054 * way to avoid this problem; the easiest fix is to design the network
2055 * protocol such that the client will never send data "out of turn".
2056 * Another solution is for the server to half-close the connection by
2057 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2058 * and then wait for the client to notice this and close its side of the
2059 * connection, after which the server can safely call g_socket_close().
2060 * (This is what #GTcpConnection does if you call
2061 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2062 * only works if the client will close its connection after the server
2065 * Returns: %TRUE on success, %FALSE on error
2070 g_socket_close (GSocket *socket,
2075 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2077 if (socket->priv->closed)
2078 return TRUE; /* Multiple close not an error */
2080 if (!check_socket (socket, NULL))
2086 res = closesocket (socket->priv->fd);
2088 res = close (socket->priv->fd);
2092 int errsv = get_socket_errno ();
2097 g_set_error (error, G_IO_ERROR,
2098 socket_io_error_from_errno (errsv),
2099 _("Error closing socket: %s"),
2100 socket_strerror (errsv));
2106 socket->priv->connected = FALSE;
2107 socket->priv->closed = TRUE;
2113 * g_socket_is_closed:
2114 * @socket: a #GSocket
2116 * Checks whether a socket is closed.
2118 * Returns: %TRUE if socket is closed, %FALSE otherwise
2123 g_socket_is_closed (GSocket *socket)
2125 return socket->priv->closed;
2129 /* Broken source, used on errors */
2131 broken_prepare (GSource *source,
2138 broken_check (GSource *source)
2144 broken_dispatch (GSource *source,
2145 GSourceFunc callback,
2151 static GSourceFuncs broken_funcs =
2160 network_events_for_condition (GIOCondition condition)
2164 if (condition & G_IO_IN)
2165 event_mask |= (FD_READ | FD_ACCEPT);
2166 if (condition & G_IO_OUT)
2167 event_mask |= (FD_WRITE | FD_CONNECT);
2168 event_mask |= FD_CLOSE;
2174 ensure_event (GSocket *socket)
2176 if (socket->priv->event == WSA_INVALID_EVENT)
2177 socket->priv->event = WSACreateEvent();
2181 update_select_events (GSocket *socket)
2188 ensure_event (socket);
2191 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2194 event_mask |= network_events_for_condition (*ptr);
2197 if (event_mask != socket->priv->selected_events)
2199 /* If no events selected, disable event so we can unset
2202 if (event_mask == 0)
2205 event = socket->priv->event;
2207 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2208 socket->priv->selected_events = event_mask;
2213 add_condition_watch (GSocket *socket,
2214 GIOCondition *condition)
2216 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2218 socket->priv->requested_conditions =
2219 g_list_prepend (socket->priv->requested_conditions, condition);
2221 update_select_events (socket);
2225 remove_condition_watch (GSocket *socket,
2226 GIOCondition *condition)
2228 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2230 socket->priv->requested_conditions =
2231 g_list_remove (socket->priv->requested_conditions, condition);
2233 update_select_events (socket);
2237 update_condition (GSocket *socket)
2239 WSANETWORKEVENTS events;
2240 GIOCondition condition;
2242 if (WSAEnumNetworkEvents (socket->priv->fd,
2243 socket->priv->event,
2246 socket->priv->current_events |= events.lNetworkEvents;
2247 if (events.lNetworkEvents & FD_WRITE &&
2248 events.iErrorCode[FD_WRITE_BIT] != 0)
2249 socket->priv->current_errors |= FD_WRITE;
2250 if (events.lNetworkEvents & FD_CONNECT &&
2251 events.iErrorCode[FD_CONNECT_BIT] != 0)
2252 socket->priv->current_errors |= FD_CONNECT;
2256 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2257 condition |= G_IO_IN;
2259 if (socket->priv->current_events & FD_CLOSE ||
2260 socket->priv->closed)
2261 condition |= G_IO_HUP;
2263 /* Never report both G_IO_OUT and HUP, these are
2264 mutually exclusive (can't write to a closed socket) */
2265 if ((condition & G_IO_HUP) == 0 &&
2266 socket->priv->current_events & FD_WRITE)
2268 if (socket->priv->current_errors & FD_WRITE)
2269 condition |= G_IO_ERR;
2271 condition |= G_IO_OUT;
2275 if (socket->priv->current_events & FD_CONNECT)
2277 if (socket->priv->current_errors & FD_CONNECT)
2278 condition |= (G_IO_HUP | G_IO_ERR);
2280 condition |= G_IO_OUT;
2292 GIOCondition condition;
2293 GCancellable *cancellable;
2294 GPollFD cancel_pollfd;
2295 GTimeVal timeout_time;
2299 socket_source_prepare (GSource *source,
2302 GSocketSource *socket_source = (GSocketSource *)source;
2304 if (g_cancellable_is_cancelled (socket_source->cancellable))
2307 if (socket_source->timeout_time.tv_sec)
2311 g_source_get_current_time (source, &now);
2312 *timeout = ((socket_source->timeout_time.tv_sec - now.tv_sec) * 1000 +
2313 (socket_source->timeout_time.tv_usec - now.tv_usec) / 1000);
2316 socket_source->socket->priv->timed_out = TRUE;
2317 socket_source->pollfd.revents = socket_source->condition & (G_IO_IN | G_IO_OUT);
2325 socket_source->pollfd.revents = update_condition (socket_source->socket);
2328 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2335 socket_source_check (GSource *source)
2339 return socket_source_prepare (source, &timeout);
2343 socket_source_dispatch (GSource *source,
2344 GSourceFunc callback,
2347 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2348 GSocketSource *socket_source = (GSocketSource *)source;
2350 return (*func) (socket_source->socket,
2351 socket_source->pollfd.revents & socket_source->condition,
2356 socket_source_finalize (GSource *source)
2358 GSocketSource *socket_source = (GSocketSource *)source;
2361 socket = socket_source->socket;
2364 remove_condition_watch (socket, &socket_source->condition);
2367 g_object_unref (socket);
2369 if (socket_source->cancellable)
2371 g_cancellable_release_fd (socket_source->cancellable);
2372 g_object_unref (socket_source->cancellable);
2376 static GSourceFuncs socket_source_funcs =
2378 socket_source_prepare,
2379 socket_source_check,
2380 socket_source_dispatch,
2381 socket_source_finalize
2385 socket_source_new (GSocket *socket,
2386 GIOCondition condition,
2387 GCancellable *cancellable)
2390 GSocketSource *socket_source;
2393 ensure_event (socket);
2395 if (socket->priv->event == WSA_INVALID_EVENT)
2397 g_warning ("Failed to create WSAEvent");
2398 return g_source_new (&broken_funcs, sizeof (GSource));
2402 condition |= G_IO_HUP | G_IO_ERR;
2404 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
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;
3323 #define __G_SOCKET_C__
3324 #include "gioaliasdef.c"