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 "ginitable.h"
49 #include "gasynchelper.h"
53 #include "gnetworkingprivate.h"
60 * @short_description: Low-level socket object
62 * @see_also: #GInitable
64 * A #GSocket is a low-level networking primitive. It is a more or less
65 * direct mapping of the BSD socket API in a portable GObject based API.
66 * It supports both the UNIX socket implementations and winsock2 on Windows.
68 * #GSocket is the platform independent base upon which the higher level
69 * network primitives are based. Applications are not typically meant to
70 * use it directly, but rather through classes like #GSocketClient,
71 * #GSocketService and #GSocketConnection. However there may be cases where
72 * direct use of #GSocket is useful.
74 * #GSocket implements the #GInitable interface, so if it is manually constructed
75 * by e.g. g_object_new() you must call g_initable_init() and check the
76 * results before using the object. This is done automatically in
77 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
80 * Sockets operate in two general modes, blocking or non-blocking. When
81 * in blocking mode all operations block until the requested operation
82 * is finished or there is an error. In non-blocking mode all calls that
83 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
84 * To know when a call would successfully run you can call g_socket_condition_check(),
85 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
86 * attach it to a #GMainContext to get callbacks when I/O is possible.
87 * Note that all sockets are always set to non blocking mode in the system, and
88 * blocking mode is emulated in GSocket.
90 * When working in non-blocking mode applications should always be able to
91 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
92 * function said that I/O was possible. This can easily happen in case
93 * of a race condition in the application, but it can also happen for other
94 * reasons. For instance, on Windows a socket is always seen as writable
95 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
97 * #GSocket<!-- -->s can be either connection oriented or datagram based.
98 * For connection oriented types you must first establish a connection by
99 * either connecting to an address or accepting a connection from another
100 * address. For connectionless socket types the target/source address is
101 * specified or received in each I/O operation.
103 * All socket file descriptors are set to be close-on-exec.
105 * Note that creating a #GSocket causes the signal %SIGPIPE to be
106 * ignored for the remainder of the program. If you are writing a
107 * command-line utility that uses #GSocket, you may need to take into
108 * account the fact that your program will not automatically be killed
109 * if it tries to write to %stdout after it has been closed.
114 static void g_socket_initable_iface_init (GInitableIface *iface);
115 static gboolean g_socket_initable_init (GInitable *initable,
116 GCancellable *cancellable,
119 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
120 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
121 g_socket_initable_iface_init));
137 struct _GSocketPrivate
139 GSocketFamily family;
141 GSocketProtocol protocol;
144 GError *construct_error;
156 GList *requested_conditions; /* list of requested GIOCondition * */
161 get_socket_errno (void)
166 return WSAGetLastError ();
171 socket_io_error_from_errno (int err)
174 return g_io_error_from_errno (err);
179 return G_IO_ERROR_ADDRESS_IN_USE;
181 return G_IO_ERROR_WOULD_BLOCK;
183 return G_IO_ERROR_PERMISSION_DENIED;
184 case WSA_INVALID_HANDLE:
185 case WSA_INVALID_PARAMETER:
188 return G_IO_ERROR_INVALID_ARGUMENT;
189 case WSAEPROTONOSUPPORT:
190 return G_IO_ERROR_NOT_SUPPORTED;
192 return G_IO_ERROR_CANCELLED;
193 case WSAESOCKTNOSUPPORT:
195 case WSAEPFNOSUPPORT:
196 case WSAEAFNOSUPPORT:
197 return G_IO_ERROR_NOT_SUPPORTED;
199 return G_IO_ERROR_FAILED;
205 socket_strerror (int err)
208 return g_strerror (err);
210 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
213 buf = g_static_private_get (&msg_private);
216 buf = g_new (gchar, 128);
217 g_static_private_set (&msg_private, buf, g_free);
220 msg = g_win32_error_message (err);
221 strncpy (buf, msg, 128);
228 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
230 _win32_unset_event_mask (GSocket *socket, int mask)
232 socket->priv->current_events &= ~mask;
233 socket->priv->current_errors &= ~mask;
236 #define win32_unset_event_mask(_socket, _mask)
240 set_fd_nonblocking (int fd)
249 if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
251 g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
255 arg = arg | O_NONBLOCK;
257 if (fcntl (fd, F_SETFL, arg) < 0)
258 g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
262 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
264 int errsv = get_socket_errno ();
265 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
271 check_socket (GSocket *socket,
274 if (!socket->priv->inited)
276 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
277 _("Invalid socket, not initialized"));
281 if (socket->priv->construct_error)
283 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
284 _("Invalid socket, initialization failed due to: %s"),
285 socket->priv->construct_error->message);
289 if (socket->priv->closed)
291 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
292 _("Socket is already closed"));
299 g_socket_details_from_fd (GSocket *socket)
301 struct sockaddr_storage address;
313 fd = socket->priv->fd;
314 optlen = sizeof value;
315 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
317 errsv = get_socket_errno ();
328 /* programmer error */
329 g_error ("creating GSocket from fd %d: %s\n",
330 fd, socket_strerror (errsv));
338 g_assert (optlen == sizeof value);
342 socket->priv->type = G_SOCKET_TYPE_STREAM;
346 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
350 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
354 socket->priv->type = G_SOCKET_TYPE_INVALID;
358 addrlen = sizeof address;
359 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
361 errsv = get_socket_errno ();
365 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
366 sizeof address.ss_family <= addrlen);
367 switch (address.ss_family)
369 case G_SOCKET_FAMILY_IPV4:
370 case G_SOCKET_FAMILY_IPV6:
371 case G_SOCKET_FAMILY_UNIX:
372 socket->priv->family = address.ss_family;
376 socket->priv->family = G_SOCKET_FAMILY_INVALID;
380 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
382 addrlen = sizeof address;
383 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
384 socket->priv->connected = TRUE;
387 optlen = sizeof bool_val;
388 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
389 (void *)&bool_val, &optlen) == 0)
391 g_assert (optlen == sizeof bool_val);
392 socket->priv->keepalive = !!bool_val;
396 /* Can't read, maybe not supported, assume FALSE */
397 socket->priv->keepalive = FALSE;
403 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
404 socket_io_error_from_errno (errsv),
405 _("creating GSocket from fd: %s"),
406 socket_strerror (errsv));
410 g_socket_create_socket (GSocketFamily family,
420 case G_SOCKET_TYPE_STREAM:
421 native_type = SOCK_STREAM;
424 case G_SOCKET_TYPE_DATAGRAM:
425 native_type = SOCK_DGRAM;
428 case G_SOCKET_TYPE_SEQPACKET:
429 native_type = SOCK_SEQPACKET;
433 g_assert_not_reached ();
438 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
439 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
444 native_type |= SOCK_CLOEXEC;
446 fd = socket (family, native_type, protocol);
450 int errsv = get_socket_errno ();
452 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
453 _("Unable to create socket: %s"), socket_strerror (errsv));
460 /* We always want to set close-on-exec to protect users. If you
461 need to so some weird inheritance to exec you can re-enable this
462 using lower level hacks with g_socket_get_fd(). */
463 flags = fcntl (fd, F_GETFD, 0);
465 (flags & FD_CLOEXEC) == 0)
468 fcntl (fd, F_SETFD, flags);
477 g_socket_constructed (GObject *object)
479 GSocket *socket = G_SOCKET (object);
481 if (socket->priv->fd >= 0)
482 /* create socket->priv info from the fd */
483 g_socket_details_from_fd (socket);
486 /* create the fd from socket->priv info */
487 socket->priv->fd = g_socket_create_socket (socket->priv->family,
489 socket->priv->protocol,
490 &socket->priv->construct_error);
492 /* Always use native nonblocking sockets, as
493 windows sets sockets to nonblocking automatically
494 in certain operations. This way we make things work
495 the same on all platforms */
496 if (socket->priv->fd != -1)
497 set_fd_nonblocking (socket->priv->fd);
501 g_socket_get_property (GObject *object,
506 GSocket *socket = G_SOCKET (object);
507 GSocketAddress *address;
512 g_value_set_enum (value, socket->priv->family);
516 g_value_set_enum (value, socket->priv->type);
520 g_value_set_enum (value, socket->priv->protocol);
524 g_value_set_int (value, socket->priv->fd);
528 g_value_set_boolean (value, socket->priv->blocking);
531 case PROP_LISTEN_BACKLOG:
532 g_value_set_int (value, socket->priv->listen_backlog);
536 g_value_set_boolean (value, socket->priv->keepalive);
539 case PROP_LOCAL_ADDRESS:
540 address = g_socket_get_local_address (socket, NULL);
541 g_value_take_object (value, address);
544 case PROP_REMOTE_ADDRESS:
545 address = g_socket_get_remote_address (socket, NULL);
546 g_value_take_object (value, address);
550 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
555 g_socket_set_property (GObject *object,
560 GSocket *socket = G_SOCKET (object);
565 socket->priv->family = g_value_get_enum (value);
569 socket->priv->type = g_value_get_enum (value);
573 socket->priv->protocol = g_value_get_enum (value);
577 socket->priv->fd = g_value_get_int (value);
581 g_socket_set_blocking (socket, g_value_get_boolean (value));
584 case PROP_LISTEN_BACKLOG:
585 g_socket_set_listen_backlog (socket, g_value_get_int (value));
589 g_socket_set_keepalive (socket, g_value_get_boolean (value));
593 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
598 g_socket_finalize (GObject *object)
600 GSocket *socket = G_SOCKET (object);
602 g_clear_error (&socket->priv->construct_error);
604 if (socket->priv->fd != -1 &&
605 !socket->priv->closed)
606 g_socket_close (socket, NULL);
609 g_assert (socket->priv->requested_conditions == NULL);
612 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
613 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
617 g_socket_class_init (GSocketClass *klass)
619 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
622 /* Make sure winsock has been initialized */
623 type = g_inet_address_get_type ();
626 /* There is no portable, thread-safe way to avoid having the process
627 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
628 * forced to simply ignore the signal process-wide.
630 signal (SIGPIPE, SIG_IGN);
633 g_type_class_add_private (klass, sizeof (GSocketPrivate));
635 gobject_class->finalize = g_socket_finalize;
636 gobject_class->constructed = g_socket_constructed;
637 gobject_class->set_property = g_socket_set_property;
638 gobject_class->get_property = g_socket_get_property;
640 g_object_class_install_property (gobject_class, PROP_FAMILY,
641 g_param_spec_enum ("family",
643 P_("The sockets address family"),
644 G_TYPE_SOCKET_FAMILY,
645 G_SOCKET_FAMILY_INVALID,
646 G_PARAM_CONSTRUCT_ONLY |
648 G_PARAM_STATIC_STRINGS));
650 g_object_class_install_property (gobject_class, PROP_TYPE,
651 g_param_spec_enum ("type",
653 P_("The sockets type"),
655 G_SOCKET_TYPE_STREAM,
656 G_PARAM_CONSTRUCT_ONLY |
658 G_PARAM_STATIC_STRINGS));
660 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
661 g_param_spec_enum ("protocol",
662 P_("Socket protocol"),
663 P_("The id of the protocol to use, or -1 for unknown"),
664 G_TYPE_SOCKET_PROTOCOL,
665 G_SOCKET_PROTOCOL_UNKNOWN,
666 G_PARAM_CONSTRUCT_ONLY |
668 G_PARAM_STATIC_STRINGS));
670 g_object_class_install_property (gobject_class, PROP_FD,
671 g_param_spec_int ("fd",
672 P_("File descriptor"),
673 P_("The sockets file descriptor"),
677 G_PARAM_CONSTRUCT_ONLY |
679 G_PARAM_STATIC_STRINGS));
681 g_object_class_install_property (gobject_class, PROP_BLOCKING,
682 g_param_spec_boolean ("blocking",
684 P_("Whether or not I/O on this socket is blocking"),
687 G_PARAM_STATIC_STRINGS));
689 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
690 g_param_spec_int ("listen-backlog",
691 P_("Listen backlog"),
692 P_("Outstanding connections in the listen queue"),
697 G_PARAM_STATIC_STRINGS));
699 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
700 g_param_spec_boolean ("keepalive",
701 P_("Keep connection alive"),
702 P_("Keep connection alive by sending periodic pings"),
705 G_PARAM_STATIC_STRINGS));
707 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
708 g_param_spec_object ("local-address",
710 P_("The local address the socket is bound to"),
711 G_TYPE_SOCKET_ADDRESS,
713 G_PARAM_STATIC_STRINGS));
715 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
716 g_param_spec_object ("remote-address",
717 P_("Remote address"),
718 P_("The remote address the socket is connected to"),
719 G_TYPE_SOCKET_ADDRESS,
721 G_PARAM_STATIC_STRINGS));
725 g_socket_initable_iface_init (GInitableIface *iface)
727 iface->init = g_socket_initable_init;
731 g_socket_init (GSocket *socket)
733 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
735 socket->priv->fd = -1;
736 socket->priv->blocking = TRUE;
737 socket->priv->listen_backlog = 10;
738 socket->priv->construct_error = NULL;
740 socket->priv->event = WSA_INVALID_EVENT;
745 g_socket_initable_init (GInitable *initable,
746 GCancellable *cancellable,
751 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
753 socket = G_SOCKET (initable);
755 if (cancellable != NULL)
757 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
758 _("Cancellable initialization not supported"));
762 socket->priv->inited = TRUE;
764 if (socket->priv->construct_error)
767 *error = g_error_copy (socket->priv->construct_error);
777 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
778 * @type: the socket type to use.
779 * @protocol: the id of the protocol to use, or 0 for default.
780 * @error: #GError for error reporting, or %NULL to ignore.
782 * Creates a new #GSocket with the defined family, type and protocol.
783 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
784 * for the family and type is used.
786 * The @protocol is a family and type specific int that specifies what
787 * kind of protocol to use. #GSocketProtocol lists several common ones.
788 * Many families only support one protocol, and use 0 for this, others
789 * support several and using 0 means to use the default protocol for
790 * the family and type.
792 * The protocol id is passed directly to the operating
793 * system, so you can use protocols not listed in #GSocketProtocol if you
794 * know the protocol number used for it.
796 * Returns: a #GSocket or %NULL on error.
797 * Free the returned object with g_object_unref().
802 g_socket_new (GSocketFamily family,
804 GSocketProtocol protocol,
807 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
811 "protocol", protocol,
816 * g_socket_new_from_fd:
817 * @fd: a native socket file descriptor.
818 * @error: #GError for error reporting, or %NULL to ignore.
820 * Creates a new #GSocket from a native file descriptor
821 * or winsock SOCKET handle.
823 * This reads all the settings from the file descriptor so that
824 * all properties should work. Note that the file descriptor
825 * will be set to non-blocking mode, independent on the blocking
826 * mode of the #GSocket.
828 * Returns: a #GSocket or %NULL on error.
829 * Free the returned object with g_object_unref().
834 g_socket_new_from_fd (gint fd,
837 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
844 * g_socket_set_blocking:
845 * @socket: a #GSocket.
846 * @blocking: Whether to use blocking I/O or not.
848 * Sets the blocking mode of the socket. In blocking mode
849 * all operations block until they succeed or there is an error. In
850 * non-blocking mode all functions return results immediately or
851 * with a %G_IO_ERROR_WOULD_BLOCK error.
853 * All sockets are created in blocking mode. However, note that the
854 * platform level socket is always non-blocking, and blocking mode
855 * is a GSocket level feature.
860 g_socket_set_blocking (GSocket *socket,
863 g_return_if_fail (G_IS_SOCKET (socket));
865 blocking = !!blocking;
867 if (socket->priv->blocking == blocking)
870 socket->priv->blocking = blocking;
871 g_object_notify (G_OBJECT (socket), "blocking");
875 * g_socket_get_blocking:
876 * @socket: a #GSocket.
878 * Gets the blocking mode of the socket. For details on blocking I/O,
879 * see g_socket_set_blocking().
881 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
886 g_socket_get_blocking (GSocket *socket)
888 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
890 return socket->priv->blocking;
894 * g_socket_set_keepalive:
895 * @socket: a #GSocket.
896 * @keepalive: Value for the keepalive flag
898 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
899 * this flag is set on a socket, the system will attempt to verify that the
900 * remote socket endpoint is still present if a sufficiently long period of
901 * time passes with no data being exchanged. If the system is unable to
902 * verify the presence of the remote endpoint, it will automatically close
905 * This option is only functional on certain kinds of sockets. (Notably,
906 * %G_SOCKET_PROTOCOL_TCP sockets.)
908 * The exact time between pings is system- and protocol-dependent, but will
909 * normally be at least two hours. Most commonly, you would set this flag
910 * on a server socket if you want to allow clients to remain idle for long
911 * periods of time, but also want to ensure that connections are eventually
912 * garbage-collected if clients crash or become unreachable.
917 g_socket_set_keepalive (GSocket *socket,
922 g_return_if_fail (G_IS_SOCKET (socket));
924 keepalive = !!keepalive;
925 if (socket->priv->keepalive == keepalive)
928 value = (gint) keepalive;
929 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
930 (gpointer) &value, sizeof (value)) < 0)
932 int errsv = get_socket_errno ();
933 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
937 socket->priv->keepalive = keepalive;
938 g_object_notify (G_OBJECT (socket), "keepalive");
942 * g_socket_get_keepalive:
943 * @socket: a #GSocket.
945 * Gets the keepalive mode of the socket. For details on this,
946 * see g_socket_set_keepalive().
948 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
953 g_socket_get_keepalive (GSocket *socket)
955 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
957 return socket->priv->keepalive;
961 * g_socket_get_listen_backlog:
962 * @socket: a #GSocket.
964 * Gets the listen backlog setting of the socket. For details on this,
965 * see g_socket_set_listen_backlog().
967 * Returns: the maximum number of pending connections.
972 g_socket_get_listen_backlog (GSocket *socket)
974 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
976 return socket->priv->listen_backlog;
980 * g_socket_set_listen_backlog:
981 * @socket: a #GSocket.
982 * @backlog: the maximum number of pending connections.
984 * Sets the maximum number of outstanding connections allowed
985 * when listening on this socket. If more clients than this are
986 * connecting to the socket and the application is not handling them
987 * on time then the new connections will be refused.
989 * Note that this must be called before g_socket_listen() and has no
990 * effect if called after that.
995 g_socket_set_listen_backlog (GSocket *socket,
998 g_return_if_fail (G_IS_SOCKET (socket));
999 g_return_if_fail (!socket->priv->listening);
1001 if (backlog != socket->priv->listen_backlog)
1003 socket->priv->listen_backlog = backlog;
1004 g_object_notify (G_OBJECT (socket), "listen-backlog");
1009 * g_socket_get_family:
1010 * @socket: a #GSocket.
1012 * Gets the socket family of the socket.
1014 * Returns: a #GSocketFamily
1019 g_socket_get_family (GSocket *socket)
1021 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1023 return socket->priv->family;
1027 * g_socket_get_socket_type:
1028 * @socket: a #GSocket.
1030 * Gets the socket type of the socket.
1032 * Returns: a #GSocketType
1037 g_socket_get_socket_type (GSocket *socket)
1039 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1041 return socket->priv->type;
1045 * g_socket_get_protocol:
1046 * @socket: a #GSocket.
1048 * Gets the socket protocol id the socket was created with.
1049 * In case the protocol is unknown, -1 is returned.
1051 * Returns: a protocol id, or -1 if unknown
1056 g_socket_get_protocol (GSocket *socket)
1058 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1060 return socket->priv->protocol;
1065 * @socket: a #GSocket.
1067 * Returns the underlying OS socket object. On unix this
1068 * is a socket file descriptor, and on windows this is
1069 * a Winsock2 SOCKET handle. This may be useful for
1070 * doing platform specific or otherwise unusual operations
1073 * Returns: the file descriptor of the socket.
1078 g_socket_get_fd (GSocket *socket)
1080 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1082 return socket->priv->fd;
1086 * g_socket_get_local_address:
1087 * @socket: a #GSocket.
1088 * @error: #GError for error reporting, or %NULL to ignore.
1090 * Try to get the local address of a bound socket. This is only
1091 * useful if the socket has been bound to a local address,
1092 * either explicitly or implicitly when connecting.
1094 * Returns: a #GSocketAddress or %NULL on error.
1095 * Free the returned object with g_object_unref().
1100 g_socket_get_local_address (GSocket *socket,
1103 struct sockaddr_storage buffer;
1104 guint32 len = sizeof (buffer);
1106 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1108 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1110 int errsv = get_socket_errno ();
1111 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1112 _("could not get local address: %s"), socket_strerror (errsv));
1116 return g_socket_address_new_from_native (&buffer, len);
1120 * g_socket_get_remote_address:
1121 * @socket: a #GSocket.
1122 * @error: #GError for error reporting, or %NULL to ignore.
1124 * Try to get the remove address of a connected socket. This is only
1125 * useful for connection oriented sockets that have been connected.
1127 * Returns: a #GSocketAddress or %NULL on error.
1128 * Free the returned object with g_object_unref().
1133 g_socket_get_remote_address (GSocket *socket,
1136 struct sockaddr_storage buffer;
1137 guint32 len = sizeof (buffer);
1139 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1141 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1143 int errsv = get_socket_errno ();
1144 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1145 _("could not get remote address: %s"), socket_strerror (errsv));
1149 return g_socket_address_new_from_native (&buffer, len);
1153 * g_socket_is_connected:
1154 * @socket: a #GSocket.
1156 * Check whether the socket is connected. This is only useful for
1157 * connection-oriented sockets.
1159 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1164 g_socket_is_connected (GSocket *socket)
1166 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1168 return socket->priv->connected;
1173 * @socket: a #GSocket.
1174 * @error: #GError for error reporting, or %NULL to ignore.
1176 * Marks the socket as a server socket, i.e. a socket that is used
1177 * to accept incoming requests using g_socket_accept().
1179 * Before calling this the socket must be bound to a local address using
1182 * To set the maximum amount of outstanding clients, use
1183 * g_socket_set_listen_backlog().
1185 * Returns: %TRUE on success, %FALSE on error.
1190 g_socket_listen (GSocket *socket,
1193 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1195 if (!check_socket (socket, error))
1198 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1200 int errsv = get_socket_errno ();
1202 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1203 _("could not listen: %s"), socket_strerror (errsv));
1207 socket->priv->listening = TRUE;
1214 * @socket: a #GSocket.
1215 * @address: a #GSocketAddress specifying the local address.
1216 * @allow_reuse: whether to allow reusing this address
1217 * @error: #GError for error reporting, or %NULL to ignore.
1219 * When a socket is created it is attached to an address family, but it
1220 * doesn't have an address in this family. g_socket_bind() assigns the
1221 * address (sometimes called name) of the socket.
1223 * It is generally required to bind to a local address before you can
1224 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1225 * In certain situations, you may also want to bind a socket that will be
1226 * used to initiate connections, though this is not normally required.
1228 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1229 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1230 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1231 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1232 * that address was previously used by another socket that has not yet been
1233 * fully cleaned-up by the kernel. Failing to set this flag on a server
1234 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1235 * the server program is stopped and then immediately restarted.)
1237 * Returns: %TRUE on success, %FALSE on error.
1242 g_socket_bind (GSocket *socket,
1243 GSocketAddress *address,
1244 gboolean reuse_address,
1247 struct sockaddr_storage addr;
1249 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1251 if (!check_socket (socket, error))
1254 /* SO_REUSEADDR on windows means something else and is not what we want.
1255 It always allows the unix variant of SO_REUSEADDR anyway */
1260 value = (int) !!reuse_address;
1261 /* Ignore errors here, the only likely error is "not supported", and
1262 this is a "best effort" thing mainly */
1263 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1264 (gpointer) &value, sizeof (value));
1268 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1271 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1272 g_socket_address_get_native_size (address)) < 0)
1274 int errsv = get_socket_errno ();
1276 G_IO_ERROR, socket_io_error_from_errno (errsv),
1277 _("Error binding to address: %s"), socket_strerror (errsv));
1285 * g_socket_speaks_ipv4:
1286 * @socket: a #GSocket
1288 * Checks if a socket is capable of speaking IPv4.
1290 * IPv4 sockets are capable of speaking IPv4. On some operating systems
1291 * and under some combinations of circumstances IPv6 sockets are also
1292 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
1295 * No other types of sockets are currently considered as being capable
1298 * Returns: %TRUE if this socket can be used with IPv4.
1303 g_socket_speaks_ipv4 (GSocket *socket)
1305 switch (socket->priv->family)
1307 case G_SOCKET_FAMILY_IPV4:
1310 case G_SOCKET_FAMILY_IPV6:
1311 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1313 guint sizeof_int = sizeof (int);
1316 if (getsockopt (socket->priv->fd,
1317 IPPROTO_IPV6, IPV6_V6ONLY,
1318 &v6_only, &sizeof_int) != 0)
1334 * @socket: a #GSocket.
1335 * @cancellable: a %GCancellable or %NULL
1336 * @error: #GError for error reporting, or %NULL to ignore.
1338 * Accept incoming connections on a connection-based socket. This removes
1339 * the first outstanding connection request from the listening socket and
1340 * creates a #GSocket object for it.
1342 * The @socket must be bound to a local address with g_socket_bind() and
1343 * must be listening for incoming connections (g_socket_listen()).
1345 * If there are no outstanding connections then the operation will block
1346 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1347 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1349 * Returns: a new #GSocket, or %NULL on error.
1350 * Free the returned object with g_object_unref().
1355 g_socket_accept (GSocket *socket,
1356 GCancellable *cancellable,
1359 GSocket *new_socket;
1362 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1364 if (!check_socket (socket, error))
1369 if (socket->priv->blocking &&
1370 !g_socket_condition_wait (socket,
1371 G_IO_IN, cancellable, error))
1374 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1376 int errsv = get_socket_errno ();
1378 win32_unset_event_mask (socket, FD_ACCEPT);
1383 if (socket->priv->blocking)
1385 #ifdef WSAEWOULDBLOCK
1386 if (errsv == WSAEWOULDBLOCK)
1389 if (errsv == EWOULDBLOCK ||
1395 g_set_error (error, G_IO_ERROR,
1396 socket_io_error_from_errno (errsv),
1397 _("Error accepting connection: %s"), socket_strerror (errsv));
1403 win32_unset_event_mask (socket, FD_ACCEPT);
1407 /* The socket inherits the accepting sockets event mask and even object,
1408 we need to remove that */
1409 WSAEventSelect (ret, NULL, 0);
1415 /* We always want to set close-on-exec to protect users. If you
1416 need to so some weird inheritance to exec you can re-enable this
1417 using lower level hacks with g_socket_get_fd(). */
1418 flags = fcntl (ret, F_GETFD, 0);
1420 (flags & FD_CLOEXEC) == 0)
1422 flags |= FD_CLOEXEC;
1423 fcntl (ret, F_SETFD, flags);
1428 new_socket = g_socket_new_from_fd (ret, error);
1429 if (new_socket == NULL)
1438 new_socket->priv->protocol = socket->priv->protocol;
1445 * @socket: a #GSocket.
1446 * @address: a #GSocketAddress specifying the remote address.
1447 * @cancellable: a %GCancellable or %NULL
1448 * @error: #GError for error reporting, or %NULL to ignore.
1450 * Connect the socket to the specified remote address.
1452 * For connection oriented socket this generally means we attempt to make
1453 * a connection to the @address. For a connection-less socket it sets
1454 * the default address for g_socket_send() and discards all incoming datagrams
1455 * from other sources.
1457 * Generally connection oriented sockets can only connect once, but
1458 * connection-less sockets can connect multiple times to change the
1461 * If the connect call needs to do network I/O it will block, unless
1462 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1463 * and the user can be notified of the connection finishing by waiting
1464 * for the G_IO_OUT condition. The result of the connection can then be
1465 * checked with g_socket_check_connect_result().
1467 * Returns: %TRUE if connected, %FALSE on error.
1472 g_socket_connect (GSocket *socket,
1473 GSocketAddress *address,
1474 GCancellable *cancellable,
1477 struct sockaddr_storage buffer;
1479 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1481 if (!check_socket (socket, error))
1484 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1489 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1490 g_socket_address_get_native_size (address)) < 0)
1492 int errsv = get_socket_errno ();
1498 if (errsv == EINPROGRESS)
1500 if (errsv == WSAEWOULDBLOCK)
1503 if (socket->priv->blocking)
1505 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
1507 if (g_socket_check_connect_result (socket, error))
1510 g_prefix_error (error, _("Error connecting: "));
1513 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1514 _("Connection in progress"));
1517 g_set_error (error, G_IO_ERROR,
1518 socket_io_error_from_errno (errsv),
1519 _("Error connecting: %s"), socket_strerror (errsv));
1526 win32_unset_event_mask (socket, FD_CONNECT);
1528 socket->priv->connected = TRUE;
1534 * g_socket_check_connect_result:
1535 * @socket: a #GSocket
1536 * @error: #GError for error reporting, or %NULL to ignore.
1538 * Checks and resets the pending connect error for the socket.
1539 * This is used to check for errors when g_socket_connect() is
1540 * used in non-blocking mode.
1542 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1547 g_socket_check_connect_result (GSocket *socket,
1553 optlen = sizeof (value);
1554 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1556 int errsv = get_socket_errno ();
1558 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1559 _("Unable to get pending error: %s"), socket_strerror (errsv));
1565 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1566 socket_strerror (value));
1574 * @socket: a #GSocket
1575 * @buffer: a buffer to read data into (which should be at least @size
1577 * @size: the number of bytes you want to read from the socket
1578 * @cancellable: a %GCancellable or %NULL
1579 * @error: #GError for error reporting, or %NULL to ignore.
1581 * Receive data (up to @size bytes) from a socket. This is mainly used by
1582 * connection-oriented sockets; it is identical to g_socket_receive_from()
1583 * with @address set to %NULL.
1585 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1586 * g_socket_receive() will always read either 0 or 1 complete messages from
1587 * the socket. If the received message is too large to fit in @buffer, then
1588 * the data beyond @size bytes will be discarded, without any explicit
1589 * indication that this has occurred.
1591 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1592 * number of bytes, up to @size. If more than @size bytes have been
1593 * received, the additional data will be returned in future calls to
1594 * g_socket_receive().
1596 * If the socket is in blocking mode the call will block until there is
1597 * some data to receive or there is an error. If there is no data available
1598 * and the socket is in non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error
1599 * will be returned. To be notified when data is available, wait for the
1600 * %G_IO_IN condition.
1602 * On error -1 is returned and @error is set accordingly.
1604 * Returns: Number of bytes read, or -1 on error
1609 g_socket_receive (GSocket *socket,
1612 GCancellable *cancellable,
1617 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1619 if (!check_socket (socket, error))
1622 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1627 if (socket->priv->blocking &&
1628 !g_socket_condition_wait (socket,
1629 G_IO_IN, cancellable, error))
1632 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1634 int errsv = get_socket_errno ();
1639 if (socket->priv->blocking)
1641 #ifdef WSAEWOULDBLOCK
1642 if (errsv == WSAEWOULDBLOCK)
1645 if (errsv == EWOULDBLOCK ||
1651 win32_unset_event_mask (socket, FD_READ);
1653 g_set_error (error, G_IO_ERROR,
1654 socket_io_error_from_errno (errsv),
1655 _("Error receiving data: %s"), socket_strerror (errsv));
1659 win32_unset_event_mask (socket, FD_READ);
1668 * g_socket_receive_from:
1669 * @socket: a #GSocket
1670 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1671 * @buffer: a buffer to read data into (which should be at least @size
1673 * @size: the number of bytes you want to read from the socket
1674 * @cancellable: a %GCancellable or %NULL
1675 * @error: #GError for error reporting, or %NULL to ignore.
1677 * Receive data (up to @size bytes) from a socket.
1679 * If @address is non-%NULL then @address will be set equal to the
1680 * source address of the received packet.
1681 * @address is owned by the caller.
1683 * See g_socket_receive() for additional information.
1685 * Returns: Number of bytes read, or -1 on error
1690 g_socket_receive_from (GSocket *socket,
1691 GSocketAddress **address,
1694 GCancellable *cancellable,
1702 return g_socket_receive_message (socket,
1712 * @socket: a #GSocket
1713 * @buffer: the buffer containing the data to send.
1714 * @size: the number of bytes to send
1715 * @cancellable: a %GCancellable or %NULL
1716 * @error: #GError for error reporting, or %NULL to ignore.
1718 * Tries to send @size bytes from @buffer on the socket. This is
1719 * mainly used by connection-oriented sockets; it is identical to
1720 * g_socket_send_to() with @address set to %NULL.
1722 * If the socket is in blocking mode the call will block until there is
1723 * space for the data in the socket queue. If there is no space available
1724 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1725 * will be returned. To be notified when space is available, wait for the
1726 * %G_IO_OUT condition. Note though that you may still receive
1727 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1728 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1729 * very common due to the way the underlying APIs work.)
1731 * On error -1 is returned and @error is set accordingly.
1733 * Returns: Number of bytes written (which may be less than @size), or -1
1739 g_socket_send (GSocket *socket,
1740 const gchar *buffer,
1742 GCancellable *cancellable,
1747 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1749 if (!check_socket (socket, error))
1752 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1757 if (socket->priv->blocking &&
1758 !g_socket_condition_wait (socket,
1759 G_IO_OUT, cancellable, error))
1762 if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
1764 int errsv = get_socket_errno ();
1769 #ifdef WSAEWOULDBLOCK
1770 if (errsv == WSAEWOULDBLOCK)
1771 win32_unset_event_mask (socket, FD_WRITE);
1774 if (socket->priv->blocking)
1776 #ifdef WSAEWOULDBLOCK
1777 if (errsv == WSAEWOULDBLOCK)
1780 if (errsv == EWOULDBLOCK ||
1786 g_set_error (error, G_IO_ERROR,
1787 socket_io_error_from_errno (errsv),
1788 _("Error sending data: %s"), socket_strerror (errsv));
1799 * @socket: a #GSocket
1800 * @address: a #GSocketAddress, or %NULL
1801 * @buffer: the buffer containing the data to send.
1802 * @size: the number of bytes to send
1803 * @cancellable: a %GCancellable or %NULL
1804 * @error: #GError for error reporting, or %NULL to ignore.
1806 * Tries to send @size bytes from @buffer to @address. If @address is
1807 * %NULL then the message is sent to the default receiver (set by
1808 * g_socket_connect()).
1810 * See g_socket_send() for additional information.
1812 * Returns: Number of bytes written (which may be less than @size), or -1
1818 g_socket_send_to (GSocket *socket,
1819 GSocketAddress *address,
1820 const gchar *buffer,
1822 GCancellable *cancellable,
1830 return g_socket_send_message (socket,
1840 * g_socket_shutdown:
1841 * @socket: a #GSocket
1842 * @shutdown_read: whether to shut down the read side
1843 * @shutdown_write: whether to shut down the write side
1844 * @error: #GError for error reporting, or %NULL to ignore.
1846 * Shut down part of a full-duplex connection.
1848 * If @shutdown_read is %TRUE then the recieving side of the connection
1849 * is shut down, and further reading is disallowed.
1851 * If @shutdown_write is %TRUE then the sending side of the connection
1852 * is shut down, and further writing is disallowed.
1854 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
1856 * One example where this is used is graceful disconnect for TCP connections
1857 * where you close the sending side, then wait for the other side to close
1858 * the connection, thus ensuring that the other side saw all sent data.
1860 * Returns: %TRUE on success, %FALSE on error
1865 g_socket_shutdown (GSocket *socket,
1866 gboolean shutdown_read,
1867 gboolean shutdown_write,
1872 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1874 if (!check_socket (socket, NULL))
1878 if (!shutdown_read && !shutdown_write)
1882 if (shutdown_read && shutdown_write)
1884 else if (shutdown_read)
1889 if (shutdown_read && shutdown_write)
1891 else if (shutdown_read)
1897 if (shutdown (socket->priv->fd, how) != 0)
1899 int errsv = get_socket_errno ();
1900 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1901 _("Unable to create socket: %s"), socket_strerror (errsv));
1905 if (shutdown_read && shutdown_write)
1906 socket->priv->connected = FALSE;
1913 * @socket: a #GSocket
1914 * @error: #GError for error reporting, or %NULL to ignore.
1916 * Closes the socket, shutting down any active connection.
1918 * Closing a socket does not wait for all outstanding I/O operations
1919 * to finish, so the caller should not rely on them to be guaranteed
1920 * to complete even if the close returns with no error.
1922 * Once the socket is closed, all other operations will return
1923 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
1926 * Sockets will be automatically closed when the last reference
1927 * is dropped, but you might want to call this function to make sure
1928 * resources are released as early as possible.
1930 * Beware that due to the way that TCP works, it is possible for
1931 * recently-sent data to be lost if either you close a socket while the
1932 * %G_IO_IN condition is set, or else if the remote connection tries to
1933 * send something to you after you close the socket but before it has
1934 * finished reading all of the data you sent. There is no easy generic
1935 * way to avoid this problem; the easiest fix is to design the network
1936 * protocol such that the client will never send data "out of turn".
1937 * Another solution is for the server to half-close the connection by
1938 * calling g_socket_shutdown() with only the @shutdown_write flag set,
1939 * and then wait for the client to notice this and close its side of the
1940 * connection, after which the server can safely call g_socket_close().
1941 * (This is what #GTcpConnection does if you call
1942 * g_tcp_connection_set_graceful_disconnect(). But of course, this
1943 * only works if the client will close its connection after the server
1946 * Returns: %TRUE on success, %FALSE on error
1951 g_socket_close (GSocket *socket,
1956 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1958 if (socket->priv->closed)
1959 return TRUE; /* Multiple close not an error */
1961 if (!check_socket (socket, NULL))
1967 res = closesocket (socket->priv->fd);
1969 res = close (socket->priv->fd);
1973 int errsv = get_socket_errno ();
1978 g_set_error (error, G_IO_ERROR,
1979 socket_io_error_from_errno (errsv),
1980 _("Error closing socket: %s"),
1981 socket_strerror (errsv));
1988 if (socket->priv->event != WSA_INVALID_EVENT)
1990 WSACloseEvent (socket->priv->event);
1991 socket->priv->event = WSA_INVALID_EVENT;
1995 socket->priv->connected = FALSE;
1996 socket->priv->closed = TRUE;
2002 * g_socket_is_closed:
2003 * @socket: a #GSocket
2005 * Checks whether a socket is closed.
2007 * Returns: %TRUE if socket is closed, %FALSE otherwise
2012 g_socket_is_closed (GSocket *socket)
2014 return socket->priv->closed;
2018 /* Broken source, used on errors */
2020 broken_prepare (GSource *source,
2027 broken_check (GSource *source)
2033 broken_dispatch (GSource *source,
2034 GSourceFunc callback,
2040 static GSourceFuncs broken_funcs =
2049 network_events_for_condition (GIOCondition condition)
2053 if (condition & G_IO_IN)
2054 event_mask |= (FD_READ | FD_ACCEPT);
2055 if (condition & G_IO_OUT)
2056 event_mask |= (FD_WRITE | FD_CONNECT);
2057 event_mask |= FD_CLOSE;
2063 ensure_event (GSocket *socket)
2065 if (socket->priv->event == WSA_INVALID_EVENT)
2066 socket->priv->event = WSACreateEvent();
2070 update_select_events (GSocket *socket)
2077 ensure_event (socket);
2080 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2083 event_mask |= network_events_for_condition (*ptr);
2086 if (event_mask != socket->priv->selected_events)
2088 /* If no events selected, disable event so we can unset
2091 if (event_mask == 0)
2094 event = socket->priv->event;
2096 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2097 socket->priv->selected_events = event_mask;
2102 add_condition_watch (GSocket *socket,
2103 GIOCondition *condition)
2105 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2107 socket->priv->requested_conditions =
2108 g_list_prepend (socket->priv->requested_conditions, condition);
2110 update_select_events (socket);
2114 remove_condition_watch (GSocket *socket,
2115 GIOCondition *condition)
2117 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2119 socket->priv->requested_conditions =
2120 g_list_remove (socket->priv->requested_conditions, condition);
2122 update_select_events (socket);
2126 update_condition (GSocket *socket)
2128 WSANETWORKEVENTS events;
2129 GIOCondition condition;
2131 if (WSAEnumNetworkEvents (socket->priv->fd,
2132 socket->priv->event,
2135 socket->priv->current_events |= events.lNetworkEvents;
2136 if (events.lNetworkEvents & FD_WRITE &&
2137 events.iErrorCode[FD_WRITE_BIT] != 0)
2138 socket->priv->current_errors |= FD_WRITE;
2139 if (events.lNetworkEvents & FD_CONNECT &&
2140 events.iErrorCode[FD_CONNECT_BIT] != 0)
2141 socket->priv->current_errors |= FD_CONNECT;
2145 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2146 condition |= G_IO_IN;
2148 if (socket->priv->current_events & FD_CLOSE ||
2149 socket->priv->closed)
2150 condition |= G_IO_HUP;
2152 /* Never report both G_IO_OUT and HUP, these are
2153 mutually exclusive (can't write to a closed socket) */
2154 if ((condition & G_IO_HUP) == 0 &&
2155 socket->priv->current_events & FD_WRITE)
2157 if (socket->priv->current_errors & FD_WRITE)
2158 condition |= G_IO_ERR;
2160 condition |= G_IO_OUT;
2164 if (socket->priv->current_events & FD_CONNECT)
2166 if (socket->priv->current_errors & FD_CONNECT)
2167 condition |= (G_IO_HUP | G_IO_ERR);
2169 condition |= G_IO_OUT;
2180 GIOCondition condition;
2181 GCancellable *cancellable;
2182 GPollFD cancel_pollfd;
2183 GIOCondition result_condition;
2187 winsock_prepare (GSource *source,
2190 GWinsockSource *winsock_source = (GWinsockSource *)source;
2191 GIOCondition current_condition;
2193 current_condition = update_condition (winsock_source->socket);
2195 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2197 winsock_source->result_condition = current_condition;
2201 if ((winsock_source->condition & current_condition) != 0)
2203 winsock_source->result_condition = current_condition;
2211 winsock_check (GSource *source)
2213 GWinsockSource *winsock_source = (GWinsockSource *)source;
2214 GIOCondition current_condition;
2216 current_condition = update_condition (winsock_source->socket);
2218 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2220 winsock_source->result_condition = current_condition;
2224 if ((winsock_source->condition & current_condition) != 0)
2226 winsock_source->result_condition = current_condition;
2234 winsock_dispatch (GSource *source,
2235 GSourceFunc callback,
2238 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2239 GWinsockSource *winsock_source = (GWinsockSource *)source;
2241 return (*func) (winsock_source->socket,
2242 winsock_source->result_condition & winsock_source->condition,
2247 winsock_finalize (GSource *source)
2249 GWinsockSource *winsock_source = (GWinsockSource *)source;
2252 socket = winsock_source->socket;
2254 remove_condition_watch (socket, &winsock_source->condition);
2255 g_object_unref (socket);
2257 if (winsock_source->cancellable)
2258 g_object_unref (winsock_source->cancellable);
2261 static GSourceFuncs winsock_funcs =
2270 winsock_source_new (GSocket *socket,
2271 GIOCondition condition,
2272 GCancellable *cancellable)
2275 GWinsockSource *winsock_source;
2277 ensure_event (socket);
2279 if (socket->priv->event == WSA_INVALID_EVENT)
2281 g_warning ("Failed to create WSAEvent");
2282 return g_source_new (&broken_funcs, sizeof (GSource));
2285 condition |= G_IO_HUP | G_IO_ERR;
2287 source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2288 winsock_source = (GWinsockSource *)source;
2290 winsock_source->socket = g_object_ref (socket);
2291 winsock_source->condition = condition;
2292 add_condition_watch (socket, &winsock_source->condition);
2294 if (g_cancellable_make_pollfd (cancellable,
2295 &winsock_source->cancel_pollfd))
2297 winsock_source->cancellable = g_object_ref (cancellable);
2298 g_source_add_poll (source, &winsock_source->cancel_pollfd);
2301 winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2302 winsock_source->pollfd.events = condition;
2303 g_source_add_poll (source, &winsock_source->pollfd);
2310 * g_socket_create_source:
2311 * @socket: a #GSocket
2312 * @condition: a #GIOCondition mask to monitor
2313 * @cancellable: a %GCancellable or %NULL
2315 * Creates a %GSource that can be attached to a %GMainContext to monitor
2316 * for the availibility of the specified @condition on the socket.
2318 * The callback on the source is of the #GSocketSourceFunc type.
2320 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2321 * these conditions will always be reported output if they are true.
2323 * @cancellable if not %NULL can be used to cancel the source, which will
2324 * cause the source to trigger, reporting the current condition (which
2325 * is likely 0 unless cancellation happened at the same time as a
2326 * condition change). You can check for this in the callback using
2327 * g_cancellable_is_cancelled().
2329 * Returns: a newly allocated %GSource, free with g_source_unref().
2334 g_socket_create_source (GSocket *socket,
2335 GIOCondition condition,
2336 GCancellable *cancellable)
2339 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2342 source = winsock_source_new (socket, condition, cancellable);
2344 source =_g_fd_source_new_with_object (G_OBJECT (socket), socket->priv->fd,
2345 condition, cancellable);
2351 * g_socket_condition_check:
2352 * @socket: a #GSocket
2353 * @condition: a #GIOCondition mask to check
2355 * Checks on the readiness of @socket to perform operations.
2356 * The operations specified in @condition are checked for and masked
2357 * against the currently-satisfied conditions on @socket. The result
2360 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2361 * these conditions will always be set in the output if they are true.
2363 * This call never blocks.
2365 * Returns: the @GIOCondition mask of the current state
2370 g_socket_condition_check (GSocket *socket,
2371 GIOCondition condition)
2373 if (!check_socket (socket, NULL))
2378 GIOCondition current_condition;
2380 condition |= G_IO_ERR | G_IO_HUP;
2382 add_condition_watch (socket, &condition);
2383 current_condition = update_condition (socket);
2384 remove_condition_watch (socket, &condition);
2385 return condition & current_condition;
2391 poll_fd.fd = socket->priv->fd;
2392 poll_fd.events = condition;
2395 result = g_poll (&poll_fd, 1, 0);
2396 while (result == -1 && get_socket_errno () == EINTR);
2398 return poll_fd.revents;
2404 * g_socket_condition_wait:
2405 * @socket: a #GSocket
2406 * @condition: a #GIOCondition mask to wait for
2407 * @cancellable: a #GCancellable, or %NULL
2408 * @error: a #GError pointer, or %NULL
2410 * Waits for @condition to become true on @socket. When the condition
2411 * is met, %TRUE is returned.
2413 * If @cancellable is cancelled before the condition is met then %FALSE
2414 * is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2416 * Returns: %TRUE if the condition was met, %FALSE otherwise
2421 g_socket_condition_wait (GSocket *socket,
2422 GIOCondition condition,
2423 GCancellable *cancellable,
2426 if (!check_socket (socket, error))
2429 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2434 GIOCondition current_condition;
2440 /* Always check these */
2441 condition |= G_IO_ERR | G_IO_HUP;
2443 add_condition_watch (socket, &condition);
2446 events[num_events++] = socket->priv->event;
2448 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2449 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2451 current_condition = update_condition (socket);
2452 while ((condition & current_condition) == 0)
2454 res = WSAWaitForMultipleEvents(num_events, events,
2455 FALSE, WSA_INFINITE, FALSE);
2456 if (res == WSA_WAIT_FAILED)
2458 int errsv = get_socket_errno ();
2460 g_set_error (error, G_IO_ERROR,
2461 socket_io_error_from_errno (errsv),
2462 _("Waiting for socket condition: %s"),
2463 socket_strerror (errsv));
2467 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2470 current_condition = update_condition (socket);
2472 remove_condition_watch (socket, &condition);
2474 return (condition & current_condition) != 0;
2482 poll_fd[0].fd = socket->priv->fd;
2483 poll_fd[0].events = condition;
2486 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2490 result = g_poll (poll_fd, num, -1);
2491 while (result == -1 && get_socket_errno () == EINTR);
2493 return cancellable == NULL ||
2494 !g_cancellable_set_error_if_cancelled (cancellable, error);
2500 * g_socket_send_message:
2501 * @socket: a #GSocket
2502 * @address: a #GSocketAddress, or %NULL
2503 * @vectors: an array of #GOutputVector structs
2504 * @num_vectors: the number of elements in @vectors, or -1
2505 * @messages: a pointer to an array of #GSocketControlMessages, or
2507 * @num_messages: number of elements in @messages, or -1.
2508 * @flags: an int containing #GSocketMsgFlags flags
2509 * @cancellable: a %GCancellable or %NULL
2510 * @error: #GError for error reporting, or %NULL to ignore.
2512 * Send data to @address on @socket. This is the most complicated and
2513 * fully-featured version of this call. For easier use, see
2514 * g_socket_send() and g_socket_send_to().
2516 * If @address is %NULL then the message is sent to the default receiver
2517 * (set by g_socket_connect()).
2519 * @vectors must point to an array of #GOutputVector structs and
2520 * @num_vectors must be the length of this array. (If @num_vectors is -1,
2521 * then @vectors is assumed to be terminated by a #GOutputVector with a
2522 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2523 * that the sent data will be gathered from. Using multiple
2524 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2525 * data from multiple sources into a single buffer, and more
2526 * network-efficient than making multiple calls to g_socket_send().
2528 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2529 * #GSocketControlMessage instances. These correspond to the control
2530 * messages to be sent on the socket.
2531 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2534 * @flags modify how the message is sent. The commonly available arguments
2535 * for this are available in the #GSocketMsgFlags enum, but the
2536 * values there are the same as the system values, and the flags
2537 * are passed in as-is, so you can pass in system-specific flags too.
2539 * If the socket is in blocking mode the call will block until there is
2540 * space for the data in the socket queue. If there is no space available
2541 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2542 * will be returned. To be notified when space is available, wait for the
2543 * %G_IO_OUT condition. Note though that you may still receive
2544 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2545 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2546 * very common due to the way the underlying APIs work.)
2548 * On error -1 is returned and @error is set accordingly.
2550 * Returns: Number of bytes written (which may be less than @size), or -1
2556 g_socket_send_message (GSocket *socket,
2557 GSocketAddress *address,
2558 GOutputVector *vectors,
2560 GSocketControlMessage **messages,
2563 GCancellable *cancellable,
2566 GOutputVector one_vector;
2569 if (!check_socket (socket, error))
2572 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2575 if (num_vectors == -1)
2577 for (num_vectors = 0;
2578 vectors[num_vectors].buffer != NULL;
2583 if (num_messages == -1)
2585 for (num_messages = 0;
2586 messages != NULL && messages[num_messages] != NULL;
2591 if (num_vectors == 0)
2595 one_vector.buffer = &zero;
2596 one_vector.size = 1;
2598 vectors = &one_vector;
2609 msg.msg_namelen = g_socket_address_get_native_size (address);
2610 msg.msg_name = g_alloca (msg.msg_namelen);
2611 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2617 /* this entire expression will be evaluated at compile time */
2618 if (sizeof *msg.msg_iov == sizeof *vectors &&
2619 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2620 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2621 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2622 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2623 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2624 G_STRUCT_OFFSET (GOutputVector, size))
2625 /* ABI is compatible */
2627 msg.msg_iov = (struct iovec *) vectors;
2628 msg.msg_iovlen = num_vectors;
2631 /* ABI is incompatible */
2635 msg.msg_iov = g_newa (struct iovec, num_vectors);
2636 for (i = 0; i < num_vectors; i++)
2638 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2639 msg.msg_iov[i].iov_len = vectors[i].size;
2641 msg.msg_iovlen = num_vectors;
2647 struct cmsghdr *cmsg;
2650 msg.msg_controllen = 0;
2651 for (i = 0; i < num_messages; i++)
2652 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2654 msg.msg_control = g_alloca (msg.msg_controllen);
2656 cmsg = CMSG_FIRSTHDR (&msg);
2657 for (i = 0; i < num_messages; i++)
2659 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2660 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2661 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2662 g_socket_control_message_serialize (messages[i],
2664 cmsg = CMSG_NXTHDR (&msg, cmsg);
2666 g_assert (cmsg == NULL);
2671 if (socket->priv->blocking &&
2672 !g_socket_condition_wait (socket,
2673 G_IO_OUT, cancellable, error))
2676 result = sendmsg (socket->priv->fd, &msg, flags);
2679 int errsv = get_socket_errno ();
2684 if (socket->priv->blocking &&
2685 (errsv == EWOULDBLOCK ||
2689 g_set_error (error, G_IO_ERROR,
2690 socket_io_error_from_errno (errsv),
2691 _("Error sending message: %s"), socket_strerror (errsv));
2702 struct sockaddr_storage addr;
2709 /* Win32 doesn't support control messages.
2710 Actually this is possible for raw and datagram sockets
2711 via WSASendMessage on Vista or later, but that doesn't
2713 if (num_messages != 0)
2715 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2716 _("GSocketControlMessage not supported on windows"));
2721 bufs = g_newa (WSABUF, num_vectors);
2722 for (i = 0; i < num_vectors; i++)
2724 bufs[i].buf = (char *)vectors[i].buffer;
2725 bufs[i].len = (gulong)vectors[i].size;
2729 addrlen = 0; /* Avoid warning */
2732 addrlen = g_socket_address_get_native_size (address);
2733 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2739 if (socket->priv->blocking &&
2740 !g_socket_condition_wait (socket,
2741 G_IO_OUT, cancellable, error))
2745 result = WSASendTo (socket->priv->fd,
2748 (const struct sockaddr *)&addr, addrlen,
2751 result = WSASend (socket->priv->fd,
2758 int errsv = get_socket_errno ();
2760 if (errsv == WSAEINTR)
2763 if (errsv == WSAEWOULDBLOCK)
2764 win32_unset_event_mask (socket, FD_WRITE);
2766 if (socket->priv->blocking &&
2767 errsv == WSAEWOULDBLOCK)
2770 g_set_error (error, G_IO_ERROR,
2771 socket_io_error_from_errno (errsv),
2772 _("Error sending message: %s"), socket_strerror (errsv));
2785 * g_socket_receive_message:
2786 * @socket: a #GSocket
2787 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2788 * @vectors: an array of #GInputVector structs
2789 * @num_vectors: the number of elements in @vectors, or -1
2790 * @messages: a pointer which will be filled with an array of
2791 * #GSocketControlMessages, or %NULL
2792 * @num_messages: a pointer which will be filled with the number of
2793 * elements in @messages, or %NULL
2794 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2795 * @cancellable: a %GCancellable or %NULL
2796 * @error: a #GError pointer, or %NULL
2798 * Receive data from a socket. This is the most complicated and
2799 * fully-featured version of this call. For easier use, see
2800 * g_socket_receive() and g_socket_receive_from().
2802 * If @address is non-%NULL then @address will be set equal to the
2803 * source address of the received packet.
2804 * @address is owned by the caller.
2806 * @vector must point to an array of #GInputVector structs and
2807 * @num_vectors must be the length of this array. These structs
2808 * describe the buffers that received data will be scattered into.
2809 * If @num_vectors is -1, then @vectors is assumed to be terminated
2810 * by a #GInputVector with a %NULL buffer pointer.
2812 * As a special case, if @num_vectors is 0 (in which case, @vectors
2813 * may of course be %NULL), then a single byte is received and
2814 * discarded. This is to facilitate the common practice of sending a
2815 * single '\0' byte for the purposes of transferring ancillary data.
2817 * @messages, if non-%NULL, will be set to point to a newly-allocated
2818 * array of #GSocketControlMessage instances. These correspond to the
2819 * control messages received from the kernel, one
2820 * #GSocketControlMessage per message from the kernel. This array is
2821 * %NULL-terminated and must be freed by the caller using g_free(). If
2822 * @messages is %NULL, any control messages received will be
2825 * @num_messages, if non-%NULL, will be set to the number of control
2826 * messages received.
2828 * If both @messages and @num_messages are non-%NULL, then
2829 * @num_messages gives the number of #GSocketControlMessage instances
2830 * in @messages (ie: not including the %NULL terminator).
2832 * @flags is an in/out parameter. The commonly available arguments
2833 * for this are available in the #GSocketMsgFlags enum, but the
2834 * values there are the same as the system values, and the flags
2835 * are passed in as-is, so you can pass in system-specific flags too
2836 * (and g_socket_receive_message() may pass system-specific flags out).
2838 * As with g_socket_receive(), data may be discarded if @socket is
2839 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
2840 * provide enough buffer space to read a complete message. You can pass
2841 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
2842 * removing it from the receive queue, but there is no portable way to find
2843 * out the length of the message other than by reading it into a
2844 * sufficiently-large buffer.
2846 * If the socket is in blocking mode the call will block until there
2847 * is some data to receive or there is an error. If there is no data
2848 * available and the socket is in non-blocking mode, a
2849 * %G_IO_ERROR_WOULD_BLOCK error will be returned. To be notified when
2850 * data is available, wait for the %G_IO_IN condition.
2852 * On error -1 is returned and @error is set accordingly.
2854 * Returns: Number of bytes read, or -1 on error
2859 g_socket_receive_message (GSocket *socket,
2860 GSocketAddress **address,
2861 GInputVector *vectors,
2863 GSocketControlMessage ***messages,
2866 GCancellable *cancellable,
2869 GInputVector one_vector;
2872 if (!check_socket (socket, error))
2875 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2878 if (num_vectors == -1)
2880 for (num_vectors = 0;
2881 vectors[num_vectors].buffer != NULL;
2886 if (num_vectors == 0)
2888 one_vector.buffer = &one_byte;
2889 one_vector.size = 1;
2891 vectors = &one_vector;
2898 struct sockaddr_storage one_sockaddr;
2903 msg.msg_name = &one_sockaddr;
2904 msg.msg_namelen = sizeof (struct sockaddr_storage);
2908 msg.msg_name = NULL;
2909 msg.msg_namelen = 0;
2913 /* this entire expression will be evaluated at compile time */
2914 if (sizeof *msg.msg_iov == sizeof *vectors &&
2915 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2916 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2917 G_STRUCT_OFFSET (GInputVector, buffer) &&
2918 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2919 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2920 G_STRUCT_OFFSET (GInputVector, size))
2921 /* ABI is compatible */
2923 msg.msg_iov = (struct iovec *) vectors;
2924 msg.msg_iovlen = num_vectors;
2927 /* ABI is incompatible */
2931 msg.msg_iov = g_newa (struct iovec, num_vectors);
2932 for (i = 0; i < num_vectors; i++)
2934 msg.msg_iov[i].iov_base = vectors[i].buffer;
2935 msg.msg_iov[i].iov_len = vectors[i].size;
2937 msg.msg_iovlen = num_vectors;
2941 msg.msg_control = g_alloca (2048);
2942 msg.msg_controllen = 2048;
2946 msg.msg_flags = *flags;
2953 if (socket->priv->blocking &&
2954 !g_socket_condition_wait (socket,
2955 G_IO_IN, cancellable, error))
2958 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2962 int errsv = get_socket_errno ();
2967 if (socket->priv->blocking &&
2968 (errsv == EWOULDBLOCK ||
2972 g_set_error (error, G_IO_ERROR,
2973 socket_io_error_from_errno (errsv),
2974 _("Error receiving message: %s"), socket_strerror (errsv));
2981 /* decode address */
2982 if (address != NULL)
2984 if (msg.msg_namelen > 0)
2985 *address = g_socket_address_new_from_native (msg.msg_name,
2991 /* decode control messages */
2993 GSocketControlMessage **my_messages = NULL;
2994 gint allocated = 0, index = 0;
2995 const gchar *scm_pointer;
2996 struct cmsghdr *cmsg;
2999 scm_pointer = (const gchar *) msg.msg_control;
3000 scm_size = msg.msg_controllen;
3002 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3004 GSocketControlMessage *message;
3006 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3008 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3010 if (message == NULL)
3011 /* We've already spewed about the problem in the
3012 deserialization code, so just continue */
3015 if (index == allocated)
3017 /* estimated 99% case: exactly 1 control message */
3018 allocated = MIN (allocated * 2, 1);
3019 my_messages = g_new (GSocketControlMessage *, (allocated + 1));
3023 my_messages[index++] = message;
3027 *num_messages = index;
3031 my_messages[index++] = NULL;
3032 *messages = my_messages;
3038 /* free all those messages we just constructed.
3039 * we have to do it this way if the user ignores the
3040 * messages so that we will close any received fds.
3042 for (i = 0; i < index; i++)
3043 g_object_unref (my_messages[i]);
3044 g_free (my_messages);
3048 /* capture the flags */
3050 *flags = msg.msg_flags;
3056 struct sockaddr_storage addr;
3058 DWORD bytes_received;
3065 bufs = g_newa (WSABUF, num_vectors);
3066 for (i = 0; i < num_vectors; i++)
3068 bufs[i].buf = (char *)vectors[i].buffer;
3069 bufs[i].len = (gulong)vectors[i].size;
3081 if (socket->priv->blocking &&
3082 !g_socket_condition_wait (socket,
3083 G_IO_IN, cancellable, error))
3086 addrlen = sizeof addr;
3088 result = WSARecvFrom (socket->priv->fd,
3090 &bytes_received, &win_flags,
3091 (struct sockaddr *)&addr, &addrlen,
3094 result = WSARecv (socket->priv->fd,
3096 &bytes_received, &win_flags,
3100 int errsv = get_socket_errno ();
3102 if (errsv == WSAEINTR)
3105 win32_unset_event_mask (socket, FD_READ);
3107 if (socket->priv->blocking &&
3108 errsv == WSAEWOULDBLOCK)
3111 g_set_error (error, G_IO_ERROR,
3112 socket_io_error_from_errno (errsv),
3113 _("Error receiving message: %s"), socket_strerror (errsv));
3117 win32_unset_event_mask (socket, FD_READ);
3121 /* decode address */
3122 if (address != NULL)
3125 *address = g_socket_address_new_from_native (&addr, addrlen);
3130 /* capture the flags */
3134 return bytes_received;
3139 #define __G_SOCKET_C__
3140 #include "gioaliasdef.c"