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
6 * Copyright © 2015 Collabora, Ltd.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General
19 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 * Authors: Christian Kellner <gicmo@gnome.org>
22 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
23 * Ryan Lortie <desrt@desrt.ca>
24 * Alexander Larsson <alexl@redhat.com>
25 * Philip Withnall <philip.withnall@collabora.co.uk>
33 #include "glib-unix.h"
44 # include <sys/ioctl.h>
47 #ifdef HAVE_SIOCGIFADDR
51 #ifdef HAVE_SYS_FILIO_H
52 # include <sys/filio.h>
59 #define GOBJECT_COMPILATION
60 #include "gobject/gtype-private.h" /* For _PRELUDE type define */
61 #undef GOBJECT_COMPILATION
62 #include "gcancellable.h"
63 #include "gdatagrambased.h"
64 #include "gioenumtypes.h"
65 #include "ginetaddress.h"
66 #include "ginetsocketaddress.h"
67 #include "ginitable.h"
71 #include "gnetworkingprivate.h"
72 #include "gsocketaddress.h"
73 #include "gsocketcontrolmessage.h"
74 #include "gcredentials.h"
75 #include "gcredentialsprivate.h"
79 /* For Windows XP runtime compatibility, but use the system's if_nametoindex() if available */
80 #include "gwin32networking.h"
85 * @short_description: Low-level socket object
87 * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
89 * A #GSocket is a low-level networking primitive. It is a more or less
90 * direct mapping of the BSD socket API in a portable GObject based API.
91 * It supports both the UNIX socket implementations and winsock2 on Windows.
93 * #GSocket is the platform independent base upon which the higher level
94 * network primitives are based. Applications are not typically meant to
95 * use it directly, but rather through classes like #GSocketClient,
96 * #GSocketService and #GSocketConnection. However there may be cases where
97 * direct use of #GSocket is useful.
99 * #GSocket implements the #GInitable interface, so if it is manually constructed
100 * by e.g. g_object_new() you must call g_initable_init() and check the
101 * results before using the object. This is done automatically in
102 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
105 * Sockets operate in two general modes, blocking or non-blocking. When
106 * in blocking mode all operations (which don’t take an explicit blocking
107 * parameter) block until the requested operation
108 * is finished or there is an error. In non-blocking mode all calls that
109 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
110 * To know when a call would successfully run you can call g_socket_condition_check(),
111 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
112 * attach it to a #GMainContext to get callbacks when I/O is possible.
113 * Note that all sockets are always set to non blocking mode in the system, and
114 * blocking mode is emulated in GSocket.
116 * When working in non-blocking mode applications should always be able to
117 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
118 * function said that I/O was possible. This can easily happen in case
119 * of a race condition in the application, but it can also happen for other
120 * reasons. For instance, on Windows a socket is always seen as writable
121 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
123 * #GSockets can be either connection oriented or datagram based.
124 * For connection oriented types you must first establish a connection by
125 * either connecting to an address or accepting a connection from another
126 * address. For connectionless socket types the target/source address is
127 * specified or received in each I/O operation.
129 * All socket file descriptors are set to be close-on-exec.
131 * Note that creating a #GSocket causes the signal %SIGPIPE to be
132 * ignored for the remainder of the program. If you are writing a
133 * command-line utility that uses #GSocket, you may need to take into
134 * account the fact that your program will not automatically be killed
135 * if it tries to write to %stdout after it has been closed.
137 * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
138 * a #GSocket concurrently from multiple threads, you must implement your own
144 static void g_socket_initable_iface_init (GInitableIface
*iface
);
145 static gboolean
g_socket_initable_init (GInitable
*initable
,
146 GCancellable
*cancellable
,
149 static void g_socket_datagram_based_iface_init (GDatagramBasedInterface
*iface
);
150 static gint
g_socket_datagram_based_receive_messages (GDatagramBased
*self
,
151 GInputMessage
*messages
,
155 GCancellable
*cancellable
,
157 static gint
g_socket_datagram_based_send_messages (GDatagramBased
*self
,
158 GOutputMessage
*messages
,
162 GCancellable
*cancellable
,
164 static GSource
*g_socket_datagram_based_create_source (GDatagramBased
*self
,
165 GIOCondition condition
,
166 GCancellable
*cancellable
);
167 static GIOCondition
g_socket_datagram_based_condition_check (GDatagramBased
*datagram_based
,
168 GIOCondition condition
);
169 static gboolean
g_socket_datagram_based_condition_wait (GDatagramBased
*datagram_based
,
170 GIOCondition condition
,
172 GCancellable
*cancellable
,
175 static GSocketAddress
*
176 cache_recv_address (GSocket
*socket
, struct sockaddr
*native
, int native_len
);
179 g_socket_receive_message_with_timeout (GSocket
*socket
,
180 GSocketAddress
**address
,
181 GInputVector
*vectors
,
183 GSocketControlMessage
***messages
,
187 GCancellable
*cancellable
,
190 g_socket_receive_messages_with_timeout (GSocket
*socket
,
191 GInputMessage
*messages
,
195 GCancellable
*cancellable
,
198 g_socket_send_message_with_timeout (GSocket
*socket
,
199 GSocketAddress
*address
,
200 GOutputVector
*vectors
,
202 GSocketControlMessage
**messages
,
206 GCancellable
*cancellable
,
209 g_socket_send_messages_with_timeout (GSocket
*socket
,
210 GOutputMessage
*messages
,
214 GCancellable
*cancellable
,
232 PROP_MULTICAST_LOOPBACK
,
236 /* Size of the receiver cache for g_socket_receive_from() */
237 #define RECV_ADDR_CACHE_SIZE 8
239 struct _GSocketPrivate
241 GSocketFamily family
;
243 GSocketProtocol protocol
;
247 GError
*construct_error
;
248 GSocketAddress
*remote_address
;
253 guint connected_read
: 1;
254 guint connected_write
: 1;
257 guint connect_pending
: 1;
261 DWORD waiting_result
;
265 GList
*requested_conditions
; /* list of requested GIOCondition * */
266 GMutex win32_source_lock
;
267 GCond win32_source_cond
;
271 GSocketAddress
*addr
;
272 struct sockaddr
*native
;
275 } recv_addr_cache
[RECV_ADDR_CACHE_SIZE
];
278 _G_DEFINE_TYPE_EXTENDED_WITH_PRELUDE (GSocket
, g_socket
, G_TYPE_OBJECT
, 0,
279 /* Need a prelude for https://bugzilla.gnome.org/show_bug.cgi?id=674885 */
280 g_type_ensure (G_TYPE_SOCKET_FAMILY
);
281 g_type_ensure (G_TYPE_SOCKET_TYPE
);
282 g_type_ensure (G_TYPE_SOCKET_PROTOCOL
);
283 g_type_ensure (G_TYPE_SOCKET_ADDRESS
);
284 /* And networking init is appropriate for the prelude */
285 g_networking_init ();
286 , /* And now the regular type init code */
287 G_ADD_PRIVATE (GSocket
)
288 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE
,
289 g_socket_initable_iface_init
);
290 G_IMPLEMENT_INTERFACE (G_TYPE_DATAGRAM_BASED
,
291 g_socket_datagram_based_iface_init
));
294 get_socket_errno (void)
299 return WSAGetLastError ();
304 socket_io_error_from_errno (int err
)
307 return g_io_error_from_win32_error (err
);
309 return g_io_error_from_errno (err
);
314 socket_strerror (int err
)
317 return g_strerror (err
);
322 msg
= g_win32_error_message (err
);
324 msg_ret
= g_intern_string (msg
);
331 /* Wrapper around g_set_error() to avoid doing excess work */
332 #define socket_set_error_lazy(err, errsv, fmt) \
334 GError **__err = (err); \
335 int __errsv = (errsv); \
339 int __code = socket_io_error_from_errno (__errsv); \
340 const char *__strerr = socket_strerror (__errsv); \
342 if (__code == G_IO_ERROR_WOULD_BLOCK) \
343 g_set_error_literal (__err, G_IO_ERROR, __code, __strerr); \
345 g_set_error (__err, G_IO_ERROR, __code, fmt, __strerr); \
350 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
352 _win32_unset_event_mask (GSocket
*socket
, int mask
)
354 g_mutex_lock (&socket
->priv
->win32_source_lock
);
355 socket
->priv
->current_events
&= ~mask
;
356 socket
->priv
->current_errors
&= ~mask
;
357 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
360 #define win32_unset_event_mask(_socket, _mask)
363 /* Windows has broken prototypes... */
365 #define getsockopt(sockfd, level, optname, optval, optlen) \
366 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
367 #define setsockopt(sockfd, level, optname, optval, optlen) \
368 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
369 #define getsockname(sockfd, addr, addrlen) \
370 getsockname (sockfd, addr, (int *)addrlen)
371 #define getpeername(sockfd, addr, addrlen) \
372 getpeername (sockfd, addr, (int *)addrlen)
373 #define recv(sockfd, buf, len, flags) \
374 recv (sockfd, (gpointer)buf, len, flags)
378 check_socket (GSocket
*socket
,
381 if (!socket
->priv
->inited
)
383 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_NOT_INITIALIZED
,
384 _("Invalid socket, not initialized"));
388 if (socket
->priv
->construct_error
)
390 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_INITIALIZED
,
391 _("Invalid socket, initialization failed due to: %s"),
392 socket
->priv
->construct_error
->message
);
396 if (socket
->priv
->closed
)
398 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_CLOSED
,
399 _("Socket is already closed"));
407 check_timeout (GSocket
*socket
,
410 if (socket
->priv
->timed_out
)
412 socket
->priv
->timed_out
= FALSE
;
413 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
,
414 _("Socket I/O timed out"));
422 g_socket_details_from_fd (GSocket
*socket
)
424 struct sockaddr_storage address
;
430 fd
= socket
->priv
->fd
;
431 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_TYPE
, &value
, NULL
))
433 errsv
= get_socket_errno ();
440 socket
->priv
->type
= G_SOCKET_TYPE_STREAM
;
444 socket
->priv
->type
= G_SOCKET_TYPE_DATAGRAM
;
448 socket
->priv
->type
= G_SOCKET_TYPE_SEQPACKET
;
452 socket
->priv
->type
= G_SOCKET_TYPE_INVALID
;
456 addrlen
= sizeof address
;
457 if (getsockname (fd
, (struct sockaddr
*) &address
, &addrlen
) != 0)
459 errsv
= get_socket_errno ();
465 g_assert (G_STRUCT_OFFSET (struct sockaddr
, sa_family
) +
466 sizeof address
.ss_family
<= addrlen
);
467 family
= address
.ss_family
;
471 /* On Solaris, this happens if the socket is not yet connected.
472 * But we can use SO_DOMAIN as a workaround there.
475 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_DOMAIN
, &family
, NULL
))
477 errsv
= get_socket_errno ();
481 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
489 case G_SOCKET_FAMILY_IPV4
:
490 case G_SOCKET_FAMILY_IPV6
:
491 socket
->priv
->family
= address
.ss_family
;
492 switch (socket
->priv
->type
)
494 case G_SOCKET_TYPE_STREAM
:
495 socket
->priv
->protocol
= G_SOCKET_PROTOCOL_TCP
;
498 case G_SOCKET_TYPE_DATAGRAM
:
499 socket
->priv
->protocol
= G_SOCKET_PROTOCOL_UDP
;
502 case G_SOCKET_TYPE_SEQPACKET
:
503 socket
->priv
->protocol
= G_SOCKET_PROTOCOL_SCTP
;
511 case G_SOCKET_FAMILY_UNIX
:
512 socket
->priv
->family
= G_SOCKET_FAMILY_UNIX
;
513 socket
->priv
->protocol
= G_SOCKET_PROTOCOL_DEFAULT
;
517 socket
->priv
->family
= G_SOCKET_FAMILY_INVALID
;
521 if (socket
->priv
->family
!= G_SOCKET_FAMILY_INVALID
)
523 addrlen
= sizeof address
;
524 if (getpeername (fd
, (struct sockaddr
*) &address
, &addrlen
) >= 0)
526 socket
->priv
->connected_read
= TRUE
;
527 socket
->priv
->connected_write
= TRUE
;
531 if (g_socket_get_option (socket
, SOL_SOCKET
, SO_KEEPALIVE
, &value
, NULL
))
533 socket
->priv
->keepalive
= !!value
;
537 /* Can't read, maybe not supported, assume FALSE */
538 socket
->priv
->keepalive
= FALSE
;
544 g_set_error (&socket
->priv
->construct_error
, G_IO_ERROR
,
545 socket_io_error_from_errno (errsv
),
546 _("creating GSocket from fd: %s"),
547 socket_strerror (errsv
));
550 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
552 g_socket (gint domain
,
560 fd
= socket (domain
, type
| SOCK_CLOEXEC
, protocol
);
565 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
566 if (fd
< 0 && (errsv
== EINVAL
|| errsv
== EPROTOTYPE
))
568 fd
= socket (domain
, type
, protocol
);
572 int errsv
= get_socket_errno ();
574 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
575 _("Unable to create socket: %s"), socket_strerror (errsv
));
584 /* We always want to set close-on-exec to protect users. If you
585 need to so some weird inheritance to exec you can re-enable this
586 using lower level hacks with g_socket_get_fd(). */
587 flags
= fcntl (fd
, F_GETFD
, 0);
589 (flags
& FD_CLOEXEC
) == 0)
592 fcntl (fd
, F_SETFD
, flags
);
601 g_socket_create_socket (GSocketFamily family
,
610 case G_SOCKET_TYPE_STREAM
:
611 native_type
= SOCK_STREAM
;
614 case G_SOCKET_TYPE_DATAGRAM
:
615 native_type
= SOCK_DGRAM
;
618 case G_SOCKET_TYPE_SEQPACKET
:
619 native_type
= SOCK_SEQPACKET
;
623 g_assert_not_reached ();
628 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_INVALID_ARGUMENT
,
629 _("Unable to create socket: %s"), _("Unknown family was specified"));
635 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_INVALID_ARGUMENT
,
636 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
640 return g_socket (family
, native_type
, protocol
, error
);
644 g_socket_constructed (GObject
*object
)
646 GSocket
*socket
= G_SOCKET (object
);
648 if (socket
->priv
->fd
>= 0)
649 /* create socket->priv info from the fd */
650 g_socket_details_from_fd (socket
);
653 /* create the fd from socket->priv info */
654 socket
->priv
->fd
= g_socket_create_socket (socket
->priv
->family
,
656 socket
->priv
->protocol
,
657 &socket
->priv
->construct_error
);
659 if (socket
->priv
->fd
!= -1)
662 GError
*error
= NULL
;
667 /* Always use native nonblocking sockets, as Windows sets sockets to
668 * nonblocking automatically in certain operations. This way we make
669 * things work the same on all platforms.
672 if (!g_unix_set_fd_nonblocking (socket
->priv
->fd
, TRUE
, &error
))
674 g_warning ("Error setting socket nonblocking: %s", error
->message
);
675 g_clear_error (&error
);
680 if (ioctlsocket (socket
->priv
->fd
, FIONBIO
, &arg
) == SOCKET_ERROR
)
682 int errsv
= get_socket_errno ();
683 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv
));
688 /* See note about SIGPIPE below. */
689 g_socket_set_option (socket
, SOL_SOCKET
, SO_NOSIGPIPE
, TRUE
, NULL
);
695 g_socket_get_property (GObject
*object
,
700 GSocket
*socket
= G_SOCKET (object
);
701 GSocketAddress
*address
;
706 g_value_set_enum (value
, socket
->priv
->family
);
710 g_value_set_enum (value
, socket
->priv
->type
);
714 g_value_set_enum (value
, socket
->priv
->protocol
);
718 g_value_set_int (value
, socket
->priv
->fd
);
722 g_value_set_boolean (value
, socket
->priv
->blocking
);
725 case PROP_LISTEN_BACKLOG
:
726 g_value_set_int (value
, socket
->priv
->listen_backlog
);
730 g_value_set_boolean (value
, socket
->priv
->keepalive
);
733 case PROP_LOCAL_ADDRESS
:
734 address
= g_socket_get_local_address (socket
, NULL
);
735 g_value_take_object (value
, address
);
738 case PROP_REMOTE_ADDRESS
:
739 address
= g_socket_get_remote_address (socket
, NULL
);
740 g_value_take_object (value
, address
);
744 g_value_set_uint (value
, socket
->priv
->timeout
);
748 g_value_set_uint (value
, g_socket_get_ttl (socket
));
752 g_value_set_boolean (value
, g_socket_get_broadcast (socket
));
755 case PROP_MULTICAST_LOOPBACK
:
756 g_value_set_boolean (value
, g_socket_get_multicast_loopback (socket
));
759 case PROP_MULTICAST_TTL
:
760 g_value_set_uint (value
, g_socket_get_multicast_ttl (socket
));
764 G_OBJECT_WARN_INVALID_PROPERTY_ID (object
, prop_id
, pspec
);
769 g_socket_set_property (GObject
*object
,
774 GSocket
*socket
= G_SOCKET (object
);
779 socket
->priv
->family
= g_value_get_enum (value
);
783 socket
->priv
->type
= g_value_get_enum (value
);
787 socket
->priv
->protocol
= g_value_get_enum (value
);
791 socket
->priv
->fd
= g_value_get_int (value
);
795 g_socket_set_blocking (socket
, g_value_get_boolean (value
));
798 case PROP_LISTEN_BACKLOG
:
799 g_socket_set_listen_backlog (socket
, g_value_get_int (value
));
803 g_socket_set_keepalive (socket
, g_value_get_boolean (value
));
807 g_socket_set_timeout (socket
, g_value_get_uint (value
));
811 g_socket_set_ttl (socket
, g_value_get_uint (value
));
815 g_socket_set_broadcast (socket
, g_value_get_boolean (value
));
818 case PROP_MULTICAST_LOOPBACK
:
819 g_socket_set_multicast_loopback (socket
, g_value_get_boolean (value
));
822 case PROP_MULTICAST_TTL
:
823 g_socket_set_multicast_ttl (socket
, g_value_get_uint (value
));
827 G_OBJECT_WARN_INVALID_PROPERTY_ID (object
, prop_id
, pspec
);
832 g_socket_finalize (GObject
*object
)
834 GSocket
*socket
= G_SOCKET (object
);
837 g_clear_error (&socket
->priv
->construct_error
);
839 if (socket
->priv
->fd
!= -1 &&
840 !socket
->priv
->closed
)
841 g_socket_close (socket
, NULL
);
843 if (socket
->priv
->remote_address
)
844 g_object_unref (socket
->priv
->remote_address
);
847 if (socket
->priv
->event
!= WSA_INVALID_EVENT
)
849 WSACloseEvent (socket
->priv
->event
);
850 socket
->priv
->event
= WSA_INVALID_EVENT
;
853 g_assert (socket
->priv
->requested_conditions
== NULL
);
854 g_mutex_clear (&socket
->priv
->win32_source_lock
);
855 g_cond_clear (&socket
->priv
->win32_source_cond
);
858 for (i
= 0; i
< RECV_ADDR_CACHE_SIZE
; i
++)
860 if (socket
->priv
->recv_addr_cache
[i
].addr
)
862 g_object_unref (socket
->priv
->recv_addr_cache
[i
].addr
);
863 g_free (socket
->priv
->recv_addr_cache
[i
].native
);
867 if (G_OBJECT_CLASS (g_socket_parent_class
)->finalize
)
868 (*G_OBJECT_CLASS (g_socket_parent_class
)->finalize
) (object
);
872 g_socket_class_init (GSocketClass
*klass
)
874 GObjectClass
*gobject_class G_GNUC_UNUSED
= G_OBJECT_CLASS (klass
);
877 /* There is no portable, thread-safe way to avoid having the process
878 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
879 * forced to simply ignore the signal process-wide.
881 * Even if we ignore it though, gdb will still stop if the app
882 * receives a SIGPIPE, which can be confusing and annoying. So when
883 * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
884 * prevent the signal from occurring at all.
886 signal (SIGPIPE
, SIG_IGN
);
889 gobject_class
->finalize
= g_socket_finalize
;
890 gobject_class
->constructed
= g_socket_constructed
;
891 gobject_class
->set_property
= g_socket_set_property
;
892 gobject_class
->get_property
= g_socket_get_property
;
894 g_object_class_install_property (gobject_class
, PROP_FAMILY
,
895 g_param_spec_enum ("family",
897 P_("The sockets address family"),
898 G_TYPE_SOCKET_FAMILY
,
899 G_SOCKET_FAMILY_INVALID
,
900 G_PARAM_CONSTRUCT_ONLY
|
902 G_PARAM_STATIC_STRINGS
));
904 g_object_class_install_property (gobject_class
, PROP_TYPE
,
905 g_param_spec_enum ("type",
907 P_("The sockets type"),
909 G_SOCKET_TYPE_STREAM
,
910 G_PARAM_CONSTRUCT_ONLY
|
912 G_PARAM_STATIC_STRINGS
));
914 g_object_class_install_property (gobject_class
, PROP_PROTOCOL
,
915 g_param_spec_enum ("protocol",
916 P_("Socket protocol"),
917 P_("The id of the protocol to use, or -1 for unknown"),
918 G_TYPE_SOCKET_PROTOCOL
,
919 G_SOCKET_PROTOCOL_UNKNOWN
,
920 G_PARAM_CONSTRUCT_ONLY
|
922 G_PARAM_STATIC_STRINGS
));
924 g_object_class_install_property (gobject_class
, PROP_FD
,
925 g_param_spec_int ("fd",
926 P_("File descriptor"),
927 P_("The sockets file descriptor"),
931 G_PARAM_CONSTRUCT_ONLY
|
933 G_PARAM_STATIC_STRINGS
));
935 g_object_class_install_property (gobject_class
, PROP_BLOCKING
,
936 g_param_spec_boolean ("blocking",
938 P_("Whether or not I/O on this socket is blocking"),
941 G_PARAM_STATIC_STRINGS
));
943 g_object_class_install_property (gobject_class
, PROP_LISTEN_BACKLOG
,
944 g_param_spec_int ("listen-backlog",
945 P_("Listen backlog"),
946 P_("Outstanding connections in the listen queue"),
951 G_PARAM_STATIC_STRINGS
));
953 g_object_class_install_property (gobject_class
, PROP_KEEPALIVE
,
954 g_param_spec_boolean ("keepalive",
955 P_("Keep connection alive"),
956 P_("Keep connection alive by sending periodic pings"),
959 G_PARAM_STATIC_STRINGS
));
961 g_object_class_install_property (gobject_class
, PROP_LOCAL_ADDRESS
,
962 g_param_spec_object ("local-address",
964 P_("The local address the socket is bound to"),
965 G_TYPE_SOCKET_ADDRESS
,
967 G_PARAM_STATIC_STRINGS
));
969 g_object_class_install_property (gobject_class
, PROP_REMOTE_ADDRESS
,
970 g_param_spec_object ("remote-address",
971 P_("Remote address"),
972 P_("The remote address the socket is connected to"),
973 G_TYPE_SOCKET_ADDRESS
,
975 G_PARAM_STATIC_STRINGS
));
980 * The timeout in seconds on socket I/O
984 g_object_class_install_property (gobject_class
, PROP_TIMEOUT
,
985 g_param_spec_uint ("timeout",
987 P_("The timeout in seconds on socket I/O"),
992 G_PARAM_STATIC_STRINGS
));
997 * Whether the socket should allow sending to broadcast addresses.
1001 g_object_class_install_property (gobject_class
, PROP_BROADCAST
,
1002 g_param_spec_boolean ("broadcast",
1004 P_("Whether to allow sending to broadcast addresses"),
1007 G_PARAM_STATIC_STRINGS
));
1012 * Time-to-live for outgoing unicast packets
1016 g_object_class_install_property (gobject_class
, PROP_TTL
,
1017 g_param_spec_uint ("ttl",
1019 P_("Time-to-live of outgoing unicast packets"),
1022 G_PARAM_STATIC_STRINGS
));
1025 * GSocket:multicast-loopback:
1027 * Whether outgoing multicast packets loop back to the local host.
1031 g_object_class_install_property (gobject_class
, PROP_MULTICAST_LOOPBACK
,
1032 g_param_spec_boolean ("multicast-loopback",
1033 P_("Multicast loopback"),
1034 P_("Whether outgoing multicast packets loop back to the local host"),
1037 G_PARAM_STATIC_STRINGS
));
1040 * GSocket:multicast-ttl:
1042 * Time-to-live out outgoing multicast packets
1046 g_object_class_install_property (gobject_class
, PROP_MULTICAST_TTL
,
1047 g_param_spec_uint ("multicast-ttl",
1048 P_("Multicast TTL"),
1049 P_("Time-to-live of outgoing multicast packets"),
1052 G_PARAM_STATIC_STRINGS
));
1056 g_socket_initable_iface_init (GInitableIface
*iface
)
1058 iface
->init
= g_socket_initable_init
;
1062 g_socket_datagram_based_iface_init (GDatagramBasedInterface
*iface
)
1064 iface
->receive_messages
= g_socket_datagram_based_receive_messages
;
1065 iface
->send_messages
= g_socket_datagram_based_send_messages
;
1066 iface
->create_source
= g_socket_datagram_based_create_source
;
1067 iface
->condition_check
= g_socket_datagram_based_condition_check
;
1068 iface
->condition_wait
= g_socket_datagram_based_condition_wait
;
1072 g_socket_init (GSocket
*socket
)
1074 socket
->priv
= g_socket_get_instance_private (socket
);
1076 socket
->priv
->fd
= -1;
1077 socket
->priv
->blocking
= TRUE
;
1078 socket
->priv
->listen_backlog
= 10;
1079 socket
->priv
->construct_error
= NULL
;
1081 socket
->priv
->event
= WSA_INVALID_EVENT
;
1082 g_mutex_init (&socket
->priv
->win32_source_lock
);
1083 g_cond_init (&socket
->priv
->win32_source_cond
);
1088 g_socket_initable_init (GInitable
*initable
,
1089 GCancellable
*cancellable
,
1094 g_return_val_if_fail (G_IS_SOCKET (initable
), FALSE
);
1096 socket
= G_SOCKET (initable
);
1098 if (cancellable
!= NULL
)
1100 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
1101 _("Cancellable initialization not supported"));
1105 socket
->priv
->inited
= TRUE
;
1107 if (socket
->priv
->construct_error
)
1110 *error
= g_error_copy (socket
->priv
->construct_error
);
1119 check_datagram_based (GDatagramBased
*self
,
1122 switch (g_socket_get_socket_type (G_SOCKET (self
)))
1124 case G_SOCKET_TYPE_INVALID
:
1125 case G_SOCKET_TYPE_STREAM
:
1126 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
1127 _("Cannot use datagram operations on a non-datagram "
1130 case G_SOCKET_TYPE_DATAGRAM
:
1131 case G_SOCKET_TYPE_SEQPACKET
:
1136 /* Due to us sharing #GSocketSource with the #GSocket implementation, it is
1137 * pretty tricky to split out #GSocket:timeout so that it does not affect
1138 * #GDatagramBased operations (but still affects #GSocket operations). It is
1139 * not worth that effort — just disallow it and require the user to specify
1140 * timeouts on a per-operation basis. */
1141 if (g_socket_get_timeout (G_SOCKET (self
)) != 0)
1143 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
1144 _("Cannot use datagram operations on a socket with a "
1153 g_socket_datagram_based_receive_messages (GDatagramBased
*self
,
1154 GInputMessage
*messages
,
1158 GCancellable
*cancellable
,
1161 if (!check_datagram_based (self
, error
))
1164 return g_socket_receive_messages_with_timeout (G_SOCKET (self
), messages
,
1165 num_messages
, flags
, timeout
,
1166 cancellable
, error
);
1170 g_socket_datagram_based_send_messages (GDatagramBased
*self
,
1171 GOutputMessage
*messages
,
1175 GCancellable
*cancellable
,
1178 if (!check_datagram_based (self
, error
))
1181 return g_socket_send_messages_with_timeout (G_SOCKET (self
), messages
,
1182 num_messages
, flags
, timeout
,
1183 cancellable
, error
);
1187 g_socket_datagram_based_create_source (GDatagramBased
*self
,
1188 GIOCondition condition
,
1189 GCancellable
*cancellable
)
1191 if (!check_datagram_based (self
, NULL
))
1194 return g_socket_create_source (G_SOCKET (self
), condition
, cancellable
);
1198 g_socket_datagram_based_condition_check (GDatagramBased
*datagram_based
,
1199 GIOCondition condition
)
1201 if (!check_datagram_based (datagram_based
, NULL
))
1204 return g_socket_condition_check (G_SOCKET (datagram_based
), condition
);
1208 g_socket_datagram_based_condition_wait (GDatagramBased
*datagram_based
,
1209 GIOCondition condition
,
1211 GCancellable
*cancellable
,
1214 if (!check_datagram_based (datagram_based
, error
))
1217 return g_socket_condition_timed_wait (G_SOCKET (datagram_based
), condition
,
1218 timeout
, cancellable
, error
);
1223 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1224 * @type: the socket type to use.
1225 * @protocol: the id of the protocol to use, or 0 for default.
1226 * @error: #GError for error reporting, or %NULL to ignore.
1228 * Creates a new #GSocket with the defined family, type and protocol.
1229 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1230 * for the family and type is used.
1232 * The @protocol is a family and type specific int that specifies what
1233 * kind of protocol to use. #GSocketProtocol lists several common ones.
1234 * Many families only support one protocol, and use 0 for this, others
1235 * support several and using 0 means to use the default protocol for
1236 * the family and type.
1238 * The protocol id is passed directly to the operating
1239 * system, so you can use protocols not listed in #GSocketProtocol if you
1240 * know the protocol number used for it.
1242 * Returns: a #GSocket or %NULL on error.
1243 * Free the returned object with g_object_unref().
1248 g_socket_new (GSocketFamily family
,
1250 GSocketProtocol protocol
,
1253 return G_SOCKET (g_initable_new (G_TYPE_SOCKET
,
1257 "protocol", protocol
,
1262 * g_socket_new_from_fd:
1263 * @fd: a native socket file descriptor.
1264 * @error: #GError for error reporting, or %NULL to ignore.
1266 * Creates a new #GSocket from a native file descriptor
1267 * or winsock SOCKET handle.
1269 * This reads all the settings from the file descriptor so that
1270 * all properties should work. Note that the file descriptor
1271 * will be set to non-blocking mode, independent on the blocking
1272 * mode of the #GSocket.
1274 * On success, the returned #GSocket takes ownership of @fd. On failure, the
1275 * caller must close @fd themselves.
1277 * Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
1278 * descriptor. Instead, a GError will be set with code %G_IO_ERROR_FAILED
1280 * Returns: a #GSocket or %NULL on error.
1281 * Free the returned object with g_object_unref().
1286 g_socket_new_from_fd (gint fd
,
1289 return G_SOCKET (g_initable_new (G_TYPE_SOCKET
,
1296 * g_socket_set_blocking:
1297 * @socket: a #GSocket.
1298 * @blocking: Whether to use blocking I/O or not.
1300 * Sets the blocking mode of the socket. In blocking mode
1301 * all operations (which don’t take an explicit blocking parameter) block until
1302 * they succeed or there is an error. In
1303 * non-blocking mode all functions return results immediately or
1304 * with a %G_IO_ERROR_WOULD_BLOCK error.
1306 * All sockets are created in blocking mode. However, note that the
1307 * platform level socket is always non-blocking, and blocking mode
1308 * is a GSocket level feature.
1313 g_socket_set_blocking (GSocket
*socket
,
1316 g_return_if_fail (G_IS_SOCKET (socket
));
1318 blocking
= !!blocking
;
1320 if (socket
->priv
->blocking
== blocking
)
1323 socket
->priv
->blocking
= blocking
;
1324 g_object_notify (G_OBJECT (socket
), "blocking");
1328 * g_socket_get_blocking:
1329 * @socket: a #GSocket.
1331 * Gets the blocking mode of the socket. For details on blocking I/O,
1332 * see g_socket_set_blocking().
1334 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1339 g_socket_get_blocking (GSocket
*socket
)
1341 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
1343 return socket
->priv
->blocking
;
1347 * g_socket_set_keepalive:
1348 * @socket: a #GSocket.
1349 * @keepalive: Value for the keepalive flag
1351 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1352 * this flag is set on a socket, the system will attempt to verify that the
1353 * remote socket endpoint is still present if a sufficiently long period of
1354 * time passes with no data being exchanged. If the system is unable to
1355 * verify the presence of the remote endpoint, it will automatically close
1358 * This option is only functional on certain kinds of sockets. (Notably,
1359 * %G_SOCKET_PROTOCOL_TCP sockets.)
1361 * The exact time between pings is system- and protocol-dependent, but will
1362 * normally be at least two hours. Most commonly, you would set this flag
1363 * on a server socket if you want to allow clients to remain idle for long
1364 * periods of time, but also want to ensure that connections are eventually
1365 * garbage-collected if clients crash or become unreachable.
1370 g_socket_set_keepalive (GSocket
*socket
,
1373 GError
*error
= NULL
;
1375 g_return_if_fail (G_IS_SOCKET (socket
));
1377 keepalive
= !!keepalive
;
1378 if (socket
->priv
->keepalive
== keepalive
)
1381 if (!g_socket_set_option (socket
, SOL_SOCKET
, SO_KEEPALIVE
,
1384 g_warning ("error setting keepalive: %s", error
->message
);
1385 g_error_free (error
);
1389 socket
->priv
->keepalive
= keepalive
;
1390 g_object_notify (G_OBJECT (socket
), "keepalive");
1394 * g_socket_get_keepalive:
1395 * @socket: a #GSocket.
1397 * Gets the keepalive mode of the socket. For details on this,
1398 * see g_socket_set_keepalive().
1400 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1405 g_socket_get_keepalive (GSocket
*socket
)
1407 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
1409 return socket
->priv
->keepalive
;
1413 * g_socket_get_listen_backlog:
1414 * @socket: a #GSocket.
1416 * Gets the listen backlog setting of the socket. For details on this,
1417 * see g_socket_set_listen_backlog().
1419 * Returns: the maximum number of pending connections.
1424 g_socket_get_listen_backlog (GSocket
*socket
)
1426 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
1428 return socket
->priv
->listen_backlog
;
1432 * g_socket_set_listen_backlog:
1433 * @socket: a #GSocket.
1434 * @backlog: the maximum number of pending connections.
1436 * Sets the maximum number of outstanding connections allowed
1437 * when listening on this socket. If more clients than this are
1438 * connecting to the socket and the application is not handling them
1439 * on time then the new connections will be refused.
1441 * Note that this must be called before g_socket_listen() and has no
1442 * effect if called after that.
1447 g_socket_set_listen_backlog (GSocket
*socket
,
1450 g_return_if_fail (G_IS_SOCKET (socket
));
1451 g_return_if_fail (!socket
->priv
->listening
);
1453 if (backlog
!= socket
->priv
->listen_backlog
)
1455 socket
->priv
->listen_backlog
= backlog
;
1456 g_object_notify (G_OBJECT (socket
), "listen-backlog");
1461 * g_socket_get_timeout:
1462 * @socket: a #GSocket.
1464 * Gets the timeout setting of the socket. For details on this, see
1465 * g_socket_set_timeout().
1467 * Returns: the timeout in seconds
1472 g_socket_get_timeout (GSocket
*socket
)
1474 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
1476 return socket
->priv
->timeout
;
1480 * g_socket_set_timeout:
1481 * @socket: a #GSocket.
1482 * @timeout: the timeout for @socket, in seconds, or 0 for none
1484 * Sets the time in seconds after which I/O operations on @socket will
1485 * time out if they have not yet completed.
1487 * On a blocking socket, this means that any blocking #GSocket
1488 * operation will time out after @timeout seconds of inactivity,
1489 * returning %G_IO_ERROR_TIMED_OUT.
1491 * On a non-blocking socket, calls to g_socket_condition_wait() will
1492 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1493 * created with g_socket_create_source() will trigger after
1494 * @timeout seconds of inactivity, with the requested condition
1495 * set, at which point calling g_socket_receive(), g_socket_send(),
1496 * g_socket_check_connect_result(), etc, will fail with
1497 * %G_IO_ERROR_TIMED_OUT.
1499 * If @timeout is 0 (the default), operations will never time out
1502 * Note that if an I/O operation is interrupted by a signal, this may
1503 * cause the timeout to be reset.
1508 g_socket_set_timeout (GSocket
*socket
,
1511 g_return_if_fail (G_IS_SOCKET (socket
));
1513 if (timeout
!= socket
->priv
->timeout
)
1515 socket
->priv
->timeout
= timeout
;
1516 g_object_notify (G_OBJECT (socket
), "timeout");
1522 * @socket: a #GSocket.
1524 * Gets the unicast time-to-live setting on @socket; see
1525 * g_socket_set_ttl() for more details.
1527 * Returns: the time-to-live setting on @socket
1532 g_socket_get_ttl (GSocket
*socket
)
1534 GError
*error
= NULL
;
1537 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
1539 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1541 g_socket_get_option (socket
, IPPROTO_IP
, IP_TTL
,
1544 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1546 g_socket_get_option (socket
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
,
1550 g_return_val_if_reached (0);
1554 g_warning ("error getting unicast ttl: %s", error
->message
);
1555 g_error_free (error
);
1564 * @socket: a #GSocket.
1565 * @ttl: the time-to-live value for all unicast packets on @socket
1567 * Sets the time-to-live for outgoing unicast packets on @socket.
1568 * By default the platform-specific default value is used.
1573 g_socket_set_ttl (GSocket
*socket
,
1576 GError
*error
= NULL
;
1578 g_return_if_fail (G_IS_SOCKET (socket
));
1580 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1582 g_socket_set_option (socket
, IPPROTO_IP
, IP_TTL
,
1585 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1587 g_socket_set_option (socket
, IPPROTO_IP
, IP_TTL
,
1589 g_socket_set_option (socket
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
,
1593 g_return_if_reached ();
1597 g_warning ("error setting unicast ttl: %s", error
->message
);
1598 g_error_free (error
);
1602 g_object_notify (G_OBJECT (socket
), "ttl");
1606 * g_socket_get_broadcast:
1607 * @socket: a #GSocket.
1609 * Gets the broadcast setting on @socket; if %TRUE,
1610 * it is possible to send packets to broadcast
1613 * Returns: the broadcast setting on @socket
1618 g_socket_get_broadcast (GSocket
*socket
)
1620 GError
*error
= NULL
;
1623 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
1625 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_BROADCAST
,
1628 g_warning ("error getting broadcast: %s", error
->message
);
1629 g_error_free (error
);
1637 * g_socket_set_broadcast:
1638 * @socket: a #GSocket.
1639 * @broadcast: whether @socket should allow sending to broadcast
1642 * Sets whether @socket should allow sending to broadcast addresses.
1643 * This is %FALSE by default.
1648 g_socket_set_broadcast (GSocket
*socket
,
1651 GError
*error
= NULL
;
1653 g_return_if_fail (G_IS_SOCKET (socket
));
1655 broadcast
= !!broadcast
;
1657 if (!g_socket_set_option (socket
, SOL_SOCKET
, SO_BROADCAST
,
1660 g_warning ("error setting broadcast: %s", error
->message
);
1661 g_error_free (error
);
1665 g_object_notify (G_OBJECT (socket
), "broadcast");
1669 * g_socket_get_multicast_loopback:
1670 * @socket: a #GSocket.
1672 * Gets the multicast loopback setting on @socket; if %TRUE (the
1673 * default), outgoing multicast packets will be looped back to
1674 * multicast listeners on the same host.
1676 * Returns: the multicast loopback setting on @socket
1681 g_socket_get_multicast_loopback (GSocket
*socket
)
1683 GError
*error
= NULL
;
1686 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
1688 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1690 g_socket_get_option (socket
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
1693 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1695 g_socket_get_option (socket
, IPPROTO_IPV6
, IPV6_MULTICAST_LOOP
,
1699 g_return_val_if_reached (FALSE
);
1703 g_warning ("error getting multicast loopback: %s", error
->message
);
1704 g_error_free (error
);
1712 * g_socket_set_multicast_loopback:
1713 * @socket: a #GSocket.
1714 * @loopback: whether @socket should receive messages sent to its
1715 * multicast groups from the local host
1717 * Sets whether outgoing multicast packets will be received by sockets
1718 * listening on that multicast address on the same host. This is %TRUE
1724 g_socket_set_multicast_loopback (GSocket
*socket
,
1727 GError
*error
= NULL
;
1729 g_return_if_fail (G_IS_SOCKET (socket
));
1731 loopback
= !!loopback
;
1733 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1735 g_socket_set_option (socket
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
1738 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1740 g_socket_set_option (socket
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
1742 g_socket_set_option (socket
, IPPROTO_IPV6
, IPV6_MULTICAST_LOOP
,
1746 g_return_if_reached ();
1750 g_warning ("error setting multicast loopback: %s", error
->message
);
1751 g_error_free (error
);
1755 g_object_notify (G_OBJECT (socket
), "multicast-loopback");
1759 * g_socket_get_multicast_ttl:
1760 * @socket: a #GSocket.
1762 * Gets the multicast time-to-live setting on @socket; see
1763 * g_socket_set_multicast_ttl() for more details.
1765 * Returns: the multicast time-to-live setting on @socket
1770 g_socket_get_multicast_ttl (GSocket
*socket
)
1772 GError
*error
= NULL
;
1775 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
1777 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1779 g_socket_get_option (socket
, IPPROTO_IP
, IP_MULTICAST_TTL
,
1782 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1784 g_socket_get_option (socket
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
,
1788 g_return_val_if_reached (FALSE
);
1792 g_warning ("error getting multicast ttl: %s", error
->message
);
1793 g_error_free (error
);
1801 * g_socket_set_multicast_ttl:
1802 * @socket: a #GSocket.
1803 * @ttl: the time-to-live value for all multicast datagrams on @socket
1805 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1806 * By default, this is 1, meaning that multicast packets will not leave
1807 * the local network.
1812 g_socket_set_multicast_ttl (GSocket
*socket
,
1815 GError
*error
= NULL
;
1817 g_return_if_fail (G_IS_SOCKET (socket
));
1819 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1821 g_socket_set_option (socket
, IPPROTO_IP
, IP_MULTICAST_TTL
,
1824 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1826 g_socket_set_option (socket
, IPPROTO_IP
, IP_MULTICAST_TTL
,
1828 g_socket_set_option (socket
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
,
1832 g_return_if_reached ();
1836 g_warning ("error setting multicast ttl: %s", error
->message
);
1837 g_error_free (error
);
1841 g_object_notify (G_OBJECT (socket
), "multicast-ttl");
1845 * g_socket_get_family:
1846 * @socket: a #GSocket.
1848 * Gets the socket family of the socket.
1850 * Returns: a #GSocketFamily
1855 g_socket_get_family (GSocket
*socket
)
1857 g_return_val_if_fail (G_IS_SOCKET (socket
), G_SOCKET_FAMILY_INVALID
);
1859 return socket
->priv
->family
;
1863 * g_socket_get_socket_type:
1864 * @socket: a #GSocket.
1866 * Gets the socket type of the socket.
1868 * Returns: a #GSocketType
1873 g_socket_get_socket_type (GSocket
*socket
)
1875 g_return_val_if_fail (G_IS_SOCKET (socket
), G_SOCKET_TYPE_INVALID
);
1877 return socket
->priv
->type
;
1881 * g_socket_get_protocol:
1882 * @socket: a #GSocket.
1884 * Gets the socket protocol id the socket was created with.
1885 * In case the protocol is unknown, -1 is returned.
1887 * Returns: a protocol id, or -1 if unknown
1892 g_socket_get_protocol (GSocket
*socket
)
1894 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
1896 return socket
->priv
->protocol
;
1901 * @socket: a #GSocket.
1903 * Returns the underlying OS socket object. On unix this
1904 * is a socket file descriptor, and on Windows this is
1905 * a Winsock2 SOCKET handle. This may be useful for
1906 * doing platform specific or otherwise unusual operations
1909 * Returns: the file descriptor of the socket.
1914 g_socket_get_fd (GSocket
*socket
)
1916 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
1918 return socket
->priv
->fd
;
1922 * g_socket_get_local_address:
1923 * @socket: a #GSocket.
1924 * @error: #GError for error reporting, or %NULL to ignore.
1926 * Try to get the local address of a bound socket. This is only
1927 * useful if the socket has been bound to a local address,
1928 * either explicitly or implicitly when connecting.
1930 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1931 * Free the returned object with g_object_unref().
1936 g_socket_get_local_address (GSocket
*socket
,
1939 struct sockaddr_storage buffer
;
1940 guint len
= sizeof (buffer
);
1942 g_return_val_if_fail (G_IS_SOCKET (socket
), NULL
);
1944 if (getsockname (socket
->priv
->fd
, (struct sockaddr
*) &buffer
, &len
) < 0)
1946 int errsv
= get_socket_errno ();
1947 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
1948 _("could not get local address: %s"), socket_strerror (errsv
));
1952 return g_socket_address_new_from_native (&buffer
, len
);
1956 * g_socket_get_remote_address:
1957 * @socket: a #GSocket.
1958 * @error: #GError for error reporting, or %NULL to ignore.
1960 * Try to get the remote address of a connected socket. This is only
1961 * useful for connection oriented sockets that have been connected.
1963 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1964 * Free the returned object with g_object_unref().
1969 g_socket_get_remote_address (GSocket
*socket
,
1972 struct sockaddr_storage buffer
;
1973 guint len
= sizeof (buffer
);
1975 g_return_val_if_fail (G_IS_SOCKET (socket
), NULL
);
1977 if (socket
->priv
->connect_pending
)
1979 if (!g_socket_check_connect_result (socket
, error
))
1982 socket
->priv
->connect_pending
= FALSE
;
1985 if (!socket
->priv
->remote_address
)
1987 if (getpeername (socket
->priv
->fd
, (struct sockaddr
*) &buffer
, &len
) < 0)
1989 int errsv
= get_socket_errno ();
1990 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
1991 _("could not get remote address: %s"), socket_strerror (errsv
));
1995 socket
->priv
->remote_address
= g_socket_address_new_from_native (&buffer
, len
);
1998 return g_object_ref (socket
->priv
->remote_address
);
2002 * g_socket_is_connected:
2003 * @socket: a #GSocket.
2005 * Check whether the socket is connected. This is only useful for
2006 * connection-oriented sockets.
2008 * If using g_socket_shutdown(), this function will return %TRUE until the
2009 * socket has been shut down for reading and writing. If you do a non-blocking
2010 * connect, this function will not return %TRUE until after you call
2011 * g_socket_check_connect_result().
2013 * Returns: %TRUE if socket is connected, %FALSE otherwise.
2018 g_socket_is_connected (GSocket
*socket
)
2020 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2022 return (socket
->priv
->connected_read
|| socket
->priv
->connected_write
);
2027 * @socket: a #GSocket.
2028 * @error: #GError for error reporting, or %NULL to ignore.
2030 * Marks the socket as a server socket, i.e. a socket that is used
2031 * to accept incoming requests using g_socket_accept().
2033 * Before calling this the socket must be bound to a local address using
2036 * To set the maximum amount of outstanding clients, use
2037 * g_socket_set_listen_backlog().
2039 * Returns: %TRUE on success, %FALSE on error.
2044 g_socket_listen (GSocket
*socket
,
2047 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2049 if (!check_socket (socket
, error
))
2052 if (listen (socket
->priv
->fd
, socket
->priv
->listen_backlog
) < 0)
2054 int errsv
= get_socket_errno ();
2056 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
2057 _("could not listen: %s"), socket_strerror (errsv
));
2061 socket
->priv
->listening
= TRUE
;
2068 * @socket: a #GSocket.
2069 * @address: a #GSocketAddress specifying the local address.
2070 * @allow_reuse: whether to allow reusing this address
2071 * @error: #GError for error reporting, or %NULL to ignore.
2073 * When a socket is created it is attached to an address family, but it
2074 * doesn't have an address in this family. g_socket_bind() assigns the
2075 * address (sometimes called name) of the socket.
2077 * It is generally required to bind to a local address before you can
2078 * receive connections. (See g_socket_listen() and g_socket_accept() ).
2079 * In certain situations, you may also want to bind a socket that will be
2080 * used to initiate connections, though this is not normally required.
2082 * If @socket is a TCP socket, then @allow_reuse controls the setting
2083 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
2084 * server sockets (sockets that you will eventually call
2085 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
2086 * set this flag on a server socket may cause g_socket_bind() to return
2087 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
2088 * immediately restarted.)
2090 * If @socket is a UDP socket, then @allow_reuse determines whether or
2091 * not other UDP sockets can be bound to the same address at the same
2092 * time. In particular, you can have several UDP sockets bound to the
2093 * same address, and they will all receive all of the multicast and
2094 * broadcast packets sent to that address. (The behavior of unicast
2095 * UDP packets to an address with multiple listeners is not defined.)
2097 * Returns: %TRUE on success, %FALSE on error.
2102 g_socket_bind (GSocket
*socket
,
2103 GSocketAddress
*address
,
2104 gboolean reuse_address
,
2107 struct sockaddr_storage addr
;
2108 gboolean so_reuseaddr
;
2110 gboolean so_reuseport
;
2113 g_return_val_if_fail (G_IS_SOCKET (socket
) && G_IS_SOCKET_ADDRESS (address
), FALSE
);
2115 if (!check_socket (socket
, error
))
2118 if (!g_socket_address_to_native (address
, &addr
, sizeof addr
, error
))
2121 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
2122 * sockets, but has nasty side effects we don't want for TCP
2125 * On other platforms, we set SO_REUSEPORT, if it exists, for
2126 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
2127 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
2128 * the desired semantics on UDP (as it does on Linux, although
2129 * Linux has SO_REUSEPORT too as of 3.9).
2133 so_reuseaddr
= reuse_address
&& (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
);
2135 so_reuseaddr
= !!reuse_address
;
2139 so_reuseport
= reuse_address
&& (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
);
2142 /* Ignore errors here, the only likely error is "not supported", and
2143 * this is a "best effort" thing mainly.
2145 g_socket_set_option (socket
, SOL_SOCKET
, SO_REUSEADDR
, so_reuseaddr
, NULL
);
2147 g_socket_set_option (socket
, SOL_SOCKET
, SO_REUSEPORT
, so_reuseport
, NULL
);
2150 if (bind (socket
->priv
->fd
, (struct sockaddr
*) &addr
,
2151 g_socket_address_get_native_size (address
)) < 0)
2153 int errsv
= get_socket_errno ();
2155 G_IO_ERROR
, socket_io_error_from_errno (errsv
),
2156 _("Error binding to address: %s"), socket_strerror (errsv
));
2164 g_socket_multicast_group_operation (GSocket
*socket
,
2165 GInetAddress
*group
,
2166 gboolean source_specific
,
2168 gboolean join_group
,
2171 const guint8
*native_addr
;
2172 gint optname
, result
;
2174 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2175 g_return_val_if_fail (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
, FALSE
);
2176 g_return_val_if_fail (G_IS_INET_ADDRESS (group
), FALSE
);
2178 if (!check_socket (socket
, error
))
2181 native_addr
= g_inet_address_to_bytes (group
);
2182 if (g_inet_address_get_family (group
) == G_SOCKET_FAMILY_IPV4
)
2184 #ifdef HAVE_IP_MREQN
2185 struct ip_mreqn mc_req
;
2187 struct ip_mreq mc_req
;
2190 memset (&mc_req
, 0, sizeof (mc_req
));
2191 memcpy (&mc_req
.imr_multiaddr
, native_addr
, sizeof (struct in_addr
));
2193 #ifdef HAVE_IP_MREQN
2195 mc_req
.imr_ifindex
= if_nametoindex (iface
);
2197 mc_req
.imr_ifindex
= 0; /* Pick any. */
2198 #elif defined(G_OS_WIN32)
2200 mc_req
.imr_interface
.s_addr
= g_htonl (if_nametoindex (iface
));
2202 mc_req
.imr_interface
.s_addr
= g_htonl (INADDR_ANY
);
2204 mc_req
.imr_interface
.s_addr
= g_htonl (INADDR_ANY
);
2207 if (source_specific
)
2209 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2210 optname
= join_group
? IP_ADD_SOURCE_MEMBERSHIP
: IP_DROP_SOURCE_MEMBERSHIP
;
2212 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
2214 _("Error joining multicast group: %s") :
2215 _("Error leaving multicast group: %s"),
2216 _("No support for source-specific multicast"));
2221 optname
= join_group
? IP_ADD_MEMBERSHIP
: IP_DROP_MEMBERSHIP
;
2222 result
= setsockopt (socket
->priv
->fd
, IPPROTO_IP
, optname
,
2223 &mc_req
, sizeof (mc_req
));
2225 else if (g_inet_address_get_family (group
) == G_SOCKET_FAMILY_IPV6
)
2227 struct ipv6_mreq mc_req_ipv6
;
2229 memset (&mc_req_ipv6
, 0, sizeof (mc_req_ipv6
));
2230 memcpy (&mc_req_ipv6
.ipv6mr_multiaddr
, native_addr
, sizeof (struct in6_addr
));
2231 #ifdef HAVE_IF_NAMETOINDEX
2233 mc_req_ipv6
.ipv6mr_interface
= if_nametoindex (iface
);
2236 mc_req_ipv6
.ipv6mr_interface
= 0;
2238 optname
= join_group
? IPV6_JOIN_GROUP
: IPV6_LEAVE_GROUP
;
2239 result
= setsockopt (socket
->priv
->fd
, IPPROTO_IPV6
, optname
,
2240 &mc_req_ipv6
, sizeof (mc_req_ipv6
));
2243 g_return_val_if_reached (FALSE
);
2247 int errsv
= get_socket_errno ();
2249 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
2251 _("Error joining multicast group: %s") :
2252 _("Error leaving multicast group: %s"),
2253 socket_strerror (errsv
));
2261 * g_socket_join_multicast_group:
2262 * @socket: a #GSocket.
2263 * @group: a #GInetAddress specifying the group address to join.
2264 * @iface: (nullable): Name of the interface to use, or %NULL
2265 * @source_specific: %TRUE if source-specific multicast should be used
2266 * @error: #GError for error reporting, or %NULL to ignore.
2268 * Registers @socket to receive multicast messages sent to @group.
2269 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2270 * been bound to an appropriate interface and port with
2273 * If @iface is %NULL, the system will automatically pick an interface
2274 * to bind to based on @group.
2276 * If @source_specific is %TRUE, source-specific multicast as defined
2277 * in RFC 4604 is used. Note that on older platforms this may fail
2278 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2280 * To bind to a given source-specific multicast address, use
2281 * g_socket_join_multicast_group_ssm() instead.
2283 * Returns: %TRUE on success, %FALSE on error.
2288 g_socket_join_multicast_group (GSocket
*socket
,
2289 GInetAddress
*group
,
2290 gboolean source_specific
,
2294 return g_socket_multicast_group_operation (socket
, group
, source_specific
, iface
, TRUE
, error
);
2298 * g_socket_leave_multicast_group:
2299 * @socket: a #GSocket.
2300 * @group: a #GInetAddress specifying the group address to leave.
2301 * @iface: (nullable): Interface used
2302 * @source_specific: %TRUE if source-specific multicast was used
2303 * @error: #GError for error reporting, or %NULL to ignore.
2305 * Removes @socket from the multicast group defined by @group, @iface,
2306 * and @source_specific (which must all have the same values they had
2307 * when you joined the group).
2309 * @socket remains bound to its address and port, and can still receive
2310 * unicast messages after calling this.
2312 * To unbind to a given source-specific multicast address, use
2313 * g_socket_leave_multicast_group_ssm() instead.
2315 * Returns: %TRUE on success, %FALSE on error.
2320 g_socket_leave_multicast_group (GSocket
*socket
,
2321 GInetAddress
*group
,
2322 gboolean source_specific
,
2326 return g_socket_multicast_group_operation (socket
, group
, source_specific
, iface
, FALSE
, error
);
2330 g_socket_multicast_group_operation_ssm (GSocket
*socket
,
2331 GInetAddress
*group
,
2332 GInetAddress
*source_specific
,
2334 gboolean join_group
,
2339 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2340 g_return_val_if_fail (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
, FALSE
);
2341 g_return_val_if_fail (G_IS_INET_ADDRESS (group
), FALSE
);
2342 g_return_val_if_fail (iface
== NULL
|| *iface
!= '\0', FALSE
);
2343 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, FALSE
);
2345 if (!source_specific
)
2347 return g_socket_multicast_group_operation (socket
, group
, FALSE
, iface
,
2351 if (!check_socket (socket
, error
))
2354 switch (g_inet_address_get_family (group
))
2356 case G_SOCKET_FAMILY_INVALID
:
2357 case G_SOCKET_FAMILY_UNIX
:
2359 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
2361 _("Error joining multicast group: %s") :
2362 _("Error leaving multicast group: %s"),
2363 _("Unsupported socket family"));
2368 case G_SOCKET_FAMILY_IPV4
:
2370 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2372 struct ip_mreq_source mc_req_src
;
2374 if (g_inet_address_get_family (source_specific
) !=
2375 G_SOCKET_FAMILY_IPV4
)
2377 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
2379 _("Error joining multicast group: %s") :
2380 _("Error leaving multicast group: %s"),
2381 _("source-specific not an IPv4 address"));
2385 memset (&mc_req_src
, 0, sizeof (mc_req_src
));
2387 /* By default use the default IPv4 multicast interface. */
2388 mc_req_src
.imr_interface
.s_addr
= g_htonl (INADDR_ANY
);
2392 #if defined(G_OS_WIN32) && defined (HAVE_IF_NAMETOINDEX)
2393 guint iface_index
= if_nametoindex (iface
);
2394 if (iface_index
== 0)
2398 g_set_error (error
, G_IO_ERROR
, g_io_error_from_errno (errsv
),
2399 _("Interface not found: %s"), g_strerror (errsv
));
2402 /* (0.0.0.iface_index) only works on Windows. */
2403 mc_req_src
.imr_interface
.s_addr
= g_htonl (iface_index
);
2404 #elif defined (HAVE_SIOCGIFADDR)
2407 struct sockaddr_in
*iface_addr
;
2408 size_t if_name_len
= strlen (iface
);
2410 memset (&ifr
, 0, sizeof (ifr
));
2412 if (if_name_len
>= sizeof (ifr
.ifr_name
))
2414 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_FILENAME_TOO_LONG
,
2415 _("Interface name too long"));
2419 memcpy (ifr
.ifr_name
, iface
, if_name_len
);
2421 /* Get the IPv4 address of the given network interface name. */
2422 ret
= ioctl (socket
->priv
->fd
, SIOCGIFADDR
, &ifr
);
2427 g_set_error (error
, G_IO_ERROR
, g_io_error_from_errno (errsv
),
2428 _("Interface not found: %s"), g_strerror (errsv
));
2432 iface_addr
= (struct sockaddr_in
*) &ifr
.ifr_addr
;
2433 mc_req_src
.imr_interface
.s_addr
= iface_addr
->sin_addr
.s_addr
;
2434 #endif /* defined(G_OS_WIN32) && defined (HAVE_IF_NAMETOINDEX) */
2436 memcpy (&mc_req_src
.imr_multiaddr
, g_inet_address_to_bytes (group
),
2437 g_inet_address_get_native_size (group
));
2438 memcpy (&mc_req_src
.imr_sourceaddr
,
2439 g_inet_address_to_bytes (source_specific
),
2440 g_inet_address_get_native_size (source_specific
));
2443 join_group
? IP_ADD_SOURCE_MEMBERSHIP
: IP_DROP_SOURCE_MEMBERSHIP
;
2444 result
= setsockopt (socket
->priv
->fd
, IPPROTO_IP
, optname
,
2445 &mc_req_src
, sizeof (mc_req_src
));
2447 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
2449 _("Error joining multicast group: %s") :
2450 _("Error leaving multicast group: %s"),
2451 _("No support for IPv4 source-specific multicast"));
2453 #endif /* IP_ADD_SOURCE_MEMBERSHIP */
2457 case G_SOCKET_FAMILY_IPV6
:
2459 #ifdef MCAST_JOIN_SOURCE_GROUP
2462 struct group_source_req mc_req_src
;
2463 GSocketAddress
*saddr_group
, *saddr_source_specific
;
2464 guint iface_index
= 0;
2466 #if defined (HAVE_IF_NAMETOINDEX)
2469 iface_index
= if_nametoindex (iface
);
2470 if (iface_index
== 0)
2474 g_set_error (error
, G_IO_ERROR
, g_io_error_from_errno (errsv
),
2475 _("Interface not found: %s"), g_strerror (errsv
));
2479 #endif /* defined (HAVE_IF_NAMETOINDEX) */
2480 mc_req_src
.gsr_interface
= iface_index
;
2482 saddr_group
= g_inet_socket_address_new (group
, 0);
2483 res
= g_socket_address_to_native (saddr_group
, &mc_req_src
.gsr_group
,
2484 sizeof (mc_req_src
.gsr_group
),
2486 g_object_unref (saddr_group
);
2490 saddr_source_specific
= g_inet_socket_address_new (source_specific
, 0);
2491 res
= g_socket_address_to_native (saddr_source_specific
,
2492 &mc_req_src
.gsr_source
,
2493 sizeof (mc_req_src
.gsr_source
),
2495 g_object_unref (saddr_source_specific
);
2501 join_group
? MCAST_JOIN_SOURCE_GROUP
: MCAST_LEAVE_SOURCE_GROUP
;
2502 result
= setsockopt (socket
->priv
->fd
, IPPROTO_IPV6
, optname
,
2503 &mc_req_src
, sizeof (mc_req_src
));
2505 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
2507 _("Error joining multicast group: %s") :
2508 _("Error leaving multicast group: %s"),
2509 _("No support for IPv6 source-specific multicast"));
2511 #endif /* MCAST_JOIN_SOURCE_GROUP */
2516 g_return_val_if_reached (FALSE
);
2521 int errsv
= get_socket_errno ();
2523 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
2525 _("Error joining multicast group: %s") :
2526 _("Error leaving multicast group: %s"),
2527 socket_strerror (errsv
));
2535 * g_socket_join_multicast_group_ssm:
2536 * @socket: a #GSocket.
2537 * @group: a #GInetAddress specifying the group address to join.
2538 * @source_specific: (nullable): a #GInetAddress specifying the
2539 * source-specific multicast address or %NULL to ignore.
2540 * @iface: (nullable): Name of the interface to use, or %NULL
2541 * @error: #GError for error reporting, or %NULL to ignore.
2543 * Registers @socket to receive multicast messages sent to @group.
2544 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2545 * been bound to an appropriate interface and port with
2548 * If @iface is %NULL, the system will automatically pick an interface
2549 * to bind to based on @group.
2551 * If @source_specific is not %NULL, use source-specific multicast as
2552 * defined in RFC 4604. Note that on older platforms this may fail
2553 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2555 * Note that this function can be called multiple times for the same
2556 * @group with different @source_specific in order to receive multicast
2557 * packets from more than one source.
2559 * Returns: %TRUE on success, %FALSE on error.
2564 g_socket_join_multicast_group_ssm (GSocket
*socket
,
2565 GInetAddress
*group
,
2566 GInetAddress
*source_specific
,
2570 return g_socket_multicast_group_operation_ssm (socket
, group
,
2571 source_specific
, iface
, TRUE
, error
);
2575 * g_socket_leave_multicast_group_ssm:
2576 * @socket: a #GSocket.
2577 * @group: a #GInetAddress specifying the group address to leave.
2578 * @source_specific: (nullable): a #GInetAddress specifying the
2579 * source-specific multicast address or %NULL to ignore.
2580 * @iface: (nullable): Name of the interface to use, or %NULL
2581 * @error: #GError for error reporting, or %NULL to ignore.
2583 * Removes @socket from the multicast group defined by @group, @iface,
2584 * and @source_specific (which must all have the same values they had
2585 * when you joined the group).
2587 * @socket remains bound to its address and port, and can still receive
2588 * unicast messages after calling this.
2590 * Returns: %TRUE on success, %FALSE on error.
2595 g_socket_leave_multicast_group_ssm (GSocket
*socket
,
2596 GInetAddress
*group
,
2597 GInetAddress
*source_specific
,
2601 return g_socket_multicast_group_operation_ssm (socket
, group
,
2602 source_specific
, iface
, FALSE
, error
);
2606 * g_socket_speaks_ipv4:
2607 * @socket: a #GSocket
2609 * Checks if a socket is capable of speaking IPv4.
2611 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2612 * and under some combinations of circumstances IPv6 sockets are also
2613 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2616 * No other types of sockets are currently considered as being capable
2619 * Returns: %TRUE if this socket can be used with IPv4.
2624 g_socket_speaks_ipv4 (GSocket
*socket
)
2626 switch (socket
->priv
->family
)
2628 case G_SOCKET_FAMILY_IPV4
:
2631 case G_SOCKET_FAMILY_IPV6
:
2632 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2636 if (!g_socket_get_option (socket
,
2637 IPPROTO_IPV6
, IPV6_V6ONLY
,
2654 * @socket: a #GSocket.
2655 * @cancellable: (nullable): a %GCancellable or %NULL
2656 * @error: #GError for error reporting, or %NULL to ignore.
2658 * Accept incoming connections on a connection-based socket. This removes
2659 * the first outstanding connection request from the listening socket and
2660 * creates a #GSocket object for it.
2662 * The @socket must be bound to a local address with g_socket_bind() and
2663 * must be listening for incoming connections (g_socket_listen()).
2665 * If there are no outstanding connections then the operation will block
2666 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2667 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2669 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2670 * Free the returned object with g_object_unref().
2675 g_socket_accept (GSocket
*socket
,
2676 GCancellable
*cancellable
,
2679 GSocket
*new_socket
;
2682 g_return_val_if_fail (G_IS_SOCKET (socket
), NULL
);
2684 if (!check_socket (socket
, error
))
2687 if (!check_timeout (socket
, error
))
2692 win32_unset_event_mask (socket
, FD_ACCEPT
);
2694 if ((ret
= accept (socket
->priv
->fd
, NULL
, 0)) < 0)
2696 int errsv
= get_socket_errno ();
2701 #ifdef WSAEWOULDBLOCK
2702 if (errsv
== WSAEWOULDBLOCK
)
2704 if (errsv
== EWOULDBLOCK
||
2708 if (socket
->priv
->blocking
)
2710 if (!g_socket_condition_wait (socket
,
2711 G_IO_IN
, cancellable
, error
))
2718 socket_set_error_lazy (error
, errsv
, _("Error accepting connection: %s"));
2726 /* The socket inherits the accepting sockets event mask and even object,
2727 we need to remove that */
2728 WSAEventSelect (ret
, NULL
, 0);
2734 /* We always want to set close-on-exec to protect users. If you
2735 need to so some weird inheritance to exec you can re-enable this
2736 using lower level hacks with g_socket_get_fd(). */
2737 flags
= fcntl (ret
, F_GETFD
, 0);
2739 (flags
& FD_CLOEXEC
) == 0)
2741 flags
|= FD_CLOEXEC
;
2742 fcntl (ret
, F_SETFD
, flags
);
2747 new_socket
= g_socket_new_from_fd (ret
, error
);
2748 if (new_socket
== NULL
)
2757 new_socket
->priv
->protocol
= socket
->priv
->protocol
;
2764 * @socket: a #GSocket.
2765 * @address: a #GSocketAddress specifying the remote address.
2766 * @cancellable: (nullable): a %GCancellable or %NULL
2767 * @error: #GError for error reporting, or %NULL to ignore.
2769 * Connect the socket to the specified remote address.
2771 * For connection oriented socket this generally means we attempt to make
2772 * a connection to the @address. For a connection-less socket it sets
2773 * the default address for g_socket_send() and discards all incoming datagrams
2774 * from other sources.
2776 * Generally connection oriented sockets can only connect once, but
2777 * connection-less sockets can connect multiple times to change the
2780 * If the connect call needs to do network I/O it will block, unless
2781 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2782 * and the user can be notified of the connection finishing by waiting
2783 * for the G_IO_OUT condition. The result of the connection must then be
2784 * checked with g_socket_check_connect_result().
2786 * Returns: %TRUE if connected, %FALSE on error.
2791 g_socket_connect (GSocket
*socket
,
2792 GSocketAddress
*address
,
2793 GCancellable
*cancellable
,
2796 struct sockaddr_storage buffer
;
2798 g_return_val_if_fail (G_IS_SOCKET (socket
) && G_IS_SOCKET_ADDRESS (address
), FALSE
);
2800 if (!check_socket (socket
, error
))
2803 if (!g_socket_address_to_native (address
, &buffer
, sizeof buffer
, error
))
2806 if (socket
->priv
->remote_address
)
2807 g_object_unref (socket
->priv
->remote_address
);
2808 socket
->priv
->remote_address
= g_object_ref (address
);
2812 win32_unset_event_mask (socket
, FD_CONNECT
);
2814 if (connect (socket
->priv
->fd
, (struct sockaddr
*) &buffer
,
2815 g_socket_address_get_native_size (address
)) < 0)
2817 int errsv
= get_socket_errno ();
2823 if (errsv
== EINPROGRESS
)
2825 if (errsv
== WSAEWOULDBLOCK
)
2828 if (socket
->priv
->blocking
)
2830 if (g_socket_condition_wait (socket
, G_IO_OUT
, cancellable
, error
))
2832 if (g_socket_check_connect_result (socket
, error
))
2838 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_PENDING
,
2839 _("Connection in progress"));
2840 socket
->priv
->connect_pending
= TRUE
;
2844 g_set_error_literal (error
, G_IO_ERROR
,
2845 socket_io_error_from_errno (errsv
),
2846 socket_strerror (errsv
));
2853 socket
->priv
->connected_read
= TRUE
;
2854 socket
->priv
->connected_write
= TRUE
;
2860 * g_socket_check_connect_result:
2861 * @socket: a #GSocket
2862 * @error: #GError for error reporting, or %NULL to ignore.
2864 * Checks and resets the pending connect error for the socket.
2865 * This is used to check for errors when g_socket_connect() is
2866 * used in non-blocking mode.
2868 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2873 g_socket_check_connect_result (GSocket
*socket
,
2878 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2880 if (!check_socket (socket
, error
))
2883 if (!check_timeout (socket
, error
))
2886 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_ERROR
, &value
, error
))
2888 g_prefix_error (error
, _("Unable to get pending error: "));
2894 g_set_error_literal (error
, G_IO_ERROR
, socket_io_error_from_errno (value
),
2895 socket_strerror (value
));
2896 if (socket
->priv
->remote_address
)
2898 g_object_unref (socket
->priv
->remote_address
);
2899 socket
->priv
->remote_address
= NULL
;
2904 socket
->priv
->connected_read
= TRUE
;
2905 socket
->priv
->connected_write
= TRUE
;
2911 * g_socket_get_available_bytes:
2912 * @socket: a #GSocket
2914 * Get the amount of data pending in the OS input buffer, without blocking.
2916 * If @socket is a UDP or SCTP socket, this will return the size of
2917 * just the next packet, even if additional packets are buffered after
2920 * Note that on Windows, this function is rather inefficient in the
2921 * UDP case, and so if you know any plausible upper bound on the size
2922 * of the incoming packet, it is better to just do a
2923 * g_socket_receive() with a buffer of that size, rather than calling
2924 * g_socket_get_available_bytes() first and then doing a receive of
2925 * exactly the right size.
2927 * Returns: the number of bytes that can be read from the socket
2928 * without blocking or truncating, or -1 on error.
2933 g_socket_get_available_bytes (GSocket
*socket
)
2936 const gint bufsize
= 64 * 1024;
2937 static guchar
*buf
= NULL
;
2943 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
2945 #if defined (SO_NREAD)
2946 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_NREAD
, &avail
, NULL
))
2948 #elif !defined (G_OS_WIN32)
2949 if (ioctl (socket
->priv
->fd
, FIONREAD
, &avail
) < 0)
2952 if (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
)
2954 if (G_UNLIKELY (g_once_init_enter (&buf
)))
2955 g_once_init_leave (&buf
, g_malloc (bufsize
));
2957 avail
= recv (socket
->priv
->fd
, buf
, bufsize
, MSG_PEEK
);
2958 if (avail
== -1 && get_socket_errno () == WSAEWOULDBLOCK
)
2963 if (ioctlsocket (socket
->priv
->fd
, FIONREAD
, &avail
) < 0)
2971 /* Block on a timed wait for @condition until (@start_time + @timeout).
2972 * Return %G_IO_ERROR_TIMED_OUT if the timeout is reached; otherwise %TRUE.
2975 block_on_timeout (GSocket
*socket
,
2976 GIOCondition condition
,
2979 GCancellable
*cancellable
,
2982 gint64 wait_timeout
= -1;
2984 g_return_val_if_fail (timeout
!= 0, TRUE
);
2986 /* check if we've timed out or how much time to wait at most */
2989 gint64 elapsed
= g_get_monotonic_time () - start_time
;
2991 if (elapsed
>= timeout
)
2993 g_set_error_literal (error
,
2994 G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
,
2995 _("Socket I/O timed out"));
2999 wait_timeout
= timeout
- elapsed
;
3002 return g_socket_condition_timed_wait (socket
, condition
, wait_timeout
,
3003 cancellable
, error
);
3007 g_socket_receive_with_timeout (GSocket
*socket
,
3011 GCancellable
*cancellable
,
3017 g_return_val_if_fail (G_IS_SOCKET (socket
) && buffer
!= NULL
, -1);
3019 start_time
= g_get_monotonic_time ();
3021 if (!check_socket (socket
, error
))
3024 if (!check_timeout (socket
, error
))
3027 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
3032 win32_unset_event_mask (socket
, FD_READ
);
3034 if ((ret
= recv (socket
->priv
->fd
, buffer
, size
, 0)) < 0)
3036 int errsv
= get_socket_errno ();
3041 #ifdef WSAEWOULDBLOCK
3042 if (errsv
== WSAEWOULDBLOCK
)
3044 if (errsv
== EWOULDBLOCK
||
3050 if (!block_on_timeout (socket
, G_IO_IN
, timeout
, start_time
,
3051 cancellable
, error
))
3058 socket_set_error_lazy (error
, errsv
, _("Error receiving data: %s"));
3070 * @socket: a #GSocket
3071 * @buffer: (array length=size) (element-type guint8): a buffer to
3072 * read data into (which should be at least @size bytes long).
3073 * @size: the number of bytes you want to read from the socket
3074 * @cancellable: (nullable): a %GCancellable or %NULL
3075 * @error: #GError for error reporting, or %NULL to ignore.
3077 * Receive data (up to @size bytes) from a socket. This is mainly used by
3078 * connection-oriented sockets; it is identical to g_socket_receive_from()
3079 * with @address set to %NULL.
3081 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
3082 * g_socket_receive() will always read either 0 or 1 complete messages from
3083 * the socket. If the received message is too large to fit in @buffer, then
3084 * the data beyond @size bytes will be discarded, without any explicit
3085 * indication that this has occurred.
3087 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
3088 * number of bytes, up to @size. If more than @size bytes have been
3089 * received, the additional data will be returned in future calls to
3090 * g_socket_receive().
3092 * If the socket is in blocking mode the call will block until there
3093 * is some data to receive, the connection is closed, or there is an
3094 * error. If there is no data available and the socket is in
3095 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3096 * returned. To be notified when data is available, wait for the
3097 * %G_IO_IN condition.
3099 * On error -1 is returned and @error is set accordingly.
3101 * Returns: Number of bytes read, or 0 if the connection was closed by
3102 * the peer, or -1 on error
3107 g_socket_receive (GSocket
*socket
,
3110 GCancellable
*cancellable
,
3113 return g_socket_receive_with_timeout (socket
, (guint8
*) buffer
, size
,
3114 socket
->priv
->blocking
? -1 : 0,
3115 cancellable
, error
);
3119 * g_socket_receive_with_blocking:
3120 * @socket: a #GSocket
3121 * @buffer: (array length=size) (element-type guint8): a buffer to
3122 * read data into (which should be at least @size bytes long).
3123 * @size: the number of bytes you want to read from the socket
3124 * @blocking: whether to do blocking or non-blocking I/O
3125 * @cancellable: (nullable): a %GCancellable or %NULL
3126 * @error: #GError for error reporting, or %NULL to ignore.
3128 * This behaves exactly the same as g_socket_receive(), except that
3129 * the choice of blocking or non-blocking behavior is determined by
3130 * the @blocking argument rather than by @socket's properties.
3132 * Returns: Number of bytes read, or 0 if the connection was closed by
3133 * the peer, or -1 on error
3138 g_socket_receive_with_blocking (GSocket
*socket
,
3142 GCancellable
*cancellable
,
3145 return g_socket_receive_with_timeout (socket
, (guint8
*) buffer
, size
,
3146 blocking
? -1 : 0, cancellable
, error
);
3150 * g_socket_receive_from:
3151 * @socket: a #GSocket
3152 * @address: (out) (optional): a pointer to a #GSocketAddress
3154 * @buffer: (array length=size) (element-type guint8): a buffer to
3155 * read data into (which should be at least @size bytes long).
3156 * @size: the number of bytes you want to read from the socket
3157 * @cancellable: (nullable): a %GCancellable or %NULL
3158 * @error: #GError for error reporting, or %NULL to ignore.
3160 * Receive data (up to @size bytes) from a socket.
3162 * If @address is non-%NULL then @address will be set equal to the
3163 * source address of the received packet.
3164 * @address is owned by the caller.
3166 * See g_socket_receive() for additional information.
3168 * Returns: Number of bytes read, or 0 if the connection was closed by
3169 * the peer, or -1 on error
3174 g_socket_receive_from (GSocket
*socket
,
3175 GSocketAddress
**address
,
3178 GCancellable
*cancellable
,
3186 return g_socket_receive_message (socket
,
3194 /* See the comment about SIGPIPE above. */
3196 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
3198 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
3202 g_socket_send_with_timeout (GSocket
*socket
,
3203 const guint8
*buffer
,
3206 GCancellable
*cancellable
,
3212 g_return_val_if_fail (G_IS_SOCKET (socket
) && buffer
!= NULL
, -1);
3214 start_time
= g_get_monotonic_time ();
3216 if (!check_socket (socket
, error
))
3219 if (!check_timeout (socket
, error
))
3222 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
3227 win32_unset_event_mask (socket
, FD_WRITE
);
3229 if ((ret
= send (socket
->priv
->fd
, buffer
, size
, G_SOCKET_DEFAULT_SEND_FLAGS
)) < 0)
3231 int errsv
= get_socket_errno ();
3236 #ifdef WSAEWOULDBLOCK
3237 if (errsv
== WSAEWOULDBLOCK
)
3239 if (errsv
== EWOULDBLOCK
||
3245 if (!block_on_timeout (socket
, G_IO_OUT
, timeout
, start_time
,
3246 cancellable
, error
))
3253 socket_set_error_lazy (error
, errsv
, _("Error sending data: %s"));
3264 * @socket: a #GSocket
3265 * @buffer: (array length=size) (element-type guint8): the buffer
3266 * containing the data to send.
3267 * @size: the number of bytes to send
3268 * @cancellable: (nullable): a %GCancellable or %NULL
3269 * @error: #GError for error reporting, or %NULL to ignore.
3271 * Tries to send @size bytes from @buffer on the socket. This is
3272 * mainly used by connection-oriented sockets; it is identical to
3273 * g_socket_send_to() with @address set to %NULL.
3275 * If the socket is in blocking mode the call will block until there is
3276 * space for the data in the socket queue. If there is no space available
3277 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3278 * will be returned. To be notified when space is available, wait for the
3279 * %G_IO_OUT condition. Note though that you may still receive
3280 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3281 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3282 * very common due to the way the underlying APIs work.)
3284 * On error -1 is returned and @error is set accordingly.
3286 * Returns: Number of bytes written (which may be less than @size), or -1
3292 g_socket_send (GSocket
*socket
,
3293 const gchar
*buffer
,
3295 GCancellable
*cancellable
,
3298 return g_socket_send_with_blocking (socket
, buffer
, size
,
3299 socket
->priv
->blocking
,
3300 cancellable
, error
);
3304 * g_socket_send_with_blocking:
3305 * @socket: a #GSocket
3306 * @buffer: (array length=size) (element-type guint8): the buffer
3307 * containing the data to send.
3308 * @size: the number of bytes to send
3309 * @blocking: whether to do blocking or non-blocking I/O
3310 * @cancellable: (nullable): a %GCancellable or %NULL
3311 * @error: #GError for error reporting, or %NULL to ignore.
3313 * This behaves exactly the same as g_socket_send(), except that
3314 * the choice of blocking or non-blocking behavior is determined by
3315 * the @blocking argument rather than by @socket's properties.
3317 * Returns: Number of bytes written (which may be less than @size), or -1
3323 g_socket_send_with_blocking (GSocket
*socket
,
3324 const gchar
*buffer
,
3327 GCancellable
*cancellable
,
3330 return g_socket_send_with_timeout (socket
, (const guint8
*) buffer
, size
,
3331 blocking
? -1 : 0, cancellable
, error
);
3336 * @socket: a #GSocket
3337 * @address: (nullable): a #GSocketAddress, or %NULL
3338 * @buffer: (array length=size) (element-type guint8): the buffer
3339 * containing the data to send.
3340 * @size: the number of bytes to send
3341 * @cancellable: (nullable): a %GCancellable or %NULL
3342 * @error: #GError for error reporting, or %NULL to ignore.
3344 * Tries to send @size bytes from @buffer to @address. If @address is
3345 * %NULL then the message is sent to the default receiver (set by
3346 * g_socket_connect()).
3348 * See g_socket_send() for additional information.
3350 * Returns: Number of bytes written (which may be less than @size), or -1
3356 g_socket_send_to (GSocket
*socket
,
3357 GSocketAddress
*address
,
3358 const gchar
*buffer
,
3360 GCancellable
*cancellable
,
3368 return g_socket_send_message (socket
,
3378 * g_socket_shutdown:
3379 * @socket: a #GSocket
3380 * @shutdown_read: whether to shut down the read side
3381 * @shutdown_write: whether to shut down the write side
3382 * @error: #GError for error reporting, or %NULL to ignore.
3384 * Shut down part or all of a full-duplex connection.
3386 * If @shutdown_read is %TRUE then the receiving side of the connection
3387 * is shut down, and further reading is disallowed.
3389 * If @shutdown_write is %TRUE then the sending side of the connection
3390 * is shut down, and further writing is disallowed.
3392 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
3394 * One example where it is useful to shut down only one side of a connection is
3395 * graceful disconnect for TCP connections where you close the sending side,
3396 * then wait for the other side to close the connection, thus ensuring that the
3397 * other side saw all sent data.
3399 * Returns: %TRUE on success, %FALSE on error
3404 g_socket_shutdown (GSocket
*socket
,
3405 gboolean shutdown_read
,
3406 gboolean shutdown_write
,
3411 g_return_val_if_fail (G_IS_SOCKET (socket
), TRUE
);
3413 if (!check_socket (socket
, error
))
3417 if (!shutdown_read
&& !shutdown_write
)
3421 if (shutdown_read
&& shutdown_write
)
3423 else if (shutdown_read
)
3428 if (shutdown_read
&& shutdown_write
)
3430 else if (shutdown_read
)
3436 if (shutdown (socket
->priv
->fd
, how
) != 0)
3438 int errsv
= get_socket_errno ();
3439 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
3440 _("Unable to shutdown socket: %s"), socket_strerror (errsv
));
3445 socket
->priv
->connected_read
= FALSE
;
3447 socket
->priv
->connected_write
= FALSE
;
3454 * @socket: a #GSocket
3455 * @error: #GError for error reporting, or %NULL to ignore.
3457 * Closes the socket, shutting down any active connection.
3459 * Closing a socket does not wait for all outstanding I/O operations
3460 * to finish, so the caller should not rely on them to be guaranteed
3461 * to complete even if the close returns with no error.
3463 * Once the socket is closed, all other operations will return
3464 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
3467 * Sockets will be automatically closed when the last reference
3468 * is dropped, but you might want to call this function to make sure
3469 * resources are released as early as possible.
3471 * Beware that due to the way that TCP works, it is possible for
3472 * recently-sent data to be lost if either you close a socket while the
3473 * %G_IO_IN condition is set, or else if the remote connection tries to
3474 * send something to you after you close the socket but before it has
3475 * finished reading all of the data you sent. There is no easy generic
3476 * way to avoid this problem; the easiest fix is to design the network
3477 * protocol such that the client will never send data "out of turn".
3478 * Another solution is for the server to half-close the connection by
3479 * calling g_socket_shutdown() with only the @shutdown_write flag set,
3480 * and then wait for the client to notice this and close its side of the
3481 * connection, after which the server can safely call g_socket_close().
3482 * (This is what #GTcpConnection does if you call
3483 * g_tcp_connection_set_graceful_disconnect(). But of course, this
3484 * only works if the client will close its connection after the server
3487 * Returns: %TRUE on success, %FALSE on error
3492 g_socket_close (GSocket
*socket
,
3497 g_return_val_if_fail (G_IS_SOCKET (socket
), TRUE
);
3499 if (socket
->priv
->closed
)
3500 return TRUE
; /* Multiple close not an error */
3502 if (!check_socket (socket
, error
))
3508 res
= closesocket (socket
->priv
->fd
);
3510 res
= close (socket
->priv
->fd
);
3514 int errsv
= get_socket_errno ();
3519 g_set_error (error
, G_IO_ERROR
,
3520 socket_io_error_from_errno (errsv
),
3521 _("Error closing socket: %s"),
3522 socket_strerror (errsv
));
3528 socket
->priv
->fd
= -1;
3529 socket
->priv
->connected_read
= FALSE
;
3530 socket
->priv
->connected_write
= FALSE
;
3531 socket
->priv
->closed
= TRUE
;
3532 if (socket
->priv
->remote_address
)
3534 g_object_unref (socket
->priv
->remote_address
);
3535 socket
->priv
->remote_address
= NULL
;
3542 * g_socket_is_closed:
3543 * @socket: a #GSocket
3545 * Checks whether a socket is closed.
3547 * Returns: %TRUE if socket is closed, %FALSE otherwise
3552 g_socket_is_closed (GSocket
*socket
)
3554 return socket
->priv
->closed
;
3558 /* Broken source, used on errors */
3560 broken_dispatch (GSource
*source
,
3561 GSourceFunc callback
,
3567 static GSourceFuncs broken_funcs
=
3576 network_events_for_condition (GIOCondition condition
)
3580 if (condition
& G_IO_IN
)
3581 event_mask
|= (FD_READ
| FD_ACCEPT
);
3582 if (condition
& G_IO_OUT
)
3583 event_mask
|= (FD_WRITE
| FD_CONNECT
);
3584 event_mask
|= FD_CLOSE
;
3590 ensure_event (GSocket
*socket
)
3592 if (socket
->priv
->event
== WSA_INVALID_EVENT
)
3593 socket
->priv
->event
= WSACreateEvent();
3597 update_select_events (GSocket
*socket
)
3604 ensure_event (socket
);
3607 for (l
= socket
->priv
->requested_conditions
; l
!= NULL
; l
= l
->next
)
3610 event_mask
|= network_events_for_condition (*ptr
);
3613 if (event_mask
!= socket
->priv
->selected_events
)
3615 /* If no events selected, disable event so we can unset
3618 if (event_mask
== 0)
3621 event
= socket
->priv
->event
;
3623 if (WSAEventSelect (socket
->priv
->fd
, event
, event_mask
) == 0)
3624 socket
->priv
->selected_events
= event_mask
;
3629 add_condition_watch (GSocket
*socket
,
3630 GIOCondition
*condition
)
3632 g_mutex_lock (&socket
->priv
->win32_source_lock
);
3633 g_assert (g_list_find (socket
->priv
->requested_conditions
, condition
) == NULL
);
3635 socket
->priv
->requested_conditions
=
3636 g_list_prepend (socket
->priv
->requested_conditions
, condition
);
3638 update_select_events (socket
);
3639 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
3643 remove_condition_watch (GSocket
*socket
,
3644 GIOCondition
*condition
)
3646 g_mutex_lock (&socket
->priv
->win32_source_lock
);
3647 g_assert (g_list_find (socket
->priv
->requested_conditions
, condition
) != NULL
);
3649 socket
->priv
->requested_conditions
=
3650 g_list_remove (socket
->priv
->requested_conditions
, condition
);
3652 update_select_events (socket
);
3653 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
3657 update_condition_unlocked (GSocket
*socket
)
3659 WSANETWORKEVENTS events
;
3660 GIOCondition condition
;
3662 if (WSAEnumNetworkEvents (socket
->priv
->fd
,
3663 socket
->priv
->event
,
3666 socket
->priv
->current_events
|= events
.lNetworkEvents
;
3667 if (events
.lNetworkEvents
& FD_WRITE
&&
3668 events
.iErrorCode
[FD_WRITE_BIT
] != 0)
3669 socket
->priv
->current_errors
|= FD_WRITE
;
3670 if (events
.lNetworkEvents
& FD_CONNECT
&&
3671 events
.iErrorCode
[FD_CONNECT_BIT
] != 0)
3672 socket
->priv
->current_errors
|= FD_CONNECT
;
3676 if (socket
->priv
->current_events
& (FD_READ
| FD_ACCEPT
))
3677 condition
|= G_IO_IN
;
3679 if (socket
->priv
->current_events
& FD_CLOSE
)
3681 int r
, errsv
, buffer
;
3683 r
= recv (socket
->priv
->fd
, &buffer
, sizeof (buffer
), MSG_PEEK
);
3685 errsv
= get_socket_errno ();
3688 (r
< 0 && errsv
== WSAENOTCONN
))
3689 condition
|= G_IO_IN
;
3691 (r
< 0 && (errsv
== WSAESHUTDOWN
|| errsv
== WSAECONNRESET
||
3692 errsv
== WSAECONNABORTED
|| errsv
== WSAENETRESET
)))
3693 condition
|= G_IO_HUP
;
3695 condition
|= G_IO_ERR
;
3698 if (socket
->priv
->closed
)
3699 condition
|= G_IO_HUP
;
3701 /* Never report both G_IO_OUT and HUP, these are
3702 mutually exclusive (can't write to a closed socket) */
3703 if ((condition
& G_IO_HUP
) == 0 &&
3704 socket
->priv
->current_events
& FD_WRITE
)
3706 if (socket
->priv
->current_errors
& FD_WRITE
)
3707 condition
|= G_IO_ERR
;
3709 condition
|= G_IO_OUT
;
3713 if (socket
->priv
->current_events
& FD_CONNECT
)
3715 if (socket
->priv
->current_errors
& FD_CONNECT
)
3716 condition
|= (G_IO_HUP
| G_IO_ERR
);
3718 condition
|= G_IO_OUT
;
3726 update_condition (GSocket
*socket
)
3729 g_mutex_lock (&socket
->priv
->win32_source_lock
);
3730 res
= update_condition_unlocked (socket
);
3731 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
3744 GIOCondition condition
;
3748 socket_source_prepare (GSource
*source
,
3751 GSocketSource
*socket_source
= (GSocketSource
*)source
;
3756 if ((socket_source
->pollfd
.revents
& G_IO_NVAL
) != 0)
3759 if (g_socket_is_closed (socket_source
->socket
))
3761 g_source_remove_poll (source
, &socket_source
->pollfd
);
3762 socket_source
->pollfd
.revents
= G_IO_NVAL
;
3766 return (update_condition (socket_source
->socket
) & socket_source
->condition
) != 0;
3768 return g_socket_is_closed (socket_source
->socket
) && socket_source
->fd_tag
!= NULL
;
3774 socket_source_check_win32 (GSource
*source
)
3778 return socket_source_prepare (source
, &timeout
);
3783 socket_source_dispatch (GSource
*source
,
3784 GSourceFunc callback
,
3787 GSocketSourceFunc func
= (GSocketSourceFunc
)callback
;
3788 GSocketSource
*socket_source
= (GSocketSource
*)source
;
3789 GSocket
*socket
= socket_source
->socket
;
3795 events
= update_condition (socket_source
->socket
);
3797 if (g_socket_is_closed (socket_source
->socket
))
3799 if (socket_source
->fd_tag
)
3800 g_source_remove_unix_fd (source
, socket_source
->fd_tag
);
3801 socket_source
->fd_tag
= NULL
;
3806 events
= g_source_query_unix_fd (source
, socket_source
->fd_tag
);
3810 timeout
= g_source_get_ready_time (source
);
3811 if (timeout
>= 0 && timeout
< g_source_get_time (source
) &&
3812 !g_socket_is_closed (socket_source
->socket
))
3814 socket
->priv
->timed_out
= TRUE
;
3815 events
|= (G_IO_IN
| G_IO_OUT
);
3818 ret
= (*func
) (socket
, events
& socket_source
->condition
, user_data
);
3820 if (socket
->priv
->timeout
&& !g_socket_is_closed (socket_source
->socket
))
3821 g_source_set_ready_time (source
, g_get_monotonic_time () + socket
->priv
->timeout
* 1000000);
3823 g_source_set_ready_time (source
, -1);
3829 socket_source_finalize (GSource
*source
)
3831 GSocketSource
*socket_source
= (GSocketSource
*)source
;
3834 socket
= socket_source
->socket
;
3837 remove_condition_watch (socket
, &socket_source
->condition
);
3840 g_object_unref (socket
);
3844 socket_source_closure_callback (GSocket
*socket
,
3845 GIOCondition condition
,
3848 GClosure
*closure
= data
;
3850 GValue params
[2] = { G_VALUE_INIT
, G_VALUE_INIT
};
3851 GValue result_value
= G_VALUE_INIT
;
3854 g_value_init (&result_value
, G_TYPE_BOOLEAN
);
3856 g_value_init (¶ms
[0], G_TYPE_SOCKET
);
3857 g_value_set_object (¶ms
[0], socket
);
3858 g_value_init (¶ms
[1], G_TYPE_IO_CONDITION
);
3859 g_value_set_flags (¶ms
[1], condition
);
3861 g_closure_invoke (closure
, &result_value
, 2, params
, NULL
);
3863 result
= g_value_get_boolean (&result_value
);
3864 g_value_unset (&result_value
);
3865 g_value_unset (¶ms
[0]);
3866 g_value_unset (¶ms
[1]);
3871 static GSourceFuncs socket_source_funcs
=
3873 socket_source_prepare
,
3875 socket_source_check_win32
,
3879 socket_source_dispatch
,
3880 socket_source_finalize
,
3881 (GSourceFunc
)socket_source_closure_callback
,
3885 socket_source_new (GSocket
*socket
,
3886 GIOCondition condition
,
3887 GCancellable
*cancellable
)
3890 GSocketSource
*socket_source
;
3893 ensure_event (socket
);
3895 if (socket
->priv
->event
== WSA_INVALID_EVENT
)
3897 g_warning ("Failed to create WSAEvent");
3898 return g_source_new (&broken_funcs
, sizeof (GSource
));
3902 condition
|= G_IO_HUP
| G_IO_ERR
| G_IO_NVAL
;
3904 source
= g_source_new (&socket_source_funcs
, sizeof (GSocketSource
));
3905 g_source_set_name (source
, "GSocket");
3906 socket_source
= (GSocketSource
*)source
;
3908 socket_source
->socket
= g_object_ref (socket
);
3909 socket_source
->condition
= condition
;
3913 GSource
*cancellable_source
;
3915 cancellable_source
= g_cancellable_source_new (cancellable
);
3916 g_source_add_child_source (source
, cancellable_source
);
3917 g_source_set_dummy_callback (cancellable_source
);
3918 g_source_unref (cancellable_source
);
3922 add_condition_watch (socket
, &socket_source
->condition
);
3923 socket_source
->pollfd
.fd
= (gintptr
) socket
->priv
->event
;
3924 socket_source
->pollfd
.events
= condition
;
3925 socket_source
->pollfd
.revents
= 0;
3926 g_source_add_poll (source
, &socket_source
->pollfd
);
3928 socket_source
->fd_tag
= g_source_add_unix_fd (source
, socket
->priv
->fd
, condition
);
3931 if (socket
->priv
->timeout
)
3932 g_source_set_ready_time (source
, g_get_monotonic_time () + socket
->priv
->timeout
* 1000000);
3934 g_source_set_ready_time (source
, -1);
3940 * g_socket_create_source: (skip)
3941 * @socket: a #GSocket
3942 * @condition: a #GIOCondition mask to monitor
3943 * @cancellable: (nullable): a %GCancellable or %NULL
3945 * Creates a #GSource that can be attached to a %GMainContext to monitor
3946 * for the availability of the specified @condition on the socket. The #GSource
3947 * keeps a reference to the @socket.
3949 * The callback on the source is of the #GSocketSourceFunc type.
3951 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3952 * these conditions will always be reported output if they are true.
3954 * @cancellable if not %NULL can be used to cancel the source, which will
3955 * cause the source to trigger, reporting the current condition (which
3956 * is likely 0 unless cancellation happened at the same time as a
3957 * condition change). You can check for this in the callback using
3958 * g_cancellable_is_cancelled().
3960 * If @socket has a timeout set, and it is reached before @condition
3961 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3962 * %G_IO_OUT depending on @condition. However, @socket will have been
3963 * marked as having had a timeout, and so the next #GSocket I/O method
3964 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3966 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3971 g_socket_create_source (GSocket
*socket
,
3972 GIOCondition condition
,
3973 GCancellable
*cancellable
)
3975 g_return_val_if_fail (G_IS_SOCKET (socket
) && (cancellable
== NULL
|| G_IS_CANCELLABLE (cancellable
)), NULL
);
3977 return socket_source_new (socket
, condition
, cancellable
);
3981 * g_socket_condition_check:
3982 * @socket: a #GSocket
3983 * @condition: a #GIOCondition mask to check
3985 * Checks on the readiness of @socket to perform operations.
3986 * The operations specified in @condition are checked for and masked
3987 * against the currently-satisfied conditions on @socket. The result
3990 * Note that on Windows, it is possible for an operation to return
3991 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3992 * g_socket_condition_check() has claimed that the socket is ready for
3993 * writing. Rather than calling g_socket_condition_check() and then
3994 * writing to the socket if it succeeds, it is generally better to
3995 * simply try writing to the socket right away, and try again later if
3996 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3998 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3999 * these conditions will always be set in the output if they are true.
4001 * This call never blocks.
4003 * Returns: the @GIOCondition mask of the current state
4008 g_socket_condition_check (GSocket
*socket
,
4009 GIOCondition condition
)
4011 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
4013 if (!check_socket (socket
, NULL
))
4018 GIOCondition current_condition
;
4020 condition
|= G_IO_ERR
| G_IO_HUP
;
4022 add_condition_watch (socket
, &condition
);
4023 current_condition
= update_condition (socket
);
4024 remove_condition_watch (socket
, &condition
);
4025 return condition
& current_condition
;
4031 poll_fd
.fd
= socket
->priv
->fd
;
4032 poll_fd
.events
= condition
;
4033 poll_fd
.revents
= 0;
4036 result
= g_poll (&poll_fd
, 1, 0);
4037 while (result
== -1 && get_socket_errno () == EINTR
);
4039 return poll_fd
.revents
;
4045 * g_socket_condition_wait:
4046 * @socket: a #GSocket
4047 * @condition: a #GIOCondition mask to wait for
4048 * @cancellable: (nullable): a #GCancellable, or %NULL
4049 * @error: a #GError pointer, or %NULL
4051 * Waits for @condition to become true on @socket. When the condition
4052 * is met, %TRUE is returned.
4054 * If @cancellable is cancelled before the condition is met, or if the
4055 * socket has a timeout set and it is reached before the condition is
4056 * met, then %FALSE is returned and @error, if non-%NULL, is set to
4057 * the appropriate value (%G_IO_ERROR_CANCELLED or
4058 * %G_IO_ERROR_TIMED_OUT).
4060 * See also g_socket_condition_timed_wait().
4062 * Returns: %TRUE if the condition was met, %FALSE otherwise
4067 g_socket_condition_wait (GSocket
*socket
,
4068 GIOCondition condition
,
4069 GCancellable
*cancellable
,
4072 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
4074 return g_socket_condition_timed_wait (socket
, condition
, -1,
4075 cancellable
, error
);
4079 * g_socket_condition_timed_wait:
4080 * @socket: a #GSocket
4081 * @condition: a #GIOCondition mask to wait for
4082 * @timeout: the maximum time (in microseconds) to wait, or -1
4083 * @cancellable: (nullable): a #GCancellable, or %NULL
4084 * @error: a #GError pointer, or %NULL
4086 * Waits for up to @timeout microseconds for @condition to become true
4087 * on @socket. If the condition is met, %TRUE is returned.
4089 * If @cancellable is cancelled before the condition is met, or if
4090 * @timeout (or the socket's #GSocket:timeout) is reached before the
4091 * condition is met, then %FALSE is returned and @error, if non-%NULL,
4092 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
4093 * %G_IO_ERROR_TIMED_OUT).
4095 * If you don't want a timeout, use g_socket_condition_wait().
4096 * (Alternatively, you can pass -1 for @timeout.)
4098 * Note that although @timeout is in microseconds for consistency with
4099 * other GLib APIs, this function actually only has millisecond
4100 * resolution, and the behavior is undefined if @timeout is not an
4101 * exact number of milliseconds.
4103 * Returns: %TRUE if the condition was met, %FALSE otherwise
4108 g_socket_condition_timed_wait (GSocket
*socket
,
4109 GIOCondition condition
,
4111 GCancellable
*cancellable
,
4116 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
4118 if (!check_socket (socket
, error
))
4121 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
4124 if (socket
->priv
->timeout
&&
4125 (timeout
< 0 || socket
->priv
->timeout
< timeout
/ G_USEC_PER_SEC
))
4126 timeout
= (gint64
) socket
->priv
->timeout
* 1000;
4127 else if (timeout
!= -1)
4128 timeout
= timeout
/ 1000;
4130 start_time
= g_get_monotonic_time ();
4134 GIOCondition current_condition
;
4140 /* Always check these */
4141 condition
|= G_IO_ERR
| G_IO_HUP
;
4143 add_condition_watch (socket
, &condition
);
4146 events
[num_events
++] = socket
->priv
->event
;
4148 if (g_cancellable_make_pollfd (cancellable
, &cancel_fd
))
4149 events
[num_events
++] = (WSAEVENT
)cancel_fd
.fd
;
4152 timeout
= WSA_INFINITE
;
4154 g_mutex_lock (&socket
->priv
->win32_source_lock
);
4155 current_condition
= update_condition_unlocked (socket
);
4156 while ((condition
& current_condition
) == 0)
4158 if (!socket
->priv
->waiting
)
4160 socket
->priv
->waiting
= TRUE
;
4161 socket
->priv
->waiting_result
= 0;
4162 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
4164 res
= WSAWaitForMultipleEvents (num_events
, events
, FALSE
, timeout
, FALSE
);
4166 g_mutex_lock (&socket
->priv
->win32_source_lock
);
4167 socket
->priv
->waiting
= FALSE
;
4168 socket
->priv
->waiting_result
= res
;
4169 g_cond_broadcast (&socket
->priv
->win32_source_cond
);
4173 if (timeout
!= WSA_INFINITE
)
4175 if (!g_cond_wait_until (&socket
->priv
->win32_source_cond
, &socket
->priv
->win32_source_lock
, timeout
))
4177 res
= WSA_WAIT_TIMEOUT
;
4182 res
= socket
->priv
->waiting_result
;
4187 g_cond_wait (&socket
->priv
->win32_source_cond
, &socket
->priv
->win32_source_lock
);
4188 res
= socket
->priv
->waiting_result
;
4192 if (res
== WSA_WAIT_FAILED
)
4194 int errsv
= get_socket_errno ();
4196 g_set_error (error
, G_IO_ERROR
,
4197 socket_io_error_from_errno (errsv
),
4198 _("Waiting for socket condition: %s"),
4199 socket_strerror (errsv
));
4202 else if (res
== WSA_WAIT_TIMEOUT
)
4204 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
,
4205 _("Socket I/O timed out"));
4209 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
4212 current_condition
= update_condition_unlocked (socket
);
4214 if (timeout
!= WSA_INFINITE
)
4216 timeout
-= (g_get_monotonic_time () - start_time
) * 1000;
4221 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
4222 remove_condition_watch (socket
, &condition
);
4224 g_cancellable_release_fd (cancellable
);
4226 return (condition
& current_condition
) != 0;
4234 poll_fd
[0].fd
= socket
->priv
->fd
;
4235 poll_fd
[0].events
= condition
;
4238 if (g_cancellable_make_pollfd (cancellable
, &poll_fd
[1]))
4244 result
= g_poll (poll_fd
, num
, timeout
);
4246 if (result
!= -1 || errsv
!= EINTR
)
4251 timeout
-= (g_get_monotonic_time () - start_time
) / 1000;
4258 g_cancellable_release_fd (cancellable
);
4262 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
,
4263 _("Socket I/O timed out"));
4267 return !g_cancellable_set_error_if_cancelled (cancellable
, error
);
4274 /* Unfortunately these have to be macros rather than inline functions due to
4275 * using alloca(). */
4276 #define output_message_to_msghdr(message, prev_message, msg, prev_msg, error) \
4278 const GOutputMessage *_message = (message); \
4279 const GOutputMessage *_prev_message = (prev_message); \
4280 struct msghdr *_msg = (msg); \
4281 const struct msghdr *_prev_msg = (prev_msg); \
4282 GError **_error = (error); \
4284 _msg->msg_flags = 0; \
4287 if (_prev_message != NULL && _prev_message->address == _message->address) \
4289 _msg->msg_name = _prev_msg->msg_name; \
4290 _msg->msg_namelen = _prev_msg->msg_namelen; \
4292 else if (_message->address != NULL) \
4294 _msg->msg_namelen = g_socket_address_get_native_size (_message->address); \
4295 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4296 if (!g_socket_address_to_native (_message->address, _msg->msg_name, \
4297 _msg->msg_namelen, _error)) \
4302 _msg->msg_name = NULL; \
4303 _msg->msg_namelen = 0; \
4308 /* this entire expression will be evaluated at compile time */ \
4309 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4310 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4311 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4312 G_STRUCT_OFFSET (GOutputVector, buffer) && \
4313 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4314 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4315 G_STRUCT_OFFSET (GOutputVector, size)) \
4316 /* ABI is compatible */ \
4318 _msg->msg_iov = (struct iovec *) _message->vectors; \
4319 _msg->msg_iovlen = _message->num_vectors; \
4322 /* ABI is incompatible */ \
4326 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4327 for (i = 0; i < _message->num_vectors; i++) \
4329 _msg->msg_iov[i].iov_base = (void *) _message->vectors[i].buffer; \
4330 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4332 _msg->msg_iovlen = _message->num_vectors; \
4338 struct cmsghdr *cmsg; \
4341 _msg->msg_controllen = 0; \
4342 for (i = 0; i < _message->num_control_messages; i++) \
4343 _msg->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (_message->control_messages[i])); \
4345 if (_msg->msg_controllen == 0) \
4346 _msg->msg_control = NULL; \
4349 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4350 memset (_msg->msg_control, '\0', _msg->msg_controllen); \
4353 cmsg = CMSG_FIRSTHDR (_msg); \
4354 for (i = 0; i < _message->num_control_messages; i++) \
4356 cmsg->cmsg_level = g_socket_control_message_get_level (_message->control_messages[i]); \
4357 cmsg->cmsg_type = g_socket_control_message_get_msg_type (_message->control_messages[i]); \
4358 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (_message->control_messages[i])); \
4359 g_socket_control_message_serialize (_message->control_messages[i], \
4360 CMSG_DATA (cmsg)); \
4361 cmsg = CMSG_NXTHDR (_msg, cmsg); \
4363 g_assert (cmsg == NULL); \
4367 #define input_message_to_msghdr(message, msg) \
4369 const GInputMessage *_message = (message); \
4370 struct msghdr *_msg = (msg); \
4373 if (_message->address) \
4375 _msg->msg_namelen = sizeof (struct sockaddr_storage); \
4376 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4380 _msg->msg_name = NULL; \
4381 _msg->msg_namelen = 0; \
4385 /* this entire expression will be evaluated at compile time */ \
4386 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4387 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4388 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4389 G_STRUCT_OFFSET (GInputVector, buffer) && \
4390 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4391 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4392 G_STRUCT_OFFSET (GInputVector, size)) \
4393 /* ABI is compatible */ \
4395 _msg->msg_iov = (struct iovec *) _message->vectors; \
4396 _msg->msg_iovlen = _message->num_vectors; \
4399 /* ABI is incompatible */ \
4403 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4404 for (i = 0; i < _message->num_vectors; i++) \
4406 _msg->msg_iov[i].iov_base = _message->vectors[i].buffer; \
4407 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4409 _msg->msg_iovlen = _message->num_vectors; \
4413 if (_message->control_messages == NULL) \
4415 _msg->msg_controllen = 0; \
4416 _msg->msg_control = NULL; \
4420 _msg->msg_controllen = 2048; \
4421 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4425 _msg->msg_flags = _message->flags; \
4429 input_message_from_msghdr (const struct msghdr
*msg
,
4430 GInputMessage
*message
,
4433 /* decode address */
4434 if (message
->address
!= NULL
)
4436 *message
->address
= cache_recv_address (socket
, msg
->msg_name
,
4440 /* decode control messages */
4442 GPtrArray
*my_messages
= NULL
;
4443 struct cmsghdr
*cmsg
;
4445 if (msg
->msg_controllen
>= sizeof (struct cmsghdr
))
4447 g_assert (message
->control_messages
!= NULL
);
4448 for (cmsg
= CMSG_FIRSTHDR (msg
);
4450 cmsg
= CMSG_NXTHDR ((struct msghdr
*) msg
, cmsg
))
4452 GSocketControlMessage
*control_message
;
4454 control_message
= g_socket_control_message_deserialize (cmsg
->cmsg_level
,
4456 cmsg
->cmsg_len
- ((char *)CMSG_DATA (cmsg
) - (char *)cmsg
),
4458 if (control_message
== NULL
)
4459 /* We've already spewed about the problem in the
4460 deserialization code, so just continue */
4463 if (my_messages
== NULL
)
4464 my_messages
= g_ptr_array_new ();
4465 g_ptr_array_add (my_messages
, control_message
);
4469 if (message
->num_control_messages
)
4470 *message
->num_control_messages
= my_messages
!= NULL
? my_messages
->len
: 0;
4472 if (message
->control_messages
)
4474 if (my_messages
== NULL
)
4476 *message
->control_messages
= NULL
;
4480 g_ptr_array_add (my_messages
, NULL
);
4481 *message
->control_messages
= (GSocketControlMessage
**) g_ptr_array_free (my_messages
, FALSE
);
4486 g_assert (my_messages
== NULL
);
4490 /* capture the flags */
4491 message
->flags
= msg
->msg_flags
;
4496 * g_socket_send_message:
4497 * @socket: a #GSocket
4498 * @address: (nullable): a #GSocketAddress, or %NULL
4499 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4500 * @num_vectors: the number of elements in @vectors, or -1
4501 * @messages: (array length=num_messages) (nullable): a pointer to an
4502 * array of #GSocketControlMessages, or %NULL.
4503 * @num_messages: number of elements in @messages, or -1.
4504 * @flags: an int containing #GSocketMsgFlags flags
4505 * @cancellable: (nullable): a %GCancellable or %NULL
4506 * @error: #GError for error reporting, or %NULL to ignore.
4508 * Send data to @address on @socket. For sending multiple messages see
4509 * g_socket_send_messages(); for easier use, see
4510 * g_socket_send() and g_socket_send_to().
4512 * If @address is %NULL then the message is sent to the default receiver
4513 * (set by g_socket_connect()).
4515 * @vectors must point to an array of #GOutputVector structs and
4516 * @num_vectors must be the length of this array. (If @num_vectors is -1,
4517 * then @vectors is assumed to be terminated by a #GOutputVector with a
4518 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
4519 * that the sent data will be gathered from. Using multiple
4520 * #GOutputVectors is more memory-efficient than manually copying
4521 * data from multiple sources into a single buffer, and more
4522 * network-efficient than making multiple calls to g_socket_send().
4524 * @messages, if non-%NULL, is taken to point to an array of @num_messages
4525 * #GSocketControlMessage instances. These correspond to the control
4526 * messages to be sent on the socket.
4527 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
4530 * @flags modify how the message is sent. The commonly available arguments
4531 * for this are available in the #GSocketMsgFlags enum, but the
4532 * values there are the same as the system values, and the flags
4533 * are passed in as-is, so you can pass in system-specific flags too.
4535 * If the socket is in blocking mode the call will block until there is
4536 * space for the data in the socket queue. If there is no space available
4537 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4538 * will be returned. To be notified when space is available, wait for the
4539 * %G_IO_OUT condition. Note though that you may still receive
4540 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4541 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4542 * very common due to the way the underlying APIs work.)
4544 * On error -1 is returned and @error is set accordingly.
4546 * Returns: Number of bytes written (which may be less than @size), or -1
4552 g_socket_send_message (GSocket
*socket
,
4553 GSocketAddress
*address
,
4554 GOutputVector
*vectors
,
4556 GSocketControlMessage
**messages
,
4559 GCancellable
*cancellable
,
4562 return g_socket_send_message_with_timeout (socket
, address
,
4563 vectors
, num_vectors
,
4564 messages
, num_messages
, flags
,
4565 socket
->priv
->blocking
? -1 : 0,
4566 cancellable
, error
);
4570 g_socket_send_message_with_timeout (GSocket
*socket
,
4571 GSocketAddress
*address
,
4572 GOutputVector
*vectors
,
4574 GSocketControlMessage
**messages
,
4578 GCancellable
*cancellable
,
4581 GOutputVector one_vector
;
4585 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
4586 g_return_val_if_fail (address
== NULL
|| G_IS_SOCKET_ADDRESS (address
), -1);
4587 g_return_val_if_fail (num_vectors
== 0 || vectors
!= NULL
, -1);
4588 g_return_val_if_fail (num_messages
== 0 || messages
!= NULL
, -1);
4589 g_return_val_if_fail (cancellable
== NULL
|| G_IS_CANCELLABLE (cancellable
), -1);
4590 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, -1);
4592 start_time
= g_get_monotonic_time ();
4594 if (!check_socket (socket
, error
))
4597 if (!check_timeout (socket
, error
))
4600 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
4603 if (num_vectors
== -1)
4605 for (num_vectors
= 0;
4606 vectors
[num_vectors
].buffer
!= NULL
;
4611 if (num_messages
== -1)
4613 for (num_messages
= 0;
4614 messages
!= NULL
&& messages
[num_messages
] != NULL
;
4619 if (num_vectors
== 0)
4623 one_vector
.buffer
= &zero
;
4624 one_vector
.size
= 1;
4626 vectors
= &one_vector
;
4631 GOutputMessage output_message
;
4634 GError
*child_error
= NULL
;
4636 output_message
.address
= address
;
4637 output_message
.vectors
= vectors
;
4638 output_message
.num_vectors
= num_vectors
;
4639 output_message
.bytes_sent
= 0;
4640 output_message
.control_messages
= messages
;
4641 output_message
.num_control_messages
= num_messages
;
4643 output_message_to_msghdr (&output_message
, NULL
, &msg
, NULL
, &child_error
);
4645 if (child_error
!= NULL
)
4647 g_propagate_error (error
, child_error
);
4653 result
= sendmsg (socket
->priv
->fd
, &msg
, flags
| G_SOCKET_DEFAULT_SEND_FLAGS
);
4656 int errsv
= get_socket_errno ();
4662 (errsv
== EWOULDBLOCK
||
4665 if (!block_on_timeout (socket
, G_IO_OUT
, timeout
, start_time
,
4666 cancellable
, error
))
4672 socket_set_error_lazy (error
, errsv
, _("Error sending message: %s"));
4682 struct sockaddr_storage addr
;
4689 /* Win32 doesn't support control messages.
4690 Actually this is possible for raw and datagram sockets
4691 via WSASendMessage on Vista or later, but that doesn't
4693 if (num_messages
!= 0)
4695 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
4696 _("GSocketControlMessage not supported on Windows"));
4701 bufs
= g_newa (WSABUF
, num_vectors
);
4702 for (i
= 0; i
< num_vectors
; i
++)
4704 bufs
[i
].buf
= (char *)vectors
[i
].buffer
;
4705 bufs
[i
].len
= (gulong
)vectors
[i
].size
;
4709 addrlen
= 0; /* Avoid warning */
4712 addrlen
= g_socket_address_get_native_size (address
);
4713 if (!g_socket_address_to_native (address
, &addr
, sizeof addr
, error
))
4719 win32_unset_event_mask (socket
, FD_WRITE
);
4722 result
= WSASendTo (socket
->priv
->fd
,
4725 (const struct sockaddr
*)&addr
, addrlen
,
4728 result
= WSASend (socket
->priv
->fd
,
4735 int errsv
= get_socket_errno ();
4737 if (errsv
== WSAEINTR
)
4740 if (errsv
== WSAEWOULDBLOCK
)
4744 if (!block_on_timeout (socket
, G_IO_OUT
, timeout
,
4745 start_time
, cancellable
, error
))
4752 socket_set_error_lazy (error
, errsv
, _("Error sending message: %s"));
4764 * g_socket_send_messages:
4765 * @socket: a #GSocket
4766 * @messages: (array length=num_messages): an array of #GOutputMessage structs
4767 * @num_messages: the number of elements in @messages
4768 * @flags: an int containing #GSocketMsgFlags flags
4769 * @cancellable: (nullable): a %GCancellable or %NULL
4770 * @error: #GError for error reporting, or %NULL to ignore.
4772 * Send multiple data messages from @socket in one go. This is the most
4773 * complicated and fully-featured version of this call. For easier use, see
4774 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
4776 * @messages must point to an array of #GOutputMessage structs and
4777 * @num_messages must be the length of this array. Each #GOutputMessage
4778 * contains an address to send the data to, and a pointer to an array of
4779 * #GOutputVector structs to describe the buffers that the data to be sent
4780 * for each message will be gathered from. Using multiple #GOutputVectors is
4781 * more memory-efficient than manually copying data from multiple sources
4782 * into a single buffer, and more network-efficient than making multiple
4783 * calls to g_socket_send(). Sending multiple messages in one go avoids the
4784 * overhead of making a lot of syscalls in scenarios where a lot of data
4785 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
4786 * or where the same data needs to be sent to multiple recipients.
4788 * @flags modify how the message is sent. The commonly available arguments
4789 * for this are available in the #GSocketMsgFlags enum, but the
4790 * values there are the same as the system values, and the flags
4791 * are passed in as-is, so you can pass in system-specific flags too.
4793 * If the socket is in blocking mode the call will block until there is
4794 * space for all the data in the socket queue. If there is no space available
4795 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4796 * will be returned if no data was written at all, otherwise the number of
4797 * messages sent will be returned. To be notified when space is available,
4798 * wait for the %G_IO_OUT condition. Note though that you may still receive
4799 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4800 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4801 * very common due to the way the underlying APIs work.)
4803 * On error -1 is returned and @error is set accordingly. An error will only
4804 * be returned if zero messages could be sent; otherwise the number of messages
4805 * successfully sent before the error will be returned.
4807 * Returns: number of messages sent, or -1 on error. Note that the number of
4808 * messages sent may be smaller than @num_messages if the socket is
4809 * non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
4810 * in which case the caller may re-try to send the remaining messages.
4815 g_socket_send_messages (GSocket
*socket
,
4816 GOutputMessage
*messages
,
4819 GCancellable
*cancellable
,
4822 return g_socket_send_messages_with_timeout (socket
, messages
, num_messages
,
4824 socket
->priv
->blocking
? -1 : 0,
4825 cancellable
, error
);
4829 g_socket_send_messages_with_timeout (GSocket
*socket
,
4830 GOutputMessage
*messages
,
4834 GCancellable
*cancellable
,
4839 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
4840 g_return_val_if_fail (num_messages
== 0 || messages
!= NULL
, -1);
4841 g_return_val_if_fail (cancellable
== NULL
|| G_IS_CANCELLABLE (cancellable
), -1);
4842 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, -1);
4844 start_time
= g_get_monotonic_time ();
4846 if (!check_socket (socket
, error
))
4849 if (!check_timeout (socket
, error
))
4852 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
4855 if (num_messages
== 0)
4858 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
4860 struct mmsghdr
*msgvec
;
4864 #define MAX_NUM_MESSAGES UIO_MAXIOV
4866 #define MAX_NUM_MESSAGES 1024
4869 if (num_messages
> MAX_NUM_MESSAGES
)
4870 num_messages
= MAX_NUM_MESSAGES
;
4872 msgvec
= g_newa (struct mmsghdr
, num_messages
);
4874 for (i
= 0; i
< num_messages
; ++i
)
4876 GOutputMessage
*msg
= &messages
[i
];
4877 struct msghdr
*msg_hdr
= &msgvec
[i
].msg_hdr
;
4878 GError
*child_error
= NULL
;
4880 msgvec
[i
].msg_len
= 0;
4882 output_message_to_msghdr (msg
, (i
> 0) ? &messages
[i
- 1] : NULL
,
4883 msg_hdr
, (i
> 0) ? &msgvec
[i
- 1].msg_hdr
: NULL
,
4886 if (child_error
!= NULL
)
4888 g_propagate_error (error
, child_error
);
4893 for (num_sent
= 0; num_sent
< num_messages
;)
4897 ret
= sendmmsg (socket
->priv
->fd
, msgvec
+ num_sent
, num_messages
- num_sent
,
4898 flags
| G_SOCKET_DEFAULT_SEND_FLAGS
);
4902 int errsv
= get_socket_errno ();
4908 (errsv
== EWOULDBLOCK
||
4911 if (!block_on_timeout (socket
, G_IO_OUT
, timeout
, start_time
,
4912 cancellable
, error
))
4916 g_clear_error (error
);
4926 /* If any messages were successfully sent, do not error. */
4930 socket_set_error_lazy (error
, errsv
, _("Error sending message: %s"));
4938 for (i
= 0; i
< num_sent
; ++i
)
4939 messages
[i
].bytes_sent
= msgvec
[i
].msg_len
;
4947 gint64 wait_timeout
;
4949 wait_timeout
= timeout
;
4951 for (i
= 0; i
< num_messages
; ++i
)
4953 GOutputMessage
*msg
= &messages
[i
];
4954 GError
*msg_error
= NULL
;
4956 result
= g_socket_send_message_with_timeout (socket
, msg
->address
,
4959 msg
->control_messages
,
4960 msg
->num_control_messages
,
4961 flags
, wait_timeout
,
4962 cancellable
, &msg_error
);
4964 /* check if we've timed out or how much time to wait at most */
4967 gint64 elapsed
= g_get_monotonic_time () - start_time
;
4968 wait_timeout
= MAX (timeout
- elapsed
, 1);
4973 /* if we couldn't send all messages, just return how many we did
4974 * manage to send, provided we managed to send at least one */
4977 g_error_free (msg_error
);
4982 g_propagate_error (error
, msg_error
);
4987 msg
->bytes_sent
= result
;
4995 static GSocketAddress
*
4996 cache_recv_address (GSocket
*socket
, struct sockaddr
*native
, int native_len
)
4998 GSocketAddress
*saddr
;
5000 guint64 oldest_time
= G_MAXUINT64
;
5001 gint oldest_index
= 0;
5003 if (native_len
<= 0)
5007 for (i
= 0; i
< RECV_ADDR_CACHE_SIZE
; i
++)
5009 GSocketAddress
*tmp
= socket
->priv
->recv_addr_cache
[i
].addr
;
5010 gpointer tmp_native
= socket
->priv
->recv_addr_cache
[i
].native
;
5011 gint tmp_native_len
= socket
->priv
->recv_addr_cache
[i
].native_len
;
5016 if (tmp_native_len
!= native_len
)
5019 if (memcmp (tmp_native
, native
, native_len
) == 0)
5021 saddr
= g_object_ref (tmp
);
5022 socket
->priv
->recv_addr_cache
[i
].last_used
= g_get_monotonic_time ();
5026 if (socket
->priv
->recv_addr_cache
[i
].last_used
< oldest_time
)
5028 oldest_time
= socket
->priv
->recv_addr_cache
[i
].last_used
;
5033 saddr
= g_socket_address_new_from_native (native
, native_len
);
5035 if (socket
->priv
->recv_addr_cache
[oldest_index
].addr
)
5037 g_object_unref (socket
->priv
->recv_addr_cache
[oldest_index
].addr
);
5038 g_free (socket
->priv
->recv_addr_cache
[oldest_index
].native
);
5041 socket
->priv
->recv_addr_cache
[oldest_index
].native
= g_memdup (native
, native_len
);
5042 socket
->priv
->recv_addr_cache
[oldest_index
].native_len
= native_len
;
5043 socket
->priv
->recv_addr_cache
[oldest_index
].addr
= g_object_ref (saddr
);
5044 socket
->priv
->recv_addr_cache
[oldest_index
].last_used
= g_get_monotonic_time ();
5050 g_socket_receive_message_with_timeout (GSocket
*socket
,
5051 GSocketAddress
**address
,
5052 GInputVector
*vectors
,
5054 GSocketControlMessage
***messages
,
5058 GCancellable
*cancellable
,
5061 GInputVector one_vector
;
5065 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
5067 start_time
= g_get_monotonic_time ();
5069 if (!check_socket (socket
, error
))
5072 if (!check_timeout (socket
, error
))
5075 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
5078 if (num_vectors
== -1)
5080 for (num_vectors
= 0;
5081 vectors
[num_vectors
].buffer
!= NULL
;
5086 if (num_vectors
== 0)
5088 one_vector
.buffer
= &one_byte
;
5089 one_vector
.size
= 1;
5091 vectors
= &one_vector
;
5096 GInputMessage input_message
;
5100 input_message
.address
= address
;
5101 input_message
.vectors
= vectors
;
5102 input_message
.num_vectors
= num_vectors
;
5103 input_message
.bytes_received
= 0;
5104 input_message
.flags
= (flags
!= NULL
) ? *flags
: 0;
5105 input_message
.control_messages
= messages
;
5106 input_message
.num_control_messages
= (guint
*) num_messages
;
5108 /* We always set the close-on-exec flag so we don't leak file
5109 * descriptors into child processes. Note that gunixfdmessage.c
5110 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5112 #ifdef MSG_CMSG_CLOEXEC
5113 input_message
.flags
|= MSG_CMSG_CLOEXEC
;
5116 input_message_to_msghdr (&input_message
, &msg
);
5121 result
= recvmsg (socket
->priv
->fd
, &msg
, msg
.msg_flags
);
5122 #ifdef MSG_CMSG_CLOEXEC
5123 if (result
< 0 && get_socket_errno () == EINVAL
)
5125 /* We must be running on an old kernel. Call without the flag. */
5126 msg
.msg_flags
&= ~(MSG_CMSG_CLOEXEC
);
5127 result
= recvmsg (socket
->priv
->fd
, &msg
, msg
.msg_flags
);
5133 int errsv
= get_socket_errno ();
5139 (errsv
== EWOULDBLOCK
||
5142 if (!block_on_timeout (socket
, G_IO_IN
, timeout
, start_time
,
5143 cancellable
, error
))
5149 socket_set_error_lazy (error
, errsv
, _("Error receiving message: %s"));
5155 input_message_from_msghdr (&msg
, &input_message
, socket
);
5158 *flags
= input_message
.flags
;
5164 struct sockaddr_storage addr
;
5166 DWORD bytes_received
;
5173 bufs
= g_newa (WSABUF
, num_vectors
);
5174 for (i
= 0; i
< num_vectors
; i
++)
5176 bufs
[i
].buf
= (char *)vectors
[i
].buffer
;
5177 bufs
[i
].len
= (gulong
)vectors
[i
].size
;
5189 win32_unset_event_mask (socket
, FD_READ
);
5191 addrlen
= sizeof addr
;
5193 result
= WSARecvFrom (socket
->priv
->fd
,
5195 &bytes_received
, &win_flags
,
5196 (struct sockaddr
*)&addr
, &addrlen
,
5199 result
= WSARecv (socket
->priv
->fd
,
5201 &bytes_received
, &win_flags
,
5205 int errsv
= get_socket_errno ();
5207 if (errsv
== WSAEINTR
)
5210 if (errsv
== WSAEWOULDBLOCK
)
5214 if (!block_on_timeout (socket
, G_IO_IN
, timeout
,
5215 start_time
, cancellable
, error
))
5222 socket_set_error_lazy (error
, errsv
, _("Error receiving message: %s"));
5228 /* decode address */
5229 if (address
!= NULL
)
5231 *address
= cache_recv_address (socket
, (struct sockaddr
*)&addr
, addrlen
);
5234 /* capture the flags */
5238 if (messages
!= NULL
)
5240 if (num_messages
!= NULL
)
5243 return bytes_received
;
5249 * g_socket_receive_messages:
5250 * @socket: a #GSocket
5251 * @messages: (array length=num_messages): an array of #GInputMessage structs
5252 * @num_messages: the number of elements in @messages
5253 * @flags: an int containing #GSocketMsgFlags flags for the overall operation
5254 * @cancellable: (nullable): a %GCancellable or %NULL
5255 * @error: #GError for error reporting, or %NULL to ignore
5257 * Receive multiple data messages from @socket in one go. This is the most
5258 * complicated and fully-featured version of this call. For easier use, see
5259 * g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
5261 * @messages must point to an array of #GInputMessage structs and
5262 * @num_messages must be the length of this array. Each #GInputMessage
5263 * contains a pointer to an array of #GInputVector structs describing the
5264 * buffers that the data received in each message will be written to. Using
5265 * multiple #GInputVectors is more memory-efficient than manually copying data
5266 * out of a single buffer to multiple sources, and more system-call-efficient
5267 * than making multiple calls to g_socket_receive(), such as in scenarios where
5268 * a lot of data packets need to be received (e.g. high-bandwidth video
5269 * streaming over RTP/UDP).
5271 * @flags modify how all messages are received. The commonly available
5272 * arguments for this are available in the #GSocketMsgFlags enum, but the
5273 * values there are the same as the system values, and the flags
5274 * are passed in as-is, so you can pass in system-specific flags too. These
5275 * flags affect the overall receive operation. Flags affecting individual
5276 * messages are returned in #GInputMessage.flags.
5278 * The other members of #GInputMessage are treated as described in its
5281 * If #GSocket:blocking is %TRUE the call will block until @num_messages have
5282 * been received, or the end of the stream is reached.
5284 * If #GSocket:blocking is %FALSE the call will return up to @num_messages
5285 * without blocking, or %G_IO_ERROR_WOULD_BLOCK if no messages are queued in the
5286 * operating system to be received.
5288 * In blocking mode, if #GSocket:timeout is positive and is reached before any
5289 * messages are received, %G_IO_ERROR_TIMED_OUT is returned, otherwise up to
5290 * @num_messages are returned. (Note: This is effectively the
5291 * behaviour of `MSG_WAITFORONE` with recvmmsg().)
5293 * To be notified when messages are available, wait for the
5294 * %G_IO_IN condition. Note though that you may still receive
5295 * %G_IO_ERROR_WOULD_BLOCK from g_socket_receive_messages() even if you were
5296 * previously notified of a %G_IO_IN condition.
5298 * If the remote peer closes the connection, any messages queued in the
5299 * operating system will be returned, and subsequent calls to
5300 * g_socket_receive_messages() will return 0 (with no error set).
5302 * On error -1 is returned and @error is set accordingly. An error will only
5303 * be returned if zero messages could be received; otherwise the number of
5304 * messages successfully received before the error will be returned.
5306 * Returns: number of messages received, or -1 on error. Note that the number
5307 * of messages received may be smaller than @num_messages if in non-blocking
5308 * mode, if the peer closed the connection, or if @num_messages
5309 * was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
5310 * to receive the remaining messages.
5315 g_socket_receive_messages (GSocket
*socket
,
5316 GInputMessage
*messages
,
5319 GCancellable
*cancellable
,
5322 if (!check_socket (socket
, error
) ||
5323 !check_timeout (socket
, error
))
5326 return g_socket_receive_messages_with_timeout (socket
, messages
, num_messages
,
5328 socket
->priv
->blocking
? -1 : 0,
5329 cancellable
, error
);
5333 g_socket_receive_messages_with_timeout (GSocket
*socket
,
5334 GInputMessage
*messages
,
5338 GCancellable
*cancellable
,
5343 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
5344 g_return_val_if_fail (num_messages
== 0 || messages
!= NULL
, -1);
5345 g_return_val_if_fail (cancellable
== NULL
||
5346 G_IS_CANCELLABLE (cancellable
), -1);
5347 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, -1);
5349 start_time
= g_get_monotonic_time ();
5351 if (!check_socket (socket
, error
))
5354 if (!check_timeout (socket
, error
))
5357 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
5360 if (num_messages
== 0)
5363 #if !defined (G_OS_WIN32) && defined (HAVE_RECVMMSG)
5365 struct mmsghdr
*msgvec
;
5366 guint i
, num_received
;
5369 #define MAX_NUM_MESSAGES UIO_MAXIOV
5371 #define MAX_NUM_MESSAGES 1024
5374 if (num_messages
> MAX_NUM_MESSAGES
)
5375 num_messages
= MAX_NUM_MESSAGES
;
5377 msgvec
= g_newa (struct mmsghdr
, num_messages
);
5379 for (i
= 0; i
< num_messages
; ++i
)
5381 GInputMessage
*msg
= &messages
[i
];
5382 struct msghdr
*msg_hdr
= &msgvec
[i
].msg_hdr
;
5384 input_message_to_msghdr (msg
, msg_hdr
);
5385 msgvec
[i
].msg_len
= 0;
5388 /* We always set the close-on-exec flag so we don't leak file
5389 * descriptors into child processes. Note that gunixfdmessage.c
5390 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5392 #ifdef MSG_CMSG_CLOEXEC
5393 flags
|= MSG_CMSG_CLOEXEC
;
5396 for (num_received
= 0; num_received
< num_messages
;)
5400 /* We operate in non-blocking mode and handle the timeout ourselves. */
5401 ret
= recvmmsg (socket
->priv
->fd
,
5402 msgvec
+ num_received
,
5403 num_messages
- num_received
,
5404 flags
| G_SOCKET_DEFAULT_SEND_FLAGS
, NULL
);
5405 #ifdef MSG_CMSG_CLOEXEC
5406 if (ret
< 0 && get_socket_errno () == EINVAL
)
5408 /* We must be running on an old kernel. Call without the flag. */
5409 flags
&= ~(MSG_CMSG_CLOEXEC
);
5410 ret
= recvmmsg (socket
->priv
->fd
,
5411 msgvec
+ num_received
,
5412 num_messages
- num_received
,
5413 flags
| G_SOCKET_DEFAULT_SEND_FLAGS
, NULL
);
5419 int errsv
= get_socket_errno ();
5425 (errsv
== EWOULDBLOCK
||
5428 if (!block_on_timeout (socket
, G_IO_IN
, timeout
, start_time
,
5429 cancellable
, error
))
5431 if (num_received
> 0)
5433 g_clear_error (error
);
5443 /* If any messages were successfully received, do not error. */
5444 if (num_received
> 0)
5447 socket_set_error_lazy (error
, errsv
,
5448 _("Error receiving message: %s"));
5458 num_received
+= ret
;
5461 for (i
= 0; i
< num_received
; ++i
)
5463 input_message_from_msghdr (&msgvec
[i
].msg_hdr
, &messages
[i
], socket
);
5464 messages
[i
].bytes_received
= msgvec
[i
].msg_len
;
5467 return num_received
;
5472 gint64 wait_timeout
;
5474 wait_timeout
= timeout
;
5476 for (i
= 0; i
< num_messages
; i
++)
5478 GInputMessage
*msg
= &messages
[i
];
5480 GError
*msg_error
= NULL
;
5482 msg
->flags
= flags
; /* in-out parameter */
5484 len
= g_socket_receive_message_with_timeout (socket
,
5488 msg
->control_messages
,
5489 (gint
*) msg
->num_control_messages
,
5495 /* check if we've timed out or how much time to wait at most */
5498 gint64 elapsed
= g_get_monotonic_time () - start_time
;
5499 wait_timeout
= MAX (timeout
- elapsed
, 1);
5503 msg
->bytes_received
= len
;
5506 (g_error_matches (msg_error
, G_IO_ERROR
, G_IO_ERROR_WOULD_BLOCK
) ||
5507 g_error_matches (msg_error
, G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
)))
5509 g_clear_error (&msg_error
);
5513 if (msg_error
!= NULL
)
5515 g_propagate_error (error
, msg_error
);
5529 * g_socket_receive_message:
5530 * @socket: a #GSocket
5531 * @address: (out) (optional): a pointer to a #GSocketAddress
5533 * @vectors: (array length=num_vectors): an array of #GInputVector structs
5534 * @num_vectors: the number of elements in @vectors, or -1
5535 * @messages: (array length=num_messages) (out) (optional) (nullable): a pointer
5536 * which may be filled with an array of #GSocketControlMessages, or %NULL
5537 * @num_messages: (out): a pointer which will be filled with the number of
5538 * elements in @messages, or %NULL
5539 * @flags: (inout): a pointer to an int containing #GSocketMsgFlags flags
5540 * @cancellable: a %GCancellable or %NULL
5541 * @error: a #GError pointer, or %NULL
5543 * Receive data from a socket. For receiving multiple messages, see
5544 * g_socket_receive_messages(); for easier use, see
5545 * g_socket_receive() and g_socket_receive_from().
5547 * If @address is non-%NULL then @address will be set equal to the
5548 * source address of the received packet.
5549 * @address is owned by the caller.
5551 * @vector must point to an array of #GInputVector structs and
5552 * @num_vectors must be the length of this array. These structs
5553 * describe the buffers that received data will be scattered into.
5554 * If @num_vectors is -1, then @vectors is assumed to be terminated
5555 * by a #GInputVector with a %NULL buffer pointer.
5557 * As a special case, if @num_vectors is 0 (in which case, @vectors
5558 * may of course be %NULL), then a single byte is received and
5559 * discarded. This is to facilitate the common practice of sending a
5560 * single '\0' byte for the purposes of transferring ancillary data.
5562 * @messages, if non-%NULL, will be set to point to a newly-allocated
5563 * array of #GSocketControlMessage instances or %NULL if no such
5564 * messages was received. These correspond to the control messages
5565 * received from the kernel, one #GSocketControlMessage per message
5566 * from the kernel. This array is %NULL-terminated and must be freed
5567 * by the caller using g_free() after calling g_object_unref() on each
5568 * element. If @messages is %NULL, any control messages received will
5571 * @num_messages, if non-%NULL, will be set to the number of control
5572 * messages received.
5574 * If both @messages and @num_messages are non-%NULL, then
5575 * @num_messages gives the number of #GSocketControlMessage instances
5576 * in @messages (ie: not including the %NULL terminator).
5578 * @flags is an in/out parameter. The commonly available arguments
5579 * for this are available in the #GSocketMsgFlags enum, but the
5580 * values there are the same as the system values, and the flags
5581 * are passed in as-is, so you can pass in system-specific flags too
5582 * (and g_socket_receive_message() may pass system-specific flags out).
5583 * Flags passed in to the parameter affect the receive operation; flags returned
5584 * out of it are relevant to the specific returned message.
5586 * As with g_socket_receive(), data may be discarded if @socket is
5587 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
5588 * provide enough buffer space to read a complete message. You can pass
5589 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
5590 * removing it from the receive queue, but there is no portable way to find
5591 * out the length of the message other than by reading it into a
5592 * sufficiently-large buffer.
5594 * If the socket is in blocking mode the call will block until there
5595 * is some data to receive, the connection is closed, or there is an
5596 * error. If there is no data available and the socket is in
5597 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
5598 * returned. To be notified when data is available, wait for the
5599 * %G_IO_IN condition.
5601 * On error -1 is returned and @error is set accordingly.
5603 * Returns: Number of bytes read, or 0 if the connection was closed by
5604 * the peer, or -1 on error
5609 g_socket_receive_message (GSocket
*socket
,
5610 GSocketAddress
**address
,
5611 GInputVector
*vectors
,
5613 GSocketControlMessage
***messages
,
5616 GCancellable
*cancellable
,
5619 return g_socket_receive_message_with_timeout (socket
, address
, vectors
,
5620 num_vectors
, messages
,
5621 num_messages
, flags
,
5622 socket
->priv
->blocking
? -1 : 0,
5623 cancellable
, error
);
5627 * g_socket_get_credentials:
5628 * @socket: a #GSocket.
5629 * @error: #GError for error reporting, or %NULL to ignore.
5631 * Returns the credentials of the foreign process connected to this
5632 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
5635 * If this operation isn't supported on the OS, the method fails with
5636 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
5637 * by reading the %SO_PEERCRED option on the underlying socket.
5639 * Other ways to obtain credentials from a foreign peer includes the
5640 * #GUnixCredentialsMessage type and
5641 * g_unix_connection_send_credentials() /
5642 * g_unix_connection_receive_credentials() functions.
5644 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
5645 * that must be freed with g_object_unref().
5650 g_socket_get_credentials (GSocket
*socket
,
5655 g_return_val_if_fail (G_IS_SOCKET (socket
), NULL
);
5656 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
5660 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
5664 guint8 native_creds_buf
[G_CREDENTIALS_NATIVE_SIZE
];
5665 socklen_t optlen
= sizeof (native_creds_buf
);
5667 if (getsockopt (socket
->priv
->fd
,
5673 ret
= g_credentials_new ();
5674 g_credentials_set_native (ret
,
5675 G_CREDENTIALS_NATIVE_TYPE
,
5679 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
5681 struct unpcbid cred
;
5682 socklen_t optlen
= sizeof (cred
);
5684 if (getsockopt (socket
->priv
->fd
,
5690 ret
= g_credentials_new ();
5691 g_credentials_set_native (ret
,
5692 G_CREDENTIALS_NATIVE_TYPE
,
5696 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
5698 ucred_t
*ucred
= NULL
;
5700 if (getpeerucred (socket
->priv
->fd
, &ucred
) == 0)
5702 ret
= g_credentials_new ();
5703 g_credentials_set_native (ret
,
5704 G_CREDENTIALS_TYPE_SOLARIS_UCRED
,
5710 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
5715 int errsv
= get_socket_errno ();
5719 socket_io_error_from_errno (errsv
),
5720 _("Unable to read socket credentials: %s"),
5721 socket_strerror (errsv
));
5726 g_set_error_literal (error
,
5728 G_IO_ERROR_NOT_SUPPORTED
,
5729 _("g_socket_get_credentials not implemented for this OS"));
5736 * g_socket_get_option:
5737 * @socket: a #GSocket
5738 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5739 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5740 * @value: (out): return location for the option value
5741 * @error: #GError for error reporting, or %NULL to ignore.
5743 * Gets the value of an integer-valued option on @socket, as with
5744 * getsockopt(). (If you need to fetch a non-integer-valued option,
5745 * you will need to call getsockopt() directly.)
5747 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5748 * header pulls in system headers that will define most of the
5749 * standard/portable socket options. For unusual socket protocols or
5750 * platform-dependent options, you may need to include additional
5753 * Note that even for socket options that are a single byte in size,
5754 * @value is still a pointer to a #gint variable, not a #guchar;
5755 * g_socket_get_option() will handle the conversion internally.
5757 * Returns: success or failure. On failure, @error will be set, and
5758 * the system error value (`errno` or WSAGetLastError()) will still
5759 * be set to the result of the getsockopt() call.
5764 g_socket_get_option (GSocket
*socket
,
5772 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
5775 size
= sizeof (gint
);
5776 if (getsockopt (socket
->priv
->fd
, level
, optname
, value
, &size
) != 0)
5778 int errsv
= get_socket_errno ();
5780 g_set_error_literal (error
,
5782 socket_io_error_from_errno (errsv
),
5783 socket_strerror (errsv
));
5785 /* Reset errno in case the caller wants to look at it */
5791 #if G_BYTE_ORDER == G_BIG_ENDIAN
5792 /* If the returned value is smaller than an int then we need to
5793 * slide it over into the low-order bytes of *value.
5795 if (size
!= sizeof (gint
))
5796 *value
= *value
>> (8 * (sizeof (gint
) - size
));
5803 * g_socket_set_option:
5804 * @socket: a #GSocket
5805 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5806 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5807 * @value: the value to set the option to
5808 * @error: #GError for error reporting, or %NULL to ignore.
5810 * Sets the value of an integer-valued option on @socket, as with
5811 * setsockopt(). (If you need to set a non-integer-valued option,
5812 * you will need to call setsockopt() directly.)
5814 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5815 * header pulls in system headers that will define most of the
5816 * standard/portable socket options. For unusual socket protocols or
5817 * platform-dependent options, you may need to include additional
5820 * Returns: success or failure. On failure, @error will be set, and
5821 * the system error value (`errno` or WSAGetLastError()) will still
5822 * be set to the result of the setsockopt() call.
5827 g_socket_set_option (GSocket
*socket
,
5835 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
5837 if (setsockopt (socket
->priv
->fd
, level
, optname
, &value
, sizeof (gint
)) == 0)
5840 #if !defined (__linux__) && !defined (G_OS_WIN32)
5841 /* Linux and Windows let you set a single-byte value from an int,
5842 * but most other platforms don't.
5844 if (errno
== EINVAL
&& value
>= SCHAR_MIN
&& value
<= CHAR_MAX
)
5846 #if G_BYTE_ORDER == G_BIG_ENDIAN
5847 value
= value
<< (8 * (sizeof (gint
) - 1));
5849 if (setsockopt (socket
->priv
->fd
, level
, optname
, &value
, 1) == 0)
5854 errsv
= get_socket_errno ();
5856 g_set_error_literal (error
,
5858 socket_io_error_from_errno (errsv
),
5859 socket_strerror (errsv
));