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
)
425 struct sockaddr_storage storage
;
433 fd
= socket
->priv
->fd
;
434 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_TYPE
, &value
, NULL
))
436 errsv
= get_socket_errno ();
443 socket
->priv
->type
= G_SOCKET_TYPE_STREAM
;
447 socket
->priv
->type
= G_SOCKET_TYPE_DATAGRAM
;
451 socket
->priv
->type
= G_SOCKET_TYPE_SEQPACKET
;
455 socket
->priv
->type
= G_SOCKET_TYPE_INVALID
;
459 addrlen
= sizeof address
;
460 if (getsockname (fd
, &address
.sa
, &addrlen
) != 0)
462 errsv
= get_socket_errno ();
468 g_assert (G_STRUCT_OFFSET (struct sockaddr
, sa_family
) +
469 sizeof address
.storage
.ss_family
<= addrlen
);
470 family
= address
.storage
.ss_family
;
474 /* On Solaris, this happens if the socket is not yet connected.
475 * But we can use SO_DOMAIN as a workaround there.
478 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_DOMAIN
, &family
, NULL
))
480 errsv
= get_socket_errno ();
484 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
492 case G_SOCKET_FAMILY_IPV4
:
493 case G_SOCKET_FAMILY_IPV6
:
494 socket
->priv
->family
= address
.storage
.ss_family
;
495 switch (socket
->priv
->type
)
497 case G_SOCKET_TYPE_STREAM
:
498 socket
->priv
->protocol
= G_SOCKET_PROTOCOL_TCP
;
501 case G_SOCKET_TYPE_DATAGRAM
:
502 socket
->priv
->protocol
= G_SOCKET_PROTOCOL_UDP
;
505 case G_SOCKET_TYPE_SEQPACKET
:
506 socket
->priv
->protocol
= G_SOCKET_PROTOCOL_SCTP
;
514 case G_SOCKET_FAMILY_UNIX
:
515 socket
->priv
->family
= G_SOCKET_FAMILY_UNIX
;
516 socket
->priv
->protocol
= G_SOCKET_PROTOCOL_DEFAULT
;
520 socket
->priv
->family
= G_SOCKET_FAMILY_INVALID
;
524 if (socket
->priv
->family
!= G_SOCKET_FAMILY_INVALID
)
526 addrlen
= sizeof address
;
527 if (getpeername (fd
, &address
.sa
, &addrlen
) >= 0)
529 socket
->priv
->connected_read
= TRUE
;
530 socket
->priv
->connected_write
= TRUE
;
534 if (g_socket_get_option (socket
, SOL_SOCKET
, SO_KEEPALIVE
, &value
, NULL
))
536 socket
->priv
->keepalive
= !!value
;
540 /* Can't read, maybe not supported, assume FALSE */
541 socket
->priv
->keepalive
= FALSE
;
547 g_set_error (&socket
->priv
->construct_error
, G_IO_ERROR
,
548 socket_io_error_from_errno (errsv
),
549 _("creating GSocket from fd: %s"),
550 socket_strerror (errsv
));
553 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
555 g_socket (gint domain
,
563 fd
= socket (domain
, type
| SOCK_CLOEXEC
, protocol
);
568 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
569 if (fd
< 0 && (errsv
== EINVAL
|| errsv
== EPROTOTYPE
))
571 fd
= socket (domain
, type
, protocol
);
575 errsv
= get_socket_errno ();
577 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
578 _("Unable to create socket: %s"), socket_strerror (errsv
));
587 /* We always want to set close-on-exec to protect users. If you
588 need to so some weird inheritance to exec you can re-enable this
589 using lower level hacks with g_socket_get_fd(). */
590 flags
= fcntl (fd
, F_GETFD
, 0);
592 (flags
& FD_CLOEXEC
) == 0)
595 fcntl (fd
, F_SETFD
, flags
);
604 g_socket_create_socket (GSocketFamily family
,
613 case G_SOCKET_TYPE_STREAM
:
614 native_type
= SOCK_STREAM
;
617 case G_SOCKET_TYPE_DATAGRAM
:
618 native_type
= SOCK_DGRAM
;
621 case G_SOCKET_TYPE_SEQPACKET
:
622 native_type
= SOCK_SEQPACKET
;
626 g_assert_not_reached ();
631 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_INVALID_ARGUMENT
,
632 _("Unable to create socket: %s"), _("Unknown family was specified"));
638 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_INVALID_ARGUMENT
,
639 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
643 return g_socket (family
, native_type
, protocol
, error
);
647 g_socket_constructed (GObject
*object
)
649 GSocket
*socket
= G_SOCKET (object
);
651 if (socket
->priv
->fd
>= 0)
652 /* create socket->priv info from the fd */
653 g_socket_details_from_fd (socket
);
656 /* create the fd from socket->priv info */
657 socket
->priv
->fd
= g_socket_create_socket (socket
->priv
->family
,
659 socket
->priv
->protocol
,
660 &socket
->priv
->construct_error
);
662 if (socket
->priv
->fd
!= -1)
665 GError
*error
= NULL
;
670 /* Always use native nonblocking sockets, as Windows sets sockets to
671 * nonblocking automatically in certain operations. This way we make
672 * things work the same on all platforms.
675 if (!g_unix_set_fd_nonblocking (socket
->priv
->fd
, TRUE
, &error
))
677 g_warning ("Error setting socket nonblocking: %s", error
->message
);
678 g_clear_error (&error
);
683 if (ioctlsocket (socket
->priv
->fd
, FIONBIO
, &arg
) == SOCKET_ERROR
)
685 int errsv
= get_socket_errno ();
686 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv
));
691 /* See note about SIGPIPE below. */
692 g_socket_set_option (socket
, SOL_SOCKET
, SO_NOSIGPIPE
, TRUE
, NULL
);
698 g_socket_get_property (GObject
*object
,
703 GSocket
*socket
= G_SOCKET (object
);
704 GSocketAddress
*address
;
709 g_value_set_enum (value
, socket
->priv
->family
);
713 g_value_set_enum (value
, socket
->priv
->type
);
717 g_value_set_enum (value
, socket
->priv
->protocol
);
721 g_value_set_int (value
, socket
->priv
->fd
);
725 g_value_set_boolean (value
, socket
->priv
->blocking
);
728 case PROP_LISTEN_BACKLOG
:
729 g_value_set_int (value
, socket
->priv
->listen_backlog
);
733 g_value_set_boolean (value
, socket
->priv
->keepalive
);
736 case PROP_LOCAL_ADDRESS
:
737 address
= g_socket_get_local_address (socket
, NULL
);
738 g_value_take_object (value
, address
);
741 case PROP_REMOTE_ADDRESS
:
742 address
= g_socket_get_remote_address (socket
, NULL
);
743 g_value_take_object (value
, address
);
747 g_value_set_uint (value
, socket
->priv
->timeout
);
751 g_value_set_uint (value
, g_socket_get_ttl (socket
));
755 g_value_set_boolean (value
, g_socket_get_broadcast (socket
));
758 case PROP_MULTICAST_LOOPBACK
:
759 g_value_set_boolean (value
, g_socket_get_multicast_loopback (socket
));
762 case PROP_MULTICAST_TTL
:
763 g_value_set_uint (value
, g_socket_get_multicast_ttl (socket
));
767 G_OBJECT_WARN_INVALID_PROPERTY_ID (object
, prop_id
, pspec
);
772 g_socket_set_property (GObject
*object
,
777 GSocket
*socket
= G_SOCKET (object
);
782 socket
->priv
->family
= g_value_get_enum (value
);
786 socket
->priv
->type
= g_value_get_enum (value
);
790 socket
->priv
->protocol
= g_value_get_enum (value
);
794 socket
->priv
->fd
= g_value_get_int (value
);
798 g_socket_set_blocking (socket
, g_value_get_boolean (value
));
801 case PROP_LISTEN_BACKLOG
:
802 g_socket_set_listen_backlog (socket
, g_value_get_int (value
));
806 g_socket_set_keepalive (socket
, g_value_get_boolean (value
));
810 g_socket_set_timeout (socket
, g_value_get_uint (value
));
814 g_socket_set_ttl (socket
, g_value_get_uint (value
));
818 g_socket_set_broadcast (socket
, g_value_get_boolean (value
));
821 case PROP_MULTICAST_LOOPBACK
:
822 g_socket_set_multicast_loopback (socket
, g_value_get_boolean (value
));
825 case PROP_MULTICAST_TTL
:
826 g_socket_set_multicast_ttl (socket
, g_value_get_uint (value
));
830 G_OBJECT_WARN_INVALID_PROPERTY_ID (object
, prop_id
, pspec
);
835 g_socket_finalize (GObject
*object
)
837 GSocket
*socket
= G_SOCKET (object
);
840 g_clear_error (&socket
->priv
->construct_error
);
842 if (socket
->priv
->fd
!= -1 &&
843 !socket
->priv
->closed
)
844 g_socket_close (socket
, NULL
);
846 if (socket
->priv
->remote_address
)
847 g_object_unref (socket
->priv
->remote_address
);
850 if (socket
->priv
->event
!= WSA_INVALID_EVENT
)
852 WSACloseEvent (socket
->priv
->event
);
853 socket
->priv
->event
= WSA_INVALID_EVENT
;
856 g_assert (socket
->priv
->requested_conditions
== NULL
);
857 g_mutex_clear (&socket
->priv
->win32_source_lock
);
858 g_cond_clear (&socket
->priv
->win32_source_cond
);
861 for (i
= 0; i
< RECV_ADDR_CACHE_SIZE
; i
++)
863 if (socket
->priv
->recv_addr_cache
[i
].addr
)
865 g_object_unref (socket
->priv
->recv_addr_cache
[i
].addr
);
866 g_free (socket
->priv
->recv_addr_cache
[i
].native
);
870 if (G_OBJECT_CLASS (g_socket_parent_class
)->finalize
)
871 (*G_OBJECT_CLASS (g_socket_parent_class
)->finalize
) (object
);
875 g_socket_class_init (GSocketClass
*klass
)
877 GObjectClass
*gobject_class G_GNUC_UNUSED
= G_OBJECT_CLASS (klass
);
880 /* There is no portable, thread-safe way to avoid having the process
881 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
882 * forced to simply ignore the signal process-wide.
884 * Even if we ignore it though, gdb will still stop if the app
885 * receives a SIGPIPE, which can be confusing and annoying. So when
886 * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
887 * prevent the signal from occurring at all.
889 signal (SIGPIPE
, SIG_IGN
);
892 gobject_class
->finalize
= g_socket_finalize
;
893 gobject_class
->constructed
= g_socket_constructed
;
894 gobject_class
->set_property
= g_socket_set_property
;
895 gobject_class
->get_property
= g_socket_get_property
;
897 g_object_class_install_property (gobject_class
, PROP_FAMILY
,
898 g_param_spec_enum ("family",
900 P_("The sockets address family"),
901 G_TYPE_SOCKET_FAMILY
,
902 G_SOCKET_FAMILY_INVALID
,
903 G_PARAM_CONSTRUCT_ONLY
|
905 G_PARAM_STATIC_STRINGS
));
907 g_object_class_install_property (gobject_class
, PROP_TYPE
,
908 g_param_spec_enum ("type",
910 P_("The sockets type"),
912 G_SOCKET_TYPE_STREAM
,
913 G_PARAM_CONSTRUCT_ONLY
|
915 G_PARAM_STATIC_STRINGS
));
917 g_object_class_install_property (gobject_class
, PROP_PROTOCOL
,
918 g_param_spec_enum ("protocol",
919 P_("Socket protocol"),
920 P_("The id of the protocol to use, or -1 for unknown"),
921 G_TYPE_SOCKET_PROTOCOL
,
922 G_SOCKET_PROTOCOL_UNKNOWN
,
923 G_PARAM_CONSTRUCT_ONLY
|
925 G_PARAM_STATIC_STRINGS
));
927 g_object_class_install_property (gobject_class
, PROP_FD
,
928 g_param_spec_int ("fd",
929 P_("File descriptor"),
930 P_("The sockets file descriptor"),
934 G_PARAM_CONSTRUCT_ONLY
|
936 G_PARAM_STATIC_STRINGS
));
938 g_object_class_install_property (gobject_class
, PROP_BLOCKING
,
939 g_param_spec_boolean ("blocking",
941 P_("Whether or not I/O on this socket is blocking"),
944 G_PARAM_STATIC_STRINGS
));
946 g_object_class_install_property (gobject_class
, PROP_LISTEN_BACKLOG
,
947 g_param_spec_int ("listen-backlog",
948 P_("Listen backlog"),
949 P_("Outstanding connections in the listen queue"),
954 G_PARAM_STATIC_STRINGS
));
956 g_object_class_install_property (gobject_class
, PROP_KEEPALIVE
,
957 g_param_spec_boolean ("keepalive",
958 P_("Keep connection alive"),
959 P_("Keep connection alive by sending periodic pings"),
962 G_PARAM_STATIC_STRINGS
));
964 g_object_class_install_property (gobject_class
, PROP_LOCAL_ADDRESS
,
965 g_param_spec_object ("local-address",
967 P_("The local address the socket is bound to"),
968 G_TYPE_SOCKET_ADDRESS
,
970 G_PARAM_STATIC_STRINGS
));
972 g_object_class_install_property (gobject_class
, PROP_REMOTE_ADDRESS
,
973 g_param_spec_object ("remote-address",
974 P_("Remote address"),
975 P_("The remote address the socket is connected to"),
976 G_TYPE_SOCKET_ADDRESS
,
978 G_PARAM_STATIC_STRINGS
));
983 * The timeout in seconds on socket I/O
987 g_object_class_install_property (gobject_class
, PROP_TIMEOUT
,
988 g_param_spec_uint ("timeout",
990 P_("The timeout in seconds on socket I/O"),
995 G_PARAM_STATIC_STRINGS
));
1000 * Whether the socket should allow sending to broadcast addresses.
1004 g_object_class_install_property (gobject_class
, PROP_BROADCAST
,
1005 g_param_spec_boolean ("broadcast",
1007 P_("Whether to allow sending to broadcast addresses"),
1010 G_PARAM_STATIC_STRINGS
));
1015 * Time-to-live for outgoing unicast packets
1019 g_object_class_install_property (gobject_class
, PROP_TTL
,
1020 g_param_spec_uint ("ttl",
1022 P_("Time-to-live of outgoing unicast packets"),
1025 G_PARAM_STATIC_STRINGS
));
1028 * GSocket:multicast-loopback:
1030 * Whether outgoing multicast packets loop back to the local host.
1034 g_object_class_install_property (gobject_class
, PROP_MULTICAST_LOOPBACK
,
1035 g_param_spec_boolean ("multicast-loopback",
1036 P_("Multicast loopback"),
1037 P_("Whether outgoing multicast packets loop back to the local host"),
1040 G_PARAM_STATIC_STRINGS
));
1043 * GSocket:multicast-ttl:
1045 * Time-to-live out outgoing multicast packets
1049 g_object_class_install_property (gobject_class
, PROP_MULTICAST_TTL
,
1050 g_param_spec_uint ("multicast-ttl",
1051 P_("Multicast TTL"),
1052 P_("Time-to-live of outgoing multicast packets"),
1055 G_PARAM_STATIC_STRINGS
));
1059 g_socket_initable_iface_init (GInitableIface
*iface
)
1061 iface
->init
= g_socket_initable_init
;
1065 g_socket_datagram_based_iface_init (GDatagramBasedInterface
*iface
)
1067 iface
->receive_messages
= g_socket_datagram_based_receive_messages
;
1068 iface
->send_messages
= g_socket_datagram_based_send_messages
;
1069 iface
->create_source
= g_socket_datagram_based_create_source
;
1070 iface
->condition_check
= g_socket_datagram_based_condition_check
;
1071 iface
->condition_wait
= g_socket_datagram_based_condition_wait
;
1075 g_socket_init (GSocket
*socket
)
1077 socket
->priv
= g_socket_get_instance_private (socket
);
1079 socket
->priv
->fd
= -1;
1080 socket
->priv
->blocking
= TRUE
;
1081 socket
->priv
->listen_backlog
= 10;
1082 socket
->priv
->construct_error
= NULL
;
1084 socket
->priv
->event
= WSA_INVALID_EVENT
;
1085 g_mutex_init (&socket
->priv
->win32_source_lock
);
1086 g_cond_init (&socket
->priv
->win32_source_cond
);
1091 g_socket_initable_init (GInitable
*initable
,
1092 GCancellable
*cancellable
,
1097 g_return_val_if_fail (G_IS_SOCKET (initable
), FALSE
);
1099 socket
= G_SOCKET (initable
);
1101 if (cancellable
!= NULL
)
1103 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
1104 _("Cancellable initialization not supported"));
1108 socket
->priv
->inited
= TRUE
;
1110 if (socket
->priv
->construct_error
)
1113 *error
= g_error_copy (socket
->priv
->construct_error
);
1122 check_datagram_based (GDatagramBased
*self
,
1125 switch (g_socket_get_socket_type (G_SOCKET (self
)))
1127 case G_SOCKET_TYPE_INVALID
:
1128 case G_SOCKET_TYPE_STREAM
:
1129 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
1130 _("Cannot use datagram operations on a non-datagram "
1133 case G_SOCKET_TYPE_DATAGRAM
:
1134 case G_SOCKET_TYPE_SEQPACKET
:
1139 /* Due to us sharing #GSocketSource with the #GSocket implementation, it is
1140 * pretty tricky to split out #GSocket:timeout so that it does not affect
1141 * #GDatagramBased operations (but still affects #GSocket operations). It is
1142 * not worth that effort — just disallow it and require the user to specify
1143 * timeouts on a per-operation basis. */
1144 if (g_socket_get_timeout (G_SOCKET (self
)) != 0)
1146 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
1147 _("Cannot use datagram operations on a socket with a "
1156 g_socket_datagram_based_receive_messages (GDatagramBased
*self
,
1157 GInputMessage
*messages
,
1161 GCancellable
*cancellable
,
1164 if (!check_datagram_based (self
, error
))
1167 return g_socket_receive_messages_with_timeout (G_SOCKET (self
), messages
,
1168 num_messages
, flags
, timeout
,
1169 cancellable
, error
);
1173 g_socket_datagram_based_send_messages (GDatagramBased
*self
,
1174 GOutputMessage
*messages
,
1178 GCancellable
*cancellable
,
1181 if (!check_datagram_based (self
, error
))
1184 return g_socket_send_messages_with_timeout (G_SOCKET (self
), messages
,
1185 num_messages
, flags
, timeout
,
1186 cancellable
, error
);
1190 g_socket_datagram_based_create_source (GDatagramBased
*self
,
1191 GIOCondition condition
,
1192 GCancellable
*cancellable
)
1194 if (!check_datagram_based (self
, NULL
))
1197 return g_socket_create_source (G_SOCKET (self
), condition
, cancellable
);
1201 g_socket_datagram_based_condition_check (GDatagramBased
*datagram_based
,
1202 GIOCondition condition
)
1204 if (!check_datagram_based (datagram_based
, NULL
))
1207 return g_socket_condition_check (G_SOCKET (datagram_based
), condition
);
1211 g_socket_datagram_based_condition_wait (GDatagramBased
*datagram_based
,
1212 GIOCondition condition
,
1214 GCancellable
*cancellable
,
1217 if (!check_datagram_based (datagram_based
, error
))
1220 return g_socket_condition_timed_wait (G_SOCKET (datagram_based
), condition
,
1221 timeout
, cancellable
, error
);
1226 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1227 * @type: the socket type to use.
1228 * @protocol: the id of the protocol to use, or 0 for default.
1229 * @error: #GError for error reporting, or %NULL to ignore.
1231 * Creates a new #GSocket with the defined family, type and protocol.
1232 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1233 * for the family and type is used.
1235 * The @protocol is a family and type specific int that specifies what
1236 * kind of protocol to use. #GSocketProtocol lists several common ones.
1237 * Many families only support one protocol, and use 0 for this, others
1238 * support several and using 0 means to use the default protocol for
1239 * the family and type.
1241 * The protocol id is passed directly to the operating
1242 * system, so you can use protocols not listed in #GSocketProtocol if you
1243 * know the protocol number used for it.
1245 * Returns: a #GSocket or %NULL on error.
1246 * Free the returned object with g_object_unref().
1251 g_socket_new (GSocketFamily family
,
1253 GSocketProtocol protocol
,
1256 return G_SOCKET (g_initable_new (G_TYPE_SOCKET
,
1260 "protocol", protocol
,
1265 * g_socket_new_from_fd:
1266 * @fd: a native socket file descriptor.
1267 * @error: #GError for error reporting, or %NULL to ignore.
1269 * Creates a new #GSocket from a native file descriptor
1270 * or winsock SOCKET handle.
1272 * This reads all the settings from the file descriptor so that
1273 * all properties should work. Note that the file descriptor
1274 * will be set to non-blocking mode, independent on the blocking
1275 * mode of the #GSocket.
1277 * On success, the returned #GSocket takes ownership of @fd. On failure, the
1278 * caller must close @fd themselves.
1280 * Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
1281 * descriptor. Instead, a GError will be set with code %G_IO_ERROR_FAILED
1283 * Returns: a #GSocket or %NULL on error.
1284 * Free the returned object with g_object_unref().
1289 g_socket_new_from_fd (gint fd
,
1292 return G_SOCKET (g_initable_new (G_TYPE_SOCKET
,
1299 * g_socket_set_blocking:
1300 * @socket: a #GSocket.
1301 * @blocking: Whether to use blocking I/O or not.
1303 * Sets the blocking mode of the socket. In blocking mode
1304 * all operations (which don’t take an explicit blocking parameter) block until
1305 * they succeed or there is an error. In
1306 * non-blocking mode all functions return results immediately or
1307 * with a %G_IO_ERROR_WOULD_BLOCK error.
1309 * All sockets are created in blocking mode. However, note that the
1310 * platform level socket is always non-blocking, and blocking mode
1311 * is a GSocket level feature.
1316 g_socket_set_blocking (GSocket
*socket
,
1319 g_return_if_fail (G_IS_SOCKET (socket
));
1321 blocking
= !!blocking
;
1323 if (socket
->priv
->blocking
== blocking
)
1326 socket
->priv
->blocking
= blocking
;
1327 g_object_notify (G_OBJECT (socket
), "blocking");
1331 * g_socket_get_blocking:
1332 * @socket: a #GSocket.
1334 * Gets the blocking mode of the socket. For details on blocking I/O,
1335 * see g_socket_set_blocking().
1337 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1342 g_socket_get_blocking (GSocket
*socket
)
1344 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
1346 return socket
->priv
->blocking
;
1350 * g_socket_set_keepalive:
1351 * @socket: a #GSocket.
1352 * @keepalive: Value for the keepalive flag
1354 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1355 * this flag is set on a socket, the system will attempt to verify that the
1356 * remote socket endpoint is still present if a sufficiently long period of
1357 * time passes with no data being exchanged. If the system is unable to
1358 * verify the presence of the remote endpoint, it will automatically close
1361 * This option is only functional on certain kinds of sockets. (Notably,
1362 * %G_SOCKET_PROTOCOL_TCP sockets.)
1364 * The exact time between pings is system- and protocol-dependent, but will
1365 * normally be at least two hours. Most commonly, you would set this flag
1366 * on a server socket if you want to allow clients to remain idle for long
1367 * periods of time, but also want to ensure that connections are eventually
1368 * garbage-collected if clients crash or become unreachable.
1373 g_socket_set_keepalive (GSocket
*socket
,
1376 GError
*error
= NULL
;
1378 g_return_if_fail (G_IS_SOCKET (socket
));
1380 keepalive
= !!keepalive
;
1381 if (socket
->priv
->keepalive
== keepalive
)
1384 if (!g_socket_set_option (socket
, SOL_SOCKET
, SO_KEEPALIVE
,
1387 g_warning ("error setting keepalive: %s", error
->message
);
1388 g_error_free (error
);
1392 socket
->priv
->keepalive
= keepalive
;
1393 g_object_notify (G_OBJECT (socket
), "keepalive");
1397 * g_socket_get_keepalive:
1398 * @socket: a #GSocket.
1400 * Gets the keepalive mode of the socket. For details on this,
1401 * see g_socket_set_keepalive().
1403 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1408 g_socket_get_keepalive (GSocket
*socket
)
1410 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
1412 return socket
->priv
->keepalive
;
1416 * g_socket_get_listen_backlog:
1417 * @socket: a #GSocket.
1419 * Gets the listen backlog setting of the socket. For details on this,
1420 * see g_socket_set_listen_backlog().
1422 * Returns: the maximum number of pending connections.
1427 g_socket_get_listen_backlog (GSocket
*socket
)
1429 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
1431 return socket
->priv
->listen_backlog
;
1435 * g_socket_set_listen_backlog:
1436 * @socket: a #GSocket.
1437 * @backlog: the maximum number of pending connections.
1439 * Sets the maximum number of outstanding connections allowed
1440 * when listening on this socket. If more clients than this are
1441 * connecting to the socket and the application is not handling them
1442 * on time then the new connections will be refused.
1444 * Note that this must be called before g_socket_listen() and has no
1445 * effect if called after that.
1450 g_socket_set_listen_backlog (GSocket
*socket
,
1453 g_return_if_fail (G_IS_SOCKET (socket
));
1454 g_return_if_fail (!socket
->priv
->listening
);
1456 if (backlog
!= socket
->priv
->listen_backlog
)
1458 socket
->priv
->listen_backlog
= backlog
;
1459 g_object_notify (G_OBJECT (socket
), "listen-backlog");
1464 * g_socket_get_timeout:
1465 * @socket: a #GSocket.
1467 * Gets the timeout setting of the socket. For details on this, see
1468 * g_socket_set_timeout().
1470 * Returns: the timeout in seconds
1475 g_socket_get_timeout (GSocket
*socket
)
1477 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
1479 return socket
->priv
->timeout
;
1483 * g_socket_set_timeout:
1484 * @socket: a #GSocket.
1485 * @timeout: the timeout for @socket, in seconds, or 0 for none
1487 * Sets the time in seconds after which I/O operations on @socket will
1488 * time out if they have not yet completed.
1490 * On a blocking socket, this means that any blocking #GSocket
1491 * operation will time out after @timeout seconds of inactivity,
1492 * returning %G_IO_ERROR_TIMED_OUT.
1494 * On a non-blocking socket, calls to g_socket_condition_wait() will
1495 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1496 * created with g_socket_create_source() will trigger after
1497 * @timeout seconds of inactivity, with the requested condition
1498 * set, at which point calling g_socket_receive(), g_socket_send(),
1499 * g_socket_check_connect_result(), etc, will fail with
1500 * %G_IO_ERROR_TIMED_OUT.
1502 * If @timeout is 0 (the default), operations will never time out
1505 * Note that if an I/O operation is interrupted by a signal, this may
1506 * cause the timeout to be reset.
1511 g_socket_set_timeout (GSocket
*socket
,
1514 g_return_if_fail (G_IS_SOCKET (socket
));
1516 if (timeout
!= socket
->priv
->timeout
)
1518 socket
->priv
->timeout
= timeout
;
1519 g_object_notify (G_OBJECT (socket
), "timeout");
1525 * @socket: a #GSocket.
1527 * Gets the unicast time-to-live setting on @socket; see
1528 * g_socket_set_ttl() for more details.
1530 * Returns: the time-to-live setting on @socket
1535 g_socket_get_ttl (GSocket
*socket
)
1537 GError
*error
= NULL
;
1540 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
1542 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1544 g_socket_get_option (socket
, IPPROTO_IP
, IP_TTL
,
1547 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1549 g_socket_get_option (socket
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
,
1553 g_return_val_if_reached (0);
1557 g_warning ("error getting unicast ttl: %s", error
->message
);
1558 g_error_free (error
);
1567 * @socket: a #GSocket.
1568 * @ttl: the time-to-live value for all unicast packets on @socket
1570 * Sets the time-to-live for outgoing unicast packets on @socket.
1571 * By default the platform-specific default value is used.
1576 g_socket_set_ttl (GSocket
*socket
,
1579 GError
*error
= NULL
;
1581 g_return_if_fail (G_IS_SOCKET (socket
));
1583 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1585 g_socket_set_option (socket
, IPPROTO_IP
, IP_TTL
,
1588 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1590 g_socket_set_option (socket
, IPPROTO_IP
, IP_TTL
,
1592 g_socket_set_option (socket
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
,
1596 g_return_if_reached ();
1600 g_warning ("error setting unicast ttl: %s", error
->message
);
1601 g_error_free (error
);
1605 g_object_notify (G_OBJECT (socket
), "ttl");
1609 * g_socket_get_broadcast:
1610 * @socket: a #GSocket.
1612 * Gets the broadcast setting on @socket; if %TRUE,
1613 * it is possible to send packets to broadcast
1616 * Returns: the broadcast setting on @socket
1621 g_socket_get_broadcast (GSocket
*socket
)
1623 GError
*error
= NULL
;
1626 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
1628 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_BROADCAST
,
1631 g_warning ("error getting broadcast: %s", error
->message
);
1632 g_error_free (error
);
1640 * g_socket_set_broadcast:
1641 * @socket: a #GSocket.
1642 * @broadcast: whether @socket should allow sending to broadcast
1645 * Sets whether @socket should allow sending to broadcast addresses.
1646 * This is %FALSE by default.
1651 g_socket_set_broadcast (GSocket
*socket
,
1654 GError
*error
= NULL
;
1656 g_return_if_fail (G_IS_SOCKET (socket
));
1658 broadcast
= !!broadcast
;
1660 if (!g_socket_set_option (socket
, SOL_SOCKET
, SO_BROADCAST
,
1663 g_warning ("error setting broadcast: %s", error
->message
);
1664 g_error_free (error
);
1668 g_object_notify (G_OBJECT (socket
), "broadcast");
1672 * g_socket_get_multicast_loopback:
1673 * @socket: a #GSocket.
1675 * Gets the multicast loopback setting on @socket; if %TRUE (the
1676 * default), outgoing multicast packets will be looped back to
1677 * multicast listeners on the same host.
1679 * Returns: the multicast loopback setting on @socket
1684 g_socket_get_multicast_loopback (GSocket
*socket
)
1686 GError
*error
= NULL
;
1689 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
1691 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1693 g_socket_get_option (socket
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
1696 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1698 g_socket_get_option (socket
, IPPROTO_IPV6
, IPV6_MULTICAST_LOOP
,
1702 g_return_val_if_reached (FALSE
);
1706 g_warning ("error getting multicast loopback: %s", error
->message
);
1707 g_error_free (error
);
1715 * g_socket_set_multicast_loopback:
1716 * @socket: a #GSocket.
1717 * @loopback: whether @socket should receive messages sent to its
1718 * multicast groups from the local host
1720 * Sets whether outgoing multicast packets will be received by sockets
1721 * listening on that multicast address on the same host. This is %TRUE
1727 g_socket_set_multicast_loopback (GSocket
*socket
,
1730 GError
*error
= NULL
;
1732 g_return_if_fail (G_IS_SOCKET (socket
));
1734 loopback
= !!loopback
;
1736 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1738 g_socket_set_option (socket
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
1741 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1743 g_socket_set_option (socket
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
1745 g_socket_set_option (socket
, IPPROTO_IPV6
, IPV6_MULTICAST_LOOP
,
1749 g_return_if_reached ();
1753 g_warning ("error setting multicast loopback: %s", error
->message
);
1754 g_error_free (error
);
1758 g_object_notify (G_OBJECT (socket
), "multicast-loopback");
1762 * g_socket_get_multicast_ttl:
1763 * @socket: a #GSocket.
1765 * Gets the multicast time-to-live setting on @socket; see
1766 * g_socket_set_multicast_ttl() for more details.
1768 * Returns: the multicast time-to-live setting on @socket
1773 g_socket_get_multicast_ttl (GSocket
*socket
)
1775 GError
*error
= NULL
;
1778 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
1780 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1782 g_socket_get_option (socket
, IPPROTO_IP
, IP_MULTICAST_TTL
,
1785 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1787 g_socket_get_option (socket
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
,
1791 g_return_val_if_reached (FALSE
);
1795 g_warning ("error getting multicast ttl: %s", error
->message
);
1796 g_error_free (error
);
1804 * g_socket_set_multicast_ttl:
1805 * @socket: a #GSocket.
1806 * @ttl: the time-to-live value for all multicast datagrams on @socket
1808 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1809 * By default, this is 1, meaning that multicast packets will not leave
1810 * the local network.
1815 g_socket_set_multicast_ttl (GSocket
*socket
,
1818 GError
*error
= NULL
;
1820 g_return_if_fail (G_IS_SOCKET (socket
));
1822 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1824 g_socket_set_option (socket
, IPPROTO_IP
, IP_MULTICAST_TTL
,
1827 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1829 g_socket_set_option (socket
, IPPROTO_IP
, IP_MULTICAST_TTL
,
1831 g_socket_set_option (socket
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
,
1835 g_return_if_reached ();
1839 g_warning ("error setting multicast ttl: %s", error
->message
);
1840 g_error_free (error
);
1844 g_object_notify (G_OBJECT (socket
), "multicast-ttl");
1848 * g_socket_get_family:
1849 * @socket: a #GSocket.
1851 * Gets the socket family of the socket.
1853 * Returns: a #GSocketFamily
1858 g_socket_get_family (GSocket
*socket
)
1860 g_return_val_if_fail (G_IS_SOCKET (socket
), G_SOCKET_FAMILY_INVALID
);
1862 return socket
->priv
->family
;
1866 * g_socket_get_socket_type:
1867 * @socket: a #GSocket.
1869 * Gets the socket type of the socket.
1871 * Returns: a #GSocketType
1876 g_socket_get_socket_type (GSocket
*socket
)
1878 g_return_val_if_fail (G_IS_SOCKET (socket
), G_SOCKET_TYPE_INVALID
);
1880 return socket
->priv
->type
;
1884 * g_socket_get_protocol:
1885 * @socket: a #GSocket.
1887 * Gets the socket protocol id the socket was created with.
1888 * In case the protocol is unknown, -1 is returned.
1890 * Returns: a protocol id, or -1 if unknown
1895 g_socket_get_protocol (GSocket
*socket
)
1897 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
1899 return socket
->priv
->protocol
;
1904 * @socket: a #GSocket.
1906 * Returns the underlying OS socket object. On unix this
1907 * is a socket file descriptor, and on Windows this is
1908 * a Winsock2 SOCKET handle. This may be useful for
1909 * doing platform specific or otherwise unusual operations
1912 * Returns: the file descriptor of the socket.
1917 g_socket_get_fd (GSocket
*socket
)
1919 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
1921 return socket
->priv
->fd
;
1925 * g_socket_get_local_address:
1926 * @socket: a #GSocket.
1927 * @error: #GError for error reporting, or %NULL to ignore.
1929 * Try to get the local address of a bound socket. This is only
1930 * useful if the socket has been bound to a local address,
1931 * either explicitly or implicitly when connecting.
1933 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1934 * Free the returned object with g_object_unref().
1939 g_socket_get_local_address (GSocket
*socket
,
1943 struct sockaddr_storage storage
;
1946 guint len
= sizeof (buffer
);
1948 g_return_val_if_fail (G_IS_SOCKET (socket
), NULL
);
1950 if (getsockname (socket
->priv
->fd
, &buffer
.sa
, &len
) < 0)
1952 int errsv
= get_socket_errno ();
1953 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
1954 _("could not get local address: %s"), socket_strerror (errsv
));
1958 return g_socket_address_new_from_native (&buffer
.storage
, len
);
1962 * g_socket_get_remote_address:
1963 * @socket: a #GSocket.
1964 * @error: #GError for error reporting, or %NULL to ignore.
1966 * Try to get the remote address of a connected socket. This is only
1967 * useful for connection oriented sockets that have been connected.
1969 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1970 * Free the returned object with g_object_unref().
1975 g_socket_get_remote_address (GSocket
*socket
,
1979 struct sockaddr_storage storage
;
1982 guint len
= sizeof (buffer
);
1984 g_return_val_if_fail (G_IS_SOCKET (socket
), NULL
);
1986 if (socket
->priv
->connect_pending
)
1988 if (!g_socket_check_connect_result (socket
, error
))
1991 socket
->priv
->connect_pending
= FALSE
;
1994 if (!socket
->priv
->remote_address
)
1996 if (getpeername (socket
->priv
->fd
, &buffer
.sa
, &len
) < 0)
1998 int errsv
= get_socket_errno ();
1999 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
2000 _("could not get remote address: %s"), socket_strerror (errsv
));
2004 socket
->priv
->remote_address
= g_socket_address_new_from_native (&buffer
.storage
, len
);
2007 return g_object_ref (socket
->priv
->remote_address
);
2011 * g_socket_is_connected:
2012 * @socket: a #GSocket.
2014 * Check whether the socket is connected. This is only useful for
2015 * connection-oriented sockets.
2017 * If using g_socket_shutdown(), this function will return %TRUE until the
2018 * socket has been shut down for reading and writing. If you do a non-blocking
2019 * connect, this function will not return %TRUE until after you call
2020 * g_socket_check_connect_result().
2022 * Returns: %TRUE if socket is connected, %FALSE otherwise.
2027 g_socket_is_connected (GSocket
*socket
)
2029 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2031 return (socket
->priv
->connected_read
|| socket
->priv
->connected_write
);
2036 * @socket: a #GSocket.
2037 * @error: #GError for error reporting, or %NULL to ignore.
2039 * Marks the socket as a server socket, i.e. a socket that is used
2040 * to accept incoming requests using g_socket_accept().
2042 * Before calling this the socket must be bound to a local address using
2045 * To set the maximum amount of outstanding clients, use
2046 * g_socket_set_listen_backlog().
2048 * Returns: %TRUE on success, %FALSE on error.
2053 g_socket_listen (GSocket
*socket
,
2056 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2058 if (!check_socket (socket
, error
))
2061 if (listen (socket
->priv
->fd
, socket
->priv
->listen_backlog
) < 0)
2063 int errsv
= get_socket_errno ();
2065 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
2066 _("could not listen: %s"), socket_strerror (errsv
));
2070 socket
->priv
->listening
= TRUE
;
2077 * @socket: a #GSocket.
2078 * @address: a #GSocketAddress specifying the local address.
2079 * @allow_reuse: whether to allow reusing this address
2080 * @error: #GError for error reporting, or %NULL to ignore.
2082 * When a socket is created it is attached to an address family, but it
2083 * doesn't have an address in this family. g_socket_bind() assigns the
2084 * address (sometimes called name) of the socket.
2086 * It is generally required to bind to a local address before you can
2087 * receive connections. (See g_socket_listen() and g_socket_accept() ).
2088 * In certain situations, you may also want to bind a socket that will be
2089 * used to initiate connections, though this is not normally required.
2091 * If @socket is a TCP socket, then @allow_reuse controls the setting
2092 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
2093 * server sockets (sockets that you will eventually call
2094 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
2095 * set this flag on a server socket may cause g_socket_bind() to return
2096 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
2097 * immediately restarted.)
2099 * If @socket is a UDP socket, then @allow_reuse determines whether or
2100 * not other UDP sockets can be bound to the same address at the same
2101 * time. In particular, you can have several UDP sockets bound to the
2102 * same address, and they will all receive all of the multicast and
2103 * broadcast packets sent to that address. (The behavior of unicast
2104 * UDP packets to an address with multiple listeners is not defined.)
2106 * Returns: %TRUE on success, %FALSE on error.
2111 g_socket_bind (GSocket
*socket
,
2112 GSocketAddress
*address
,
2113 gboolean reuse_address
,
2117 struct sockaddr_storage storage
;
2120 gboolean so_reuseaddr
;
2122 gboolean so_reuseport
;
2125 g_return_val_if_fail (G_IS_SOCKET (socket
) && G_IS_SOCKET_ADDRESS (address
), FALSE
);
2127 if (!check_socket (socket
, error
))
2130 if (!g_socket_address_to_native (address
, &addr
.storage
, sizeof addr
, error
))
2133 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
2134 * sockets, but has nasty side effects we don't want for TCP
2137 * On other platforms, we set SO_REUSEPORT, if it exists, for
2138 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
2139 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
2140 * the desired semantics on UDP (as it does on Linux, although
2141 * Linux has SO_REUSEPORT too as of 3.9).
2145 so_reuseaddr
= reuse_address
&& (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
);
2147 so_reuseaddr
= !!reuse_address
;
2151 so_reuseport
= reuse_address
&& (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
);
2154 /* Ignore errors here, the only likely error is "not supported", and
2155 * this is a "best effort" thing mainly.
2157 g_socket_set_option (socket
, SOL_SOCKET
, SO_REUSEADDR
, so_reuseaddr
, NULL
);
2159 g_socket_set_option (socket
, SOL_SOCKET
, SO_REUSEPORT
, so_reuseport
, NULL
);
2162 if (bind (socket
->priv
->fd
, &addr
.sa
,
2163 g_socket_address_get_native_size (address
)) < 0)
2165 int errsv
= get_socket_errno ();
2167 G_IO_ERROR
, socket_io_error_from_errno (errsv
),
2168 _("Error binding to address: %s"), socket_strerror (errsv
));
2176 g_socket_multicast_group_operation (GSocket
*socket
,
2177 GInetAddress
*group
,
2178 gboolean source_specific
,
2180 gboolean join_group
,
2183 const guint8
*native_addr
;
2184 gint optname
, result
;
2186 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2187 g_return_val_if_fail (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
, FALSE
);
2188 g_return_val_if_fail (G_IS_INET_ADDRESS (group
), FALSE
);
2190 if (!check_socket (socket
, error
))
2193 native_addr
= g_inet_address_to_bytes (group
);
2194 if (g_inet_address_get_family (group
) == G_SOCKET_FAMILY_IPV4
)
2196 #ifdef HAVE_IP_MREQN
2197 struct ip_mreqn mc_req
;
2199 struct ip_mreq mc_req
;
2202 memset (&mc_req
, 0, sizeof (mc_req
));
2203 memcpy (&mc_req
.imr_multiaddr
, native_addr
, sizeof (struct in_addr
));
2205 #ifdef HAVE_IP_MREQN
2207 mc_req
.imr_ifindex
= if_nametoindex (iface
);
2209 mc_req
.imr_ifindex
= 0; /* Pick any. */
2210 #elif defined(G_OS_WIN32)
2212 mc_req
.imr_interface
.s_addr
= g_htonl (if_nametoindex (iface
));
2214 mc_req
.imr_interface
.s_addr
= g_htonl (INADDR_ANY
);
2216 mc_req
.imr_interface
.s_addr
= g_htonl (INADDR_ANY
);
2219 if (source_specific
)
2221 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2222 optname
= join_group
? IP_ADD_SOURCE_MEMBERSHIP
: IP_DROP_SOURCE_MEMBERSHIP
;
2224 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
2226 _("Error joining multicast group: %s") :
2227 _("Error leaving multicast group: %s"),
2228 _("No support for source-specific multicast"));
2233 optname
= join_group
? IP_ADD_MEMBERSHIP
: IP_DROP_MEMBERSHIP
;
2234 result
= setsockopt (socket
->priv
->fd
, IPPROTO_IP
, optname
,
2235 &mc_req
, sizeof (mc_req
));
2237 else if (g_inet_address_get_family (group
) == G_SOCKET_FAMILY_IPV6
)
2239 struct ipv6_mreq mc_req_ipv6
;
2241 memset (&mc_req_ipv6
, 0, sizeof (mc_req_ipv6
));
2242 memcpy (&mc_req_ipv6
.ipv6mr_multiaddr
, native_addr
, sizeof (struct in6_addr
));
2243 #ifdef HAVE_IF_NAMETOINDEX
2245 mc_req_ipv6
.ipv6mr_interface
= if_nametoindex (iface
);
2248 mc_req_ipv6
.ipv6mr_interface
= 0;
2250 optname
= join_group
? IPV6_JOIN_GROUP
: IPV6_LEAVE_GROUP
;
2251 result
= setsockopt (socket
->priv
->fd
, IPPROTO_IPV6
, optname
,
2252 &mc_req_ipv6
, sizeof (mc_req_ipv6
));
2255 g_return_val_if_reached (FALSE
);
2259 int errsv
= get_socket_errno ();
2261 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
2263 _("Error joining multicast group: %s") :
2264 _("Error leaving multicast group: %s"),
2265 socket_strerror (errsv
));
2273 * g_socket_join_multicast_group:
2274 * @socket: a #GSocket.
2275 * @group: a #GInetAddress specifying the group address to join.
2276 * @iface: (nullable): Name of the interface to use, or %NULL
2277 * @source_specific: %TRUE if source-specific multicast should be used
2278 * @error: #GError for error reporting, or %NULL to ignore.
2280 * Registers @socket to receive multicast messages sent to @group.
2281 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2282 * been bound to an appropriate interface and port with
2285 * If @iface is %NULL, the system will automatically pick an interface
2286 * to bind to based on @group.
2288 * If @source_specific is %TRUE, source-specific multicast as defined
2289 * in RFC 4604 is used. Note that on older platforms this may fail
2290 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2292 * To bind to a given source-specific multicast address, use
2293 * g_socket_join_multicast_group_ssm() instead.
2295 * Returns: %TRUE on success, %FALSE on error.
2300 g_socket_join_multicast_group (GSocket
*socket
,
2301 GInetAddress
*group
,
2302 gboolean source_specific
,
2306 return g_socket_multicast_group_operation (socket
, group
, source_specific
, iface
, TRUE
, error
);
2310 * g_socket_leave_multicast_group:
2311 * @socket: a #GSocket.
2312 * @group: a #GInetAddress specifying the group address to leave.
2313 * @iface: (nullable): Interface used
2314 * @source_specific: %TRUE if source-specific multicast was used
2315 * @error: #GError for error reporting, or %NULL to ignore.
2317 * Removes @socket from the multicast group defined by @group, @iface,
2318 * and @source_specific (which must all have the same values they had
2319 * when you joined the group).
2321 * @socket remains bound to its address and port, and can still receive
2322 * unicast messages after calling this.
2324 * To unbind to a given source-specific multicast address, use
2325 * g_socket_leave_multicast_group_ssm() instead.
2327 * Returns: %TRUE on success, %FALSE on error.
2332 g_socket_leave_multicast_group (GSocket
*socket
,
2333 GInetAddress
*group
,
2334 gboolean source_specific
,
2338 return g_socket_multicast_group_operation (socket
, group
, source_specific
, iface
, FALSE
, error
);
2342 g_socket_multicast_group_operation_ssm (GSocket
*socket
,
2343 GInetAddress
*group
,
2344 GInetAddress
*source_specific
,
2346 gboolean join_group
,
2351 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2352 g_return_val_if_fail (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
, FALSE
);
2353 g_return_val_if_fail (G_IS_INET_ADDRESS (group
), FALSE
);
2354 g_return_val_if_fail (iface
== NULL
|| *iface
!= '\0', FALSE
);
2355 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, FALSE
);
2357 if (!source_specific
)
2359 return g_socket_multicast_group_operation (socket
, group
, FALSE
, iface
,
2363 if (!check_socket (socket
, error
))
2366 switch (g_inet_address_get_family (group
))
2368 case G_SOCKET_FAMILY_INVALID
:
2369 case G_SOCKET_FAMILY_UNIX
:
2371 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
2373 _("Error joining multicast group: %s") :
2374 _("Error leaving multicast group: %s"),
2375 _("Unsupported socket family"));
2380 case G_SOCKET_FAMILY_IPV4
:
2382 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2384 #ifdef BROKEN_IP_MREQ_SOURCE_STRUCT
2385 #define S_ADDR_FIELD(src) src.imr_interface
2387 #define S_ADDR_FIELD(src) src.imr_interface.s_addr
2391 struct ip_mreq_source mc_req_src
;
2393 if (g_inet_address_get_family (source_specific
) !=
2394 G_SOCKET_FAMILY_IPV4
)
2396 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
2398 _("Error joining multicast group: %s") :
2399 _("Error leaving multicast group: %s"),
2400 _("source-specific not an IPv4 address"));
2404 memset (&mc_req_src
, 0, sizeof (mc_req_src
));
2406 /* By default use the default IPv4 multicast interface. */
2407 S_ADDR_FIELD(mc_req_src
) = g_htonl (INADDR_ANY
);
2411 #if defined(G_OS_WIN32) && defined (HAVE_IF_NAMETOINDEX)
2412 guint iface_index
= if_nametoindex (iface
);
2413 if (iface_index
== 0)
2417 g_set_error (error
, G_IO_ERROR
, g_io_error_from_errno (errsv
),
2418 _("Interface not found: %s"), g_strerror (errsv
));
2421 /* (0.0.0.iface_index) only works on Windows. */
2422 S_ADDR_FIELD(mc_req_src
) = g_htonl (iface_index
);
2423 #elif defined (HAVE_SIOCGIFADDR)
2426 struct sockaddr_in
*iface_addr
;
2427 size_t if_name_len
= strlen (iface
);
2429 memset (&ifr
, 0, sizeof (ifr
));
2431 if (if_name_len
>= sizeof (ifr
.ifr_name
))
2433 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_FILENAME_TOO_LONG
,
2434 _("Interface name too long"));
2438 memcpy (ifr
.ifr_name
, iface
, if_name_len
);
2440 /* Get the IPv4 address of the given network interface name. */
2441 ret
= ioctl (socket
->priv
->fd
, SIOCGIFADDR
, &ifr
);
2446 g_set_error (error
, G_IO_ERROR
, g_io_error_from_errno (errsv
),
2447 _("Interface not found: %s"), g_strerror (errsv
));
2451 iface_addr
= (struct sockaddr_in
*) &ifr
.ifr_addr
;
2452 S_ADDR_FIELD(mc_req_src
) = iface_addr
->sin_addr
.s_addr
;
2453 #endif /* defined(G_OS_WIN32) && defined (HAVE_IF_NAMETOINDEX) */
2455 memcpy (&mc_req_src
.imr_multiaddr
, g_inet_address_to_bytes (group
),
2456 g_inet_address_get_native_size (group
));
2457 memcpy (&mc_req_src
.imr_sourceaddr
,
2458 g_inet_address_to_bytes (source_specific
),
2459 g_inet_address_get_native_size (source_specific
));
2462 join_group
? IP_ADD_SOURCE_MEMBERSHIP
: IP_DROP_SOURCE_MEMBERSHIP
;
2463 result
= setsockopt (socket
->priv
->fd
, IPPROTO_IP
, optname
,
2464 &mc_req_src
, sizeof (mc_req_src
));
2469 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
2471 _("Error joining multicast group: %s") :
2472 _("Error leaving multicast group: %s"),
2473 _("No support for IPv4 source-specific multicast"));
2475 #endif /* IP_ADD_SOURCE_MEMBERSHIP */
2479 case G_SOCKET_FAMILY_IPV6
:
2481 #ifdef MCAST_JOIN_SOURCE_GROUP
2484 struct group_source_req mc_req_src
;
2485 GSocketAddress
*saddr_group
, *saddr_source_specific
;
2486 guint iface_index
= 0;
2488 #if defined (HAVE_IF_NAMETOINDEX)
2491 iface_index
= if_nametoindex (iface
);
2492 if (iface_index
== 0)
2496 g_set_error (error
, G_IO_ERROR
, g_io_error_from_errno (errsv
),
2497 _("Interface not found: %s"), g_strerror (errsv
));
2501 #endif /* defined (HAVE_IF_NAMETOINDEX) */
2502 mc_req_src
.gsr_interface
= iface_index
;
2504 saddr_group
= g_inet_socket_address_new (group
, 0);
2505 res
= g_socket_address_to_native (saddr_group
, &mc_req_src
.gsr_group
,
2506 sizeof (mc_req_src
.gsr_group
),
2508 g_object_unref (saddr_group
);
2512 saddr_source_specific
= g_inet_socket_address_new (source_specific
, 0);
2513 res
= g_socket_address_to_native (saddr_source_specific
,
2514 &mc_req_src
.gsr_source
,
2515 sizeof (mc_req_src
.gsr_source
),
2517 g_object_unref (saddr_source_specific
);
2523 join_group
? MCAST_JOIN_SOURCE_GROUP
: MCAST_LEAVE_SOURCE_GROUP
;
2524 result
= setsockopt (socket
->priv
->fd
, IPPROTO_IPV6
, optname
,
2525 &mc_req_src
, sizeof (mc_req_src
));
2527 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
2529 _("Error joining multicast group: %s") :
2530 _("Error leaving multicast group: %s"),
2531 _("No support for IPv6 source-specific multicast"));
2533 #endif /* MCAST_JOIN_SOURCE_GROUP */
2538 g_return_val_if_reached (FALSE
);
2543 int errsv
= get_socket_errno ();
2545 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
2547 _("Error joining multicast group: %s") :
2548 _("Error leaving multicast group: %s"),
2549 socket_strerror (errsv
));
2557 * g_socket_join_multicast_group_ssm:
2558 * @socket: a #GSocket.
2559 * @group: a #GInetAddress specifying the group address to join.
2560 * @source_specific: (nullable): a #GInetAddress specifying the
2561 * source-specific multicast address or %NULL to ignore.
2562 * @iface: (nullable): Name of the interface to use, or %NULL
2563 * @error: #GError for error reporting, or %NULL to ignore.
2565 * Registers @socket to receive multicast messages sent to @group.
2566 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2567 * been bound to an appropriate interface and port with
2570 * If @iface is %NULL, the system will automatically pick an interface
2571 * to bind to based on @group.
2573 * If @source_specific is not %NULL, use source-specific multicast as
2574 * defined in RFC 4604. Note that on older platforms this may fail
2575 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2577 * Note that this function can be called multiple times for the same
2578 * @group with different @source_specific in order to receive multicast
2579 * packets from more than one source.
2581 * Returns: %TRUE on success, %FALSE on error.
2586 g_socket_join_multicast_group_ssm (GSocket
*socket
,
2587 GInetAddress
*group
,
2588 GInetAddress
*source_specific
,
2592 return g_socket_multicast_group_operation_ssm (socket
, group
,
2593 source_specific
, iface
, TRUE
, error
);
2597 * g_socket_leave_multicast_group_ssm:
2598 * @socket: a #GSocket.
2599 * @group: a #GInetAddress specifying the group address to leave.
2600 * @source_specific: (nullable): a #GInetAddress specifying the
2601 * source-specific multicast address or %NULL to ignore.
2602 * @iface: (nullable): Name of the interface to use, or %NULL
2603 * @error: #GError for error reporting, or %NULL to ignore.
2605 * Removes @socket from the multicast group defined by @group, @iface,
2606 * and @source_specific (which must all have the same values they had
2607 * when you joined the group).
2609 * @socket remains bound to its address and port, and can still receive
2610 * unicast messages after calling this.
2612 * Returns: %TRUE on success, %FALSE on error.
2617 g_socket_leave_multicast_group_ssm (GSocket
*socket
,
2618 GInetAddress
*group
,
2619 GInetAddress
*source_specific
,
2623 return g_socket_multicast_group_operation_ssm (socket
, group
,
2624 source_specific
, iface
, FALSE
, error
);
2628 * g_socket_speaks_ipv4:
2629 * @socket: a #GSocket
2631 * Checks if a socket is capable of speaking IPv4.
2633 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2634 * and under some combinations of circumstances IPv6 sockets are also
2635 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2638 * No other types of sockets are currently considered as being capable
2641 * Returns: %TRUE if this socket can be used with IPv4.
2646 g_socket_speaks_ipv4 (GSocket
*socket
)
2648 switch (socket
->priv
->family
)
2650 case G_SOCKET_FAMILY_IPV4
:
2653 case G_SOCKET_FAMILY_IPV6
:
2654 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2658 if (!g_socket_get_option (socket
,
2659 IPPROTO_IPV6
, IPV6_V6ONLY
,
2676 * @socket: a #GSocket.
2677 * @cancellable: (nullable): a %GCancellable or %NULL
2678 * @error: #GError for error reporting, or %NULL to ignore.
2680 * Accept incoming connections on a connection-based socket. This removes
2681 * the first outstanding connection request from the listening socket and
2682 * creates a #GSocket object for it.
2684 * The @socket must be bound to a local address with g_socket_bind() and
2685 * must be listening for incoming connections (g_socket_listen()).
2687 * If there are no outstanding connections then the operation will block
2688 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2689 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2691 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2692 * Free the returned object with g_object_unref().
2697 g_socket_accept (GSocket
*socket
,
2698 GCancellable
*cancellable
,
2701 GSocket
*new_socket
;
2704 g_return_val_if_fail (G_IS_SOCKET (socket
), NULL
);
2706 if (!check_socket (socket
, error
))
2709 if (!check_timeout (socket
, error
))
2714 win32_unset_event_mask (socket
, FD_ACCEPT
);
2716 if ((ret
= accept (socket
->priv
->fd
, NULL
, 0)) < 0)
2718 int errsv
= get_socket_errno ();
2723 #ifdef WSAEWOULDBLOCK
2724 if (errsv
== WSAEWOULDBLOCK
)
2726 if (errsv
== EWOULDBLOCK
||
2730 if (socket
->priv
->blocking
)
2732 if (!g_socket_condition_wait (socket
,
2733 G_IO_IN
, cancellable
, error
))
2740 socket_set_error_lazy (error
, errsv
, _("Error accepting connection: %s"));
2748 /* The socket inherits the accepting sockets event mask and even object,
2749 we need to remove that */
2750 WSAEventSelect (ret
, NULL
, 0);
2756 /* We always want to set close-on-exec to protect users. If you
2757 need to so some weird inheritance to exec you can re-enable this
2758 using lower level hacks with g_socket_get_fd(). */
2759 flags
= fcntl (ret
, F_GETFD
, 0);
2761 (flags
& FD_CLOEXEC
) == 0)
2763 flags
|= FD_CLOEXEC
;
2764 fcntl (ret
, F_SETFD
, flags
);
2769 new_socket
= g_socket_new_from_fd (ret
, error
);
2770 if (new_socket
== NULL
)
2779 new_socket
->priv
->protocol
= socket
->priv
->protocol
;
2786 * @socket: a #GSocket.
2787 * @address: a #GSocketAddress specifying the remote address.
2788 * @cancellable: (nullable): a %GCancellable or %NULL
2789 * @error: #GError for error reporting, or %NULL to ignore.
2791 * Connect the socket to the specified remote address.
2793 * For connection oriented socket this generally means we attempt to make
2794 * a connection to the @address. For a connection-less socket it sets
2795 * the default address for g_socket_send() and discards all incoming datagrams
2796 * from other sources.
2798 * Generally connection oriented sockets can only connect once, but
2799 * connection-less sockets can connect multiple times to change the
2802 * If the connect call needs to do network I/O it will block, unless
2803 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2804 * and the user can be notified of the connection finishing by waiting
2805 * for the G_IO_OUT condition. The result of the connection must then be
2806 * checked with g_socket_check_connect_result().
2808 * Returns: %TRUE if connected, %FALSE on error.
2813 g_socket_connect (GSocket
*socket
,
2814 GSocketAddress
*address
,
2815 GCancellable
*cancellable
,
2819 struct sockaddr_storage storage
;
2823 g_return_val_if_fail (G_IS_SOCKET (socket
) && G_IS_SOCKET_ADDRESS (address
), FALSE
);
2825 if (!check_socket (socket
, error
))
2828 if (!g_socket_address_to_native (address
, &buffer
.storage
, sizeof buffer
, error
))
2831 if (socket
->priv
->remote_address
)
2832 g_object_unref (socket
->priv
->remote_address
);
2833 socket
->priv
->remote_address
= g_object_ref (address
);
2837 win32_unset_event_mask (socket
, FD_CONNECT
);
2839 if (connect (socket
->priv
->fd
, &buffer
.sa
,
2840 g_socket_address_get_native_size (address
)) < 0)
2842 int errsv
= get_socket_errno ();
2848 if (errsv
== EINPROGRESS
)
2850 if (errsv
== WSAEWOULDBLOCK
)
2853 if (socket
->priv
->blocking
)
2855 if (g_socket_condition_wait (socket
, G_IO_OUT
, cancellable
, error
))
2857 if (g_socket_check_connect_result (socket
, error
))
2863 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_PENDING
,
2864 _("Connection in progress"));
2865 socket
->priv
->connect_pending
= TRUE
;
2869 g_set_error_literal (error
, G_IO_ERROR
,
2870 socket_io_error_from_errno (errsv
),
2871 socket_strerror (errsv
));
2878 socket
->priv
->connected_read
= TRUE
;
2879 socket
->priv
->connected_write
= TRUE
;
2885 * g_socket_check_connect_result:
2886 * @socket: a #GSocket
2887 * @error: #GError for error reporting, or %NULL to ignore.
2889 * Checks and resets the pending connect error for the socket.
2890 * This is used to check for errors when g_socket_connect() is
2891 * used in non-blocking mode.
2893 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2898 g_socket_check_connect_result (GSocket
*socket
,
2903 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2905 if (!check_socket (socket
, error
))
2908 if (!check_timeout (socket
, error
))
2911 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_ERROR
, &value
, error
))
2913 g_prefix_error (error
, _("Unable to get pending error: "));
2919 g_set_error_literal (error
, G_IO_ERROR
, socket_io_error_from_errno (value
),
2920 socket_strerror (value
));
2921 if (socket
->priv
->remote_address
)
2923 g_object_unref (socket
->priv
->remote_address
);
2924 socket
->priv
->remote_address
= NULL
;
2929 socket
->priv
->connected_read
= TRUE
;
2930 socket
->priv
->connected_write
= TRUE
;
2936 * g_socket_get_available_bytes:
2937 * @socket: a #GSocket
2939 * Get the amount of data pending in the OS input buffer, without blocking.
2941 * If @socket is a UDP or SCTP socket, this will return the size of
2942 * just the next packet, even if additional packets are buffered after
2945 * Note that on Windows, this function is rather inefficient in the
2946 * UDP case, and so if you know any plausible upper bound on the size
2947 * of the incoming packet, it is better to just do a
2948 * g_socket_receive() with a buffer of that size, rather than calling
2949 * g_socket_get_available_bytes() first and then doing a receive of
2950 * exactly the right size.
2952 * Returns: the number of bytes that can be read from the socket
2953 * without blocking or truncating, or -1 on error.
2958 g_socket_get_available_bytes (GSocket
*socket
)
2961 const gint bufsize
= 64 * 1024;
2962 static guchar
*buf
= NULL
;
2970 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
2973 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_NREAD
, &avail
, NULL
))
2976 if (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
)
2978 if (G_UNLIKELY (g_once_init_enter (&buf
)))
2979 g_once_init_leave (&buf
, g_malloc (bufsize
));
2981 /* On datagram sockets, FIONREAD ioctl is not reliable because many
2982 * systems add internal header size to the reported size, making it
2983 * unusable for this function. */
2984 avail
= recv (socket
->priv
->fd
, buf
, bufsize
, MSG_PEEK
);
2987 int errsv
= get_socket_errno ();
2989 if (errsv
== WSAEWOULDBLOCK
)
2991 if (errsv
== EWOULDBLOCK
|| errsv
== EAGAIN
)
2999 if (ioctlsocket (socket
->priv
->fd
, FIONREAD
, &avail
) < 0)
3001 if (ioctl (socket
->priv
->fd
, FIONREAD
, &avail
) < 0)
3010 /* Block on a timed wait for @condition until (@start_time + @timeout).
3011 * Return %G_IO_ERROR_TIMED_OUT if the timeout is reached; otherwise %TRUE.
3014 block_on_timeout (GSocket
*socket
,
3015 GIOCondition condition
,
3018 GCancellable
*cancellable
,
3021 gint64 wait_timeout
= -1;
3023 g_return_val_if_fail (timeout
!= 0, TRUE
);
3025 /* check if we've timed out or how much time to wait at most */
3028 gint64 elapsed
= g_get_monotonic_time () - start_time
;
3030 if (elapsed
>= timeout
)
3032 g_set_error_literal (error
,
3033 G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
,
3034 _("Socket I/O timed out"));
3038 wait_timeout
= timeout
- elapsed
;
3041 return g_socket_condition_timed_wait (socket
, condition
, wait_timeout
,
3042 cancellable
, error
);
3046 g_socket_receive_with_timeout (GSocket
*socket
,
3050 GCancellable
*cancellable
,
3056 g_return_val_if_fail (G_IS_SOCKET (socket
) && buffer
!= NULL
, -1);
3058 start_time
= g_get_monotonic_time ();
3060 if (!check_socket (socket
, error
))
3063 if (!check_timeout (socket
, error
))
3066 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
3071 win32_unset_event_mask (socket
, FD_READ
);
3073 if ((ret
= recv (socket
->priv
->fd
, buffer
, size
, 0)) < 0)
3075 int errsv
= get_socket_errno ();
3080 #ifdef WSAEWOULDBLOCK
3081 if (errsv
== WSAEWOULDBLOCK
)
3083 if (errsv
== EWOULDBLOCK
||
3089 if (!block_on_timeout (socket
, G_IO_IN
, timeout
, start_time
,
3090 cancellable
, error
))
3097 socket_set_error_lazy (error
, errsv
, _("Error receiving data: %s"));
3109 * @socket: a #GSocket
3110 * @buffer: (array length=size) (element-type guint8): a buffer to
3111 * read data into (which should be at least @size bytes long).
3112 * @size: the number of bytes you want to read from the socket
3113 * @cancellable: (nullable): a %GCancellable or %NULL
3114 * @error: #GError for error reporting, or %NULL to ignore.
3116 * Receive data (up to @size bytes) from a socket. This is mainly used by
3117 * connection-oriented sockets; it is identical to g_socket_receive_from()
3118 * with @address set to %NULL.
3120 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
3121 * g_socket_receive() will always read either 0 or 1 complete messages from
3122 * the socket. If the received message is too large to fit in @buffer, then
3123 * the data beyond @size bytes will be discarded, without any explicit
3124 * indication that this has occurred.
3126 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
3127 * number of bytes, up to @size. If more than @size bytes have been
3128 * received, the additional data will be returned in future calls to
3129 * g_socket_receive().
3131 * If the socket is in blocking mode the call will block until there
3132 * is some data to receive, the connection is closed, or there is an
3133 * error. If there is no data available and the socket is in
3134 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3135 * returned. To be notified when data is available, wait for the
3136 * %G_IO_IN condition.
3138 * On error -1 is returned and @error is set accordingly.
3140 * Returns: Number of bytes read, or 0 if the connection was closed by
3141 * the peer, or -1 on error
3146 g_socket_receive (GSocket
*socket
,
3149 GCancellable
*cancellable
,
3152 return g_socket_receive_with_timeout (socket
, (guint8
*) buffer
, size
,
3153 socket
->priv
->blocking
? -1 : 0,
3154 cancellable
, error
);
3158 * g_socket_receive_with_blocking:
3159 * @socket: a #GSocket
3160 * @buffer: (array length=size) (element-type guint8): a buffer to
3161 * read data into (which should be at least @size bytes long).
3162 * @size: the number of bytes you want to read from the socket
3163 * @blocking: whether to do blocking or non-blocking I/O
3164 * @cancellable: (nullable): a %GCancellable or %NULL
3165 * @error: #GError for error reporting, or %NULL to ignore.
3167 * This behaves exactly the same as g_socket_receive(), except that
3168 * the choice of blocking or non-blocking behavior is determined by
3169 * the @blocking argument rather than by @socket's properties.
3171 * Returns: Number of bytes read, or 0 if the connection was closed by
3172 * the peer, or -1 on error
3177 g_socket_receive_with_blocking (GSocket
*socket
,
3181 GCancellable
*cancellable
,
3184 return g_socket_receive_with_timeout (socket
, (guint8
*) buffer
, size
,
3185 blocking
? -1 : 0, cancellable
, error
);
3189 * g_socket_receive_from:
3190 * @socket: a #GSocket
3191 * @address: (out) (optional): a pointer to a #GSocketAddress
3193 * @buffer: (array length=size) (element-type guint8): a buffer to
3194 * read data into (which should be at least @size bytes long).
3195 * @size: the number of bytes you want to read from the socket
3196 * @cancellable: (nullable): a %GCancellable or %NULL
3197 * @error: #GError for error reporting, or %NULL to ignore.
3199 * Receive data (up to @size bytes) from a socket.
3201 * If @address is non-%NULL then @address will be set equal to the
3202 * source address of the received packet.
3203 * @address is owned by the caller.
3205 * See g_socket_receive() for additional information.
3207 * Returns: Number of bytes read, or 0 if the connection was closed by
3208 * the peer, or -1 on error
3213 g_socket_receive_from (GSocket
*socket
,
3214 GSocketAddress
**address
,
3217 GCancellable
*cancellable
,
3225 return g_socket_receive_message (socket
,
3233 /* See the comment about SIGPIPE above. */
3235 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
3237 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
3241 g_socket_send_with_timeout (GSocket
*socket
,
3242 const guint8
*buffer
,
3245 GCancellable
*cancellable
,
3251 g_return_val_if_fail (G_IS_SOCKET (socket
) && buffer
!= NULL
, -1);
3253 start_time
= g_get_monotonic_time ();
3255 if (!check_socket (socket
, error
))
3258 if (!check_timeout (socket
, error
))
3261 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
3266 win32_unset_event_mask (socket
, FD_WRITE
);
3268 if ((ret
= send (socket
->priv
->fd
, (const char *)buffer
, size
, G_SOCKET_DEFAULT_SEND_FLAGS
)) < 0)
3270 int errsv
= get_socket_errno ();
3275 #ifdef WSAEWOULDBLOCK
3276 if (errsv
== WSAEWOULDBLOCK
)
3278 if (errsv
== EWOULDBLOCK
||
3284 if (!block_on_timeout (socket
, G_IO_OUT
, timeout
, start_time
,
3285 cancellable
, error
))
3292 socket_set_error_lazy (error
, errsv
, _("Error sending data: %s"));
3303 * @socket: a #GSocket
3304 * @buffer: (array length=size) (element-type guint8): the buffer
3305 * containing the data to send.
3306 * @size: the number of bytes to send
3307 * @cancellable: (nullable): a %GCancellable or %NULL
3308 * @error: #GError for error reporting, or %NULL to ignore.
3310 * Tries to send @size bytes from @buffer on the socket. This is
3311 * mainly used by connection-oriented sockets; it is identical to
3312 * g_socket_send_to() with @address set to %NULL.
3314 * If the socket is in blocking mode the call will block until there is
3315 * space for the data in the socket queue. If there is no space available
3316 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3317 * will be returned. To be notified when space is available, wait for the
3318 * %G_IO_OUT condition. Note though that you may still receive
3319 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3320 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3321 * very common due to the way the underlying APIs work.)
3323 * On error -1 is returned and @error is set accordingly.
3325 * Returns: Number of bytes written (which may be less than @size), or -1
3331 g_socket_send (GSocket
*socket
,
3332 const gchar
*buffer
,
3334 GCancellable
*cancellable
,
3337 return g_socket_send_with_blocking (socket
, buffer
, size
,
3338 socket
->priv
->blocking
,
3339 cancellable
, error
);
3343 * g_socket_send_with_blocking:
3344 * @socket: a #GSocket
3345 * @buffer: (array length=size) (element-type guint8): the buffer
3346 * containing the data to send.
3347 * @size: the number of bytes to send
3348 * @blocking: whether to do blocking or non-blocking I/O
3349 * @cancellable: (nullable): a %GCancellable or %NULL
3350 * @error: #GError for error reporting, or %NULL to ignore.
3352 * This behaves exactly the same as g_socket_send(), except that
3353 * the choice of blocking or non-blocking behavior is determined by
3354 * the @blocking argument rather than by @socket's properties.
3356 * Returns: Number of bytes written (which may be less than @size), or -1
3362 g_socket_send_with_blocking (GSocket
*socket
,
3363 const gchar
*buffer
,
3366 GCancellable
*cancellable
,
3369 return g_socket_send_with_timeout (socket
, (const guint8
*) buffer
, size
,
3370 blocking
? -1 : 0, cancellable
, error
);
3375 * @socket: a #GSocket
3376 * @address: (nullable): a #GSocketAddress, or %NULL
3377 * @buffer: (array length=size) (element-type guint8): the buffer
3378 * containing the data to send.
3379 * @size: the number of bytes to send
3380 * @cancellable: (nullable): a %GCancellable or %NULL
3381 * @error: #GError for error reporting, or %NULL to ignore.
3383 * Tries to send @size bytes from @buffer to @address. If @address is
3384 * %NULL then the message is sent to the default receiver (set by
3385 * g_socket_connect()).
3387 * See g_socket_send() for additional information.
3389 * Returns: Number of bytes written (which may be less than @size), or -1
3395 g_socket_send_to (GSocket
*socket
,
3396 GSocketAddress
*address
,
3397 const gchar
*buffer
,
3399 GCancellable
*cancellable
,
3407 return g_socket_send_message (socket
,
3417 * g_socket_shutdown:
3418 * @socket: a #GSocket
3419 * @shutdown_read: whether to shut down the read side
3420 * @shutdown_write: whether to shut down the write side
3421 * @error: #GError for error reporting, or %NULL to ignore.
3423 * Shut down part or all of a full-duplex connection.
3425 * If @shutdown_read is %TRUE then the receiving side of the connection
3426 * is shut down, and further reading is disallowed.
3428 * If @shutdown_write is %TRUE then the sending side of the connection
3429 * is shut down, and further writing is disallowed.
3431 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
3433 * One example where it is useful to shut down only one side of a connection is
3434 * graceful disconnect for TCP connections where you close the sending side,
3435 * then wait for the other side to close the connection, thus ensuring that the
3436 * other side saw all sent data.
3438 * Returns: %TRUE on success, %FALSE on error
3443 g_socket_shutdown (GSocket
*socket
,
3444 gboolean shutdown_read
,
3445 gboolean shutdown_write
,
3450 g_return_val_if_fail (G_IS_SOCKET (socket
), TRUE
);
3452 if (!check_socket (socket
, error
))
3456 if (!shutdown_read
&& !shutdown_write
)
3460 if (shutdown_read
&& shutdown_write
)
3462 else if (shutdown_read
)
3467 if (shutdown_read
&& shutdown_write
)
3469 else if (shutdown_read
)
3475 if (shutdown (socket
->priv
->fd
, how
) != 0)
3477 int errsv
= get_socket_errno ();
3478 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
3479 _("Unable to shutdown socket: %s"), socket_strerror (errsv
));
3484 socket
->priv
->connected_read
= FALSE
;
3486 socket
->priv
->connected_write
= FALSE
;
3493 * @socket: a #GSocket
3494 * @error: #GError for error reporting, or %NULL to ignore.
3496 * Closes the socket, shutting down any active connection.
3498 * Closing a socket does not wait for all outstanding I/O operations
3499 * to finish, so the caller should not rely on them to be guaranteed
3500 * to complete even if the close returns with no error.
3502 * Once the socket is closed, all other operations will return
3503 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
3506 * Sockets will be automatically closed when the last reference
3507 * is dropped, but you might want to call this function to make sure
3508 * resources are released as early as possible.
3510 * Beware that due to the way that TCP works, it is possible for
3511 * recently-sent data to be lost if either you close a socket while the
3512 * %G_IO_IN condition is set, or else if the remote connection tries to
3513 * send something to you after you close the socket but before it has
3514 * finished reading all of the data you sent. There is no easy generic
3515 * way to avoid this problem; the easiest fix is to design the network
3516 * protocol such that the client will never send data "out of turn".
3517 * Another solution is for the server to half-close the connection by
3518 * calling g_socket_shutdown() with only the @shutdown_write flag set,
3519 * and then wait for the client to notice this and close its side of the
3520 * connection, after which the server can safely call g_socket_close().
3521 * (This is what #GTcpConnection does if you call
3522 * g_tcp_connection_set_graceful_disconnect(). But of course, this
3523 * only works if the client will close its connection after the server
3526 * Returns: %TRUE on success, %FALSE on error
3531 g_socket_close (GSocket
*socket
,
3536 g_return_val_if_fail (G_IS_SOCKET (socket
), TRUE
);
3538 if (socket
->priv
->closed
)
3539 return TRUE
; /* Multiple close not an error */
3541 if (!check_socket (socket
, error
))
3547 res
= closesocket (socket
->priv
->fd
);
3549 res
= close (socket
->priv
->fd
);
3553 int errsv
= get_socket_errno ();
3558 g_set_error (error
, G_IO_ERROR
,
3559 socket_io_error_from_errno (errsv
),
3560 _("Error closing socket: %s"),
3561 socket_strerror (errsv
));
3567 socket
->priv
->fd
= -1;
3568 socket
->priv
->connected_read
= FALSE
;
3569 socket
->priv
->connected_write
= FALSE
;
3570 socket
->priv
->closed
= TRUE
;
3571 if (socket
->priv
->remote_address
)
3573 g_object_unref (socket
->priv
->remote_address
);
3574 socket
->priv
->remote_address
= NULL
;
3581 * g_socket_is_closed:
3582 * @socket: a #GSocket
3584 * Checks whether a socket is closed.
3586 * Returns: %TRUE if socket is closed, %FALSE otherwise
3591 g_socket_is_closed (GSocket
*socket
)
3593 return socket
->priv
->closed
;
3597 /* Broken source, used on errors */
3599 broken_dispatch (GSource
*source
,
3600 GSourceFunc callback
,
3606 static GSourceFuncs broken_funcs
=
3615 network_events_for_condition (GIOCondition condition
)
3619 if (condition
& G_IO_IN
)
3620 event_mask
|= (FD_READ
| FD_ACCEPT
);
3621 if (condition
& G_IO_OUT
)
3622 event_mask
|= (FD_WRITE
| FD_CONNECT
);
3623 event_mask
|= FD_CLOSE
;
3629 ensure_event (GSocket
*socket
)
3631 if (socket
->priv
->event
== WSA_INVALID_EVENT
)
3632 socket
->priv
->event
= WSACreateEvent();
3636 update_select_events (GSocket
*socket
)
3643 ensure_event (socket
);
3646 for (l
= socket
->priv
->requested_conditions
; l
!= NULL
; l
= l
->next
)
3649 event_mask
|= network_events_for_condition (*ptr
);
3652 if (event_mask
!= socket
->priv
->selected_events
)
3654 /* If no events selected, disable event so we can unset
3657 if (event_mask
== 0)
3660 event
= socket
->priv
->event
;
3662 if (WSAEventSelect (socket
->priv
->fd
, event
, event_mask
) == 0)
3663 socket
->priv
->selected_events
= event_mask
;
3668 add_condition_watch (GSocket
*socket
,
3669 GIOCondition
*condition
)
3671 g_mutex_lock (&socket
->priv
->win32_source_lock
);
3672 g_assert (g_list_find (socket
->priv
->requested_conditions
, condition
) == NULL
);
3674 socket
->priv
->requested_conditions
=
3675 g_list_prepend (socket
->priv
->requested_conditions
, condition
);
3677 update_select_events (socket
);
3678 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
3682 remove_condition_watch (GSocket
*socket
,
3683 GIOCondition
*condition
)
3685 g_mutex_lock (&socket
->priv
->win32_source_lock
);
3686 g_assert (g_list_find (socket
->priv
->requested_conditions
, condition
) != NULL
);
3688 socket
->priv
->requested_conditions
=
3689 g_list_remove (socket
->priv
->requested_conditions
, condition
);
3691 update_select_events (socket
);
3692 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
3696 update_condition_unlocked (GSocket
*socket
)
3698 WSANETWORKEVENTS events
;
3699 GIOCondition condition
;
3701 if (WSAEnumNetworkEvents (socket
->priv
->fd
,
3702 socket
->priv
->event
,
3705 socket
->priv
->current_events
|= events
.lNetworkEvents
;
3706 if (events
.lNetworkEvents
& FD_WRITE
&&
3707 events
.iErrorCode
[FD_WRITE_BIT
] != 0)
3708 socket
->priv
->current_errors
|= FD_WRITE
;
3709 if (events
.lNetworkEvents
& FD_CONNECT
&&
3710 events
.iErrorCode
[FD_CONNECT_BIT
] != 0)
3711 socket
->priv
->current_errors
|= FD_CONNECT
;
3715 if (socket
->priv
->current_events
& (FD_READ
| FD_ACCEPT
))
3716 condition
|= G_IO_IN
;
3718 if (socket
->priv
->current_events
& FD_CLOSE
)
3720 int r
, errsv
, buffer
;
3722 r
= recv (socket
->priv
->fd
, &buffer
, sizeof (buffer
), MSG_PEEK
);
3724 errsv
= get_socket_errno ();
3727 (r
< 0 && errsv
== WSAENOTCONN
))
3728 condition
|= G_IO_IN
;
3730 (r
< 0 && (errsv
== WSAESHUTDOWN
|| errsv
== WSAECONNRESET
||
3731 errsv
== WSAECONNABORTED
|| errsv
== WSAENETRESET
)))
3732 condition
|= G_IO_HUP
;
3734 condition
|= G_IO_ERR
;
3737 if (socket
->priv
->closed
)
3738 condition
|= G_IO_HUP
;
3740 /* Never report both G_IO_OUT and HUP, these are
3741 mutually exclusive (can't write to a closed socket) */
3742 if ((condition
& G_IO_HUP
) == 0 &&
3743 socket
->priv
->current_events
& FD_WRITE
)
3745 if (socket
->priv
->current_errors
& FD_WRITE
)
3746 condition
|= G_IO_ERR
;
3748 condition
|= G_IO_OUT
;
3752 if (socket
->priv
->current_events
& FD_CONNECT
)
3754 if (socket
->priv
->current_errors
& FD_CONNECT
)
3755 condition
|= (G_IO_HUP
| G_IO_ERR
);
3757 condition
|= G_IO_OUT
;
3765 update_condition (GSocket
*socket
)
3768 g_mutex_lock (&socket
->priv
->win32_source_lock
);
3769 res
= update_condition_unlocked (socket
);
3770 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
3783 GIOCondition condition
;
3787 socket_source_prepare (GSource
*source
,
3790 GSocketSource
*socket_source
= (GSocketSource
*)source
;
3795 if ((socket_source
->pollfd
.revents
& G_IO_NVAL
) != 0)
3798 if (g_socket_is_closed (socket_source
->socket
))
3800 g_source_remove_poll (source
, &socket_source
->pollfd
);
3801 socket_source
->pollfd
.revents
= G_IO_NVAL
;
3805 return (update_condition (socket_source
->socket
) & socket_source
->condition
) != 0;
3807 return g_socket_is_closed (socket_source
->socket
) && socket_source
->fd_tag
!= NULL
;
3813 socket_source_check_win32 (GSource
*source
)
3817 return socket_source_prepare (source
, &timeout
);
3822 socket_source_dispatch (GSource
*source
,
3823 GSourceFunc callback
,
3826 GSocketSourceFunc func
= (GSocketSourceFunc
)callback
;
3827 GSocketSource
*socket_source
= (GSocketSource
*)source
;
3828 GSocket
*socket
= socket_source
->socket
;
3834 events
= update_condition (socket_source
->socket
);
3836 if (g_socket_is_closed (socket_source
->socket
))
3838 if (socket_source
->fd_tag
)
3839 g_source_remove_unix_fd (source
, socket_source
->fd_tag
);
3840 socket_source
->fd_tag
= NULL
;
3845 events
= g_source_query_unix_fd (source
, socket_source
->fd_tag
);
3849 timeout
= g_source_get_ready_time (source
);
3850 if (timeout
>= 0 && timeout
< g_source_get_time (source
) &&
3851 !g_socket_is_closed (socket_source
->socket
))
3853 socket
->priv
->timed_out
= TRUE
;
3854 events
|= (G_IO_IN
| G_IO_OUT
);
3857 ret
= (*func
) (socket
, events
& socket_source
->condition
, user_data
);
3859 if (socket
->priv
->timeout
&& !g_socket_is_closed (socket_source
->socket
))
3860 g_source_set_ready_time (source
, g_get_monotonic_time () + socket
->priv
->timeout
* 1000000);
3862 g_source_set_ready_time (source
, -1);
3868 socket_source_finalize (GSource
*source
)
3870 GSocketSource
*socket_source
= (GSocketSource
*)source
;
3873 socket
= socket_source
->socket
;
3876 remove_condition_watch (socket
, &socket_source
->condition
);
3879 g_object_unref (socket
);
3883 socket_source_closure_callback (GSocket
*socket
,
3884 GIOCondition condition
,
3887 GClosure
*closure
= data
;
3889 GValue params
[2] = { G_VALUE_INIT
, G_VALUE_INIT
};
3890 GValue result_value
= G_VALUE_INIT
;
3893 g_value_init (&result_value
, G_TYPE_BOOLEAN
);
3895 g_value_init (¶ms
[0], G_TYPE_SOCKET
);
3896 g_value_set_object (¶ms
[0], socket
);
3897 g_value_init (¶ms
[1], G_TYPE_IO_CONDITION
);
3898 g_value_set_flags (¶ms
[1], condition
);
3900 g_closure_invoke (closure
, &result_value
, 2, params
, NULL
);
3902 result
= g_value_get_boolean (&result_value
);
3903 g_value_unset (&result_value
);
3904 g_value_unset (¶ms
[0]);
3905 g_value_unset (¶ms
[1]);
3910 static GSourceFuncs socket_source_funcs
=
3912 socket_source_prepare
,
3914 socket_source_check_win32
,
3918 socket_source_dispatch
,
3919 socket_source_finalize
,
3920 (GSourceFunc
)socket_source_closure_callback
,
3924 socket_source_new (GSocket
*socket
,
3925 GIOCondition condition
,
3926 GCancellable
*cancellable
)
3929 GSocketSource
*socket_source
;
3932 ensure_event (socket
);
3934 if (socket
->priv
->event
== WSA_INVALID_EVENT
)
3936 g_warning ("Failed to create WSAEvent");
3937 return g_source_new (&broken_funcs
, sizeof (GSource
));
3941 condition
|= G_IO_HUP
| G_IO_ERR
| G_IO_NVAL
;
3943 source
= g_source_new (&socket_source_funcs
, sizeof (GSocketSource
));
3944 g_source_set_name (source
, "GSocket");
3945 socket_source
= (GSocketSource
*)source
;
3947 socket_source
->socket
= g_object_ref (socket
);
3948 socket_source
->condition
= condition
;
3952 GSource
*cancellable_source
;
3954 cancellable_source
= g_cancellable_source_new (cancellable
);
3955 g_source_add_child_source (source
, cancellable_source
);
3956 g_source_set_dummy_callback (cancellable_source
);
3957 g_source_unref (cancellable_source
);
3961 add_condition_watch (socket
, &socket_source
->condition
);
3962 socket_source
->pollfd
.fd
= (gintptr
) socket
->priv
->event
;
3963 socket_source
->pollfd
.events
= condition
;
3964 socket_source
->pollfd
.revents
= 0;
3965 g_source_add_poll (source
, &socket_source
->pollfd
);
3967 socket_source
->fd_tag
= g_source_add_unix_fd (source
, socket
->priv
->fd
, condition
);
3970 if (socket
->priv
->timeout
)
3971 g_source_set_ready_time (source
, g_get_monotonic_time () + socket
->priv
->timeout
* 1000000);
3973 g_source_set_ready_time (source
, -1);
3979 * g_socket_create_source: (skip)
3980 * @socket: a #GSocket
3981 * @condition: a #GIOCondition mask to monitor
3982 * @cancellable: (nullable): a %GCancellable or %NULL
3984 * Creates a #GSource that can be attached to a %GMainContext to monitor
3985 * for the availability of the specified @condition on the socket. The #GSource
3986 * keeps a reference to the @socket.
3988 * The callback on the source is of the #GSocketSourceFunc type.
3990 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3991 * these conditions will always be reported output if they are true.
3993 * @cancellable if not %NULL can be used to cancel the source, which will
3994 * cause the source to trigger, reporting the current condition (which
3995 * is likely 0 unless cancellation happened at the same time as a
3996 * condition change). You can check for this in the callback using
3997 * g_cancellable_is_cancelled().
3999 * If @socket has a timeout set, and it is reached before @condition
4000 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
4001 * %G_IO_OUT depending on @condition. However, @socket will have been
4002 * marked as having had a timeout, and so the next #GSocket I/O method
4003 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
4005 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
4010 g_socket_create_source (GSocket
*socket
,
4011 GIOCondition condition
,
4012 GCancellable
*cancellable
)
4014 g_return_val_if_fail (G_IS_SOCKET (socket
) && (cancellable
== NULL
|| G_IS_CANCELLABLE (cancellable
)), NULL
);
4016 return socket_source_new (socket
, condition
, cancellable
);
4020 * g_socket_condition_check:
4021 * @socket: a #GSocket
4022 * @condition: a #GIOCondition mask to check
4024 * Checks on the readiness of @socket to perform operations.
4025 * The operations specified in @condition are checked for and masked
4026 * against the currently-satisfied conditions on @socket. The result
4029 * Note that on Windows, it is possible for an operation to return
4030 * %G_IO_ERROR_WOULD_BLOCK even immediately after
4031 * g_socket_condition_check() has claimed that the socket is ready for
4032 * writing. Rather than calling g_socket_condition_check() and then
4033 * writing to the socket if it succeeds, it is generally better to
4034 * simply try writing to the socket right away, and try again later if
4035 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
4037 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
4038 * these conditions will always be set in the output if they are true.
4040 * This call never blocks.
4042 * Returns: the @GIOCondition mask of the current state
4047 g_socket_condition_check (GSocket
*socket
,
4048 GIOCondition condition
)
4050 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
4052 if (!check_socket (socket
, NULL
))
4057 GIOCondition current_condition
;
4059 condition
|= G_IO_ERR
| G_IO_HUP
;
4061 add_condition_watch (socket
, &condition
);
4062 current_condition
= update_condition (socket
);
4063 remove_condition_watch (socket
, &condition
);
4064 return condition
& current_condition
;
4070 poll_fd
.fd
= socket
->priv
->fd
;
4071 poll_fd
.events
= condition
;
4072 poll_fd
.revents
= 0;
4075 result
= g_poll (&poll_fd
, 1, 0);
4076 while (result
== -1 && get_socket_errno () == EINTR
);
4078 return poll_fd
.revents
;
4084 * g_socket_condition_wait:
4085 * @socket: a #GSocket
4086 * @condition: a #GIOCondition mask to wait for
4087 * @cancellable: (nullable): a #GCancellable, or %NULL
4088 * @error: a #GError pointer, or %NULL
4090 * Waits for @condition to become true on @socket. When the condition
4091 * is met, %TRUE is returned.
4093 * If @cancellable is cancelled before the condition is met, or if the
4094 * socket has a timeout set and it is reached before the condition is
4095 * met, then %FALSE is returned and @error, if non-%NULL, is set to
4096 * the appropriate value (%G_IO_ERROR_CANCELLED or
4097 * %G_IO_ERROR_TIMED_OUT).
4099 * See also g_socket_condition_timed_wait().
4101 * Returns: %TRUE if the condition was met, %FALSE otherwise
4106 g_socket_condition_wait (GSocket
*socket
,
4107 GIOCondition condition
,
4108 GCancellable
*cancellable
,
4111 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
4113 return g_socket_condition_timed_wait (socket
, condition
, -1,
4114 cancellable
, error
);
4118 * g_socket_condition_timed_wait:
4119 * @socket: a #GSocket
4120 * @condition: a #GIOCondition mask to wait for
4121 * @timeout: the maximum time (in microseconds) to wait, or -1
4122 * @cancellable: (nullable): a #GCancellable, or %NULL
4123 * @error: a #GError pointer, or %NULL
4125 * Waits for up to @timeout microseconds for @condition to become true
4126 * on @socket. If the condition is met, %TRUE is returned.
4128 * If @cancellable is cancelled before the condition is met, or if
4129 * @timeout (or the socket's #GSocket:timeout) is reached before the
4130 * condition is met, then %FALSE is returned and @error, if non-%NULL,
4131 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
4132 * %G_IO_ERROR_TIMED_OUT).
4134 * If you don't want a timeout, use g_socket_condition_wait().
4135 * (Alternatively, you can pass -1 for @timeout.)
4137 * Note that although @timeout is in microseconds for consistency with
4138 * other GLib APIs, this function actually only has millisecond
4139 * resolution, and the behavior is undefined if @timeout is not an
4140 * exact number of milliseconds.
4142 * Returns: %TRUE if the condition was met, %FALSE otherwise
4147 g_socket_condition_timed_wait (GSocket
*socket
,
4148 GIOCondition condition
,
4150 GCancellable
*cancellable
,
4155 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
4157 if (!check_socket (socket
, error
))
4160 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
4163 if (socket
->priv
->timeout
&&
4164 (timeout
< 0 || socket
->priv
->timeout
< timeout
/ G_USEC_PER_SEC
))
4165 timeout
= (gint64
) socket
->priv
->timeout
* 1000;
4166 else if (timeout
!= -1)
4167 timeout
= timeout
/ 1000;
4169 start_time
= g_get_monotonic_time ();
4173 GIOCondition current_condition
;
4179 /* Always check these */
4180 condition
|= G_IO_ERR
| G_IO_HUP
;
4182 add_condition_watch (socket
, &condition
);
4185 events
[num_events
++] = socket
->priv
->event
;
4187 if (g_cancellable_make_pollfd (cancellable
, &cancel_fd
))
4188 events
[num_events
++] = (WSAEVENT
)cancel_fd
.fd
;
4191 timeout
= WSA_INFINITE
;
4193 g_mutex_lock (&socket
->priv
->win32_source_lock
);
4194 current_condition
= update_condition_unlocked (socket
);
4195 while ((condition
& current_condition
) == 0)
4197 if (!socket
->priv
->waiting
)
4199 socket
->priv
->waiting
= TRUE
;
4200 socket
->priv
->waiting_result
= 0;
4201 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
4203 res
= WSAWaitForMultipleEvents (num_events
, events
, FALSE
, timeout
, FALSE
);
4205 g_mutex_lock (&socket
->priv
->win32_source_lock
);
4206 socket
->priv
->waiting
= FALSE
;
4207 socket
->priv
->waiting_result
= res
;
4208 g_cond_broadcast (&socket
->priv
->win32_source_cond
);
4212 if (timeout
!= WSA_INFINITE
)
4214 if (!g_cond_wait_until (&socket
->priv
->win32_source_cond
, &socket
->priv
->win32_source_lock
, timeout
))
4216 res
= WSA_WAIT_TIMEOUT
;
4221 res
= socket
->priv
->waiting_result
;
4226 g_cond_wait (&socket
->priv
->win32_source_cond
, &socket
->priv
->win32_source_lock
);
4227 res
= socket
->priv
->waiting_result
;
4231 if (res
== WSA_WAIT_FAILED
)
4233 int errsv
= get_socket_errno ();
4235 g_set_error (error
, G_IO_ERROR
,
4236 socket_io_error_from_errno (errsv
),
4237 _("Waiting for socket condition: %s"),
4238 socket_strerror (errsv
));
4241 else if (res
== WSA_WAIT_TIMEOUT
)
4243 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
,
4244 _("Socket I/O timed out"));
4248 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
4251 current_condition
= update_condition_unlocked (socket
);
4253 if (timeout
!= WSA_INFINITE
)
4255 timeout
-= (g_get_monotonic_time () - start_time
) * 1000;
4260 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
4261 remove_condition_watch (socket
, &condition
);
4263 g_cancellable_release_fd (cancellable
);
4265 return (condition
& current_condition
) != 0;
4273 poll_fd
[0].fd
= socket
->priv
->fd
;
4274 poll_fd
[0].events
= condition
;
4277 if (g_cancellable_make_pollfd (cancellable
, &poll_fd
[1]))
4283 result
= g_poll (poll_fd
, num
, timeout
);
4285 if (result
!= -1 || errsv
!= EINTR
)
4290 timeout
-= (g_get_monotonic_time () - start_time
) / 1000;
4297 g_cancellable_release_fd (cancellable
);
4301 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
,
4302 _("Socket I/O timed out"));
4306 return !g_cancellable_set_error_if_cancelled (cancellable
, error
);
4313 /* Unfortunately these have to be macros rather than inline functions due to
4314 * using alloca(). */
4315 #define output_message_to_msghdr(message, prev_message, msg, prev_msg, error) \
4317 const GOutputMessage *_message = (message); \
4318 const GOutputMessage *_prev_message = (prev_message); \
4319 struct msghdr *_msg = (msg); \
4320 const struct msghdr *_prev_msg = (prev_msg); \
4321 GError **_error = (error); \
4323 _msg->msg_flags = 0; \
4326 if (_prev_message != NULL && _prev_message->address == _message->address) \
4328 _msg->msg_name = _prev_msg->msg_name; \
4329 _msg->msg_namelen = _prev_msg->msg_namelen; \
4331 else if (_message->address != NULL) \
4333 _msg->msg_namelen = g_socket_address_get_native_size (_message->address); \
4334 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4335 if (!g_socket_address_to_native (_message->address, _msg->msg_name, \
4336 _msg->msg_namelen, _error)) \
4341 _msg->msg_name = NULL; \
4342 _msg->msg_namelen = 0; \
4347 /* this entire expression will be evaluated at compile time */ \
4348 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4349 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4350 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4351 G_STRUCT_OFFSET (GOutputVector, buffer) && \
4352 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4353 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4354 G_STRUCT_OFFSET (GOutputVector, size)) \
4355 /* ABI is compatible */ \
4357 _msg->msg_iov = (struct iovec *) _message->vectors; \
4358 _msg->msg_iovlen = _message->num_vectors; \
4361 /* ABI is incompatible */ \
4365 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4366 for (i = 0; i < _message->num_vectors; i++) \
4368 _msg->msg_iov[i].iov_base = (void *) _message->vectors[i].buffer; \
4369 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4371 _msg->msg_iovlen = _message->num_vectors; \
4377 struct cmsghdr *cmsg; \
4380 _msg->msg_controllen = 0; \
4381 for (i = 0; i < _message->num_control_messages; i++) \
4382 _msg->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (_message->control_messages[i])); \
4384 if (_msg->msg_controllen == 0) \
4385 _msg->msg_control = NULL; \
4388 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4389 memset (_msg->msg_control, '\0', _msg->msg_controllen); \
4392 cmsg = CMSG_FIRSTHDR (_msg); \
4393 for (i = 0; i < _message->num_control_messages; i++) \
4395 cmsg->cmsg_level = g_socket_control_message_get_level (_message->control_messages[i]); \
4396 cmsg->cmsg_type = g_socket_control_message_get_msg_type (_message->control_messages[i]); \
4397 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (_message->control_messages[i])); \
4398 g_socket_control_message_serialize (_message->control_messages[i], \
4399 CMSG_DATA (cmsg)); \
4400 cmsg = CMSG_NXTHDR (_msg, cmsg); \
4402 g_assert (cmsg == NULL); \
4406 #define input_message_to_msghdr(message, msg) \
4408 const GInputMessage *_message = (message); \
4409 struct msghdr *_msg = (msg); \
4412 if (_message->address) \
4414 _msg->msg_namelen = sizeof (struct sockaddr_storage); \
4415 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4419 _msg->msg_name = NULL; \
4420 _msg->msg_namelen = 0; \
4424 /* this entire expression will be evaluated at compile time */ \
4425 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4426 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4427 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4428 G_STRUCT_OFFSET (GInputVector, buffer) && \
4429 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4430 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4431 G_STRUCT_OFFSET (GInputVector, size)) \
4432 /* ABI is compatible */ \
4434 _msg->msg_iov = (struct iovec *) _message->vectors; \
4435 _msg->msg_iovlen = _message->num_vectors; \
4438 /* ABI is incompatible */ \
4442 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4443 for (i = 0; i < _message->num_vectors; i++) \
4445 _msg->msg_iov[i].iov_base = _message->vectors[i].buffer; \
4446 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4448 _msg->msg_iovlen = _message->num_vectors; \
4452 if (_message->control_messages == NULL) \
4454 _msg->msg_controllen = 0; \
4455 _msg->msg_control = NULL; \
4459 _msg->msg_controllen = 2048; \
4460 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4464 _msg->msg_flags = _message->flags; \
4468 input_message_from_msghdr (const struct msghdr
*msg
,
4469 GInputMessage
*message
,
4472 /* decode address */
4473 if (message
->address
!= NULL
)
4475 *message
->address
= cache_recv_address (socket
, msg
->msg_name
,
4479 /* decode control messages */
4481 GPtrArray
*my_messages
= NULL
;
4482 struct cmsghdr
*cmsg
;
4484 if (msg
->msg_controllen
>= sizeof (struct cmsghdr
))
4486 g_assert (message
->control_messages
!= NULL
);
4487 for (cmsg
= CMSG_FIRSTHDR (msg
);
4489 cmsg
= CMSG_NXTHDR ((struct msghdr
*) msg
, cmsg
))
4491 GSocketControlMessage
*control_message
;
4493 control_message
= g_socket_control_message_deserialize (cmsg
->cmsg_level
,
4495 cmsg
->cmsg_len
- ((char *)CMSG_DATA (cmsg
) - (char *)cmsg
),
4497 if (control_message
== NULL
)
4498 /* We've already spewed about the problem in the
4499 deserialization code, so just continue */
4502 if (my_messages
== NULL
)
4503 my_messages
= g_ptr_array_new ();
4504 g_ptr_array_add (my_messages
, control_message
);
4508 if (message
->num_control_messages
)
4509 *message
->num_control_messages
= my_messages
!= NULL
? my_messages
->len
: 0;
4511 if (message
->control_messages
)
4513 if (my_messages
== NULL
)
4515 *message
->control_messages
= NULL
;
4519 g_ptr_array_add (my_messages
, NULL
);
4520 *message
->control_messages
= (GSocketControlMessage
**) g_ptr_array_free (my_messages
, FALSE
);
4525 g_assert (my_messages
== NULL
);
4529 /* capture the flags */
4530 message
->flags
= msg
->msg_flags
;
4535 * g_socket_send_message:
4536 * @socket: a #GSocket
4537 * @address: (nullable): a #GSocketAddress, or %NULL
4538 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4539 * @num_vectors: the number of elements in @vectors, or -1
4540 * @messages: (array length=num_messages) (nullable): a pointer to an
4541 * array of #GSocketControlMessages, or %NULL.
4542 * @num_messages: number of elements in @messages, or -1.
4543 * @flags: an int containing #GSocketMsgFlags flags
4544 * @cancellable: (nullable): a %GCancellable or %NULL
4545 * @error: #GError for error reporting, or %NULL to ignore.
4547 * Send data to @address on @socket. For sending multiple messages see
4548 * g_socket_send_messages(); for easier use, see
4549 * g_socket_send() and g_socket_send_to().
4551 * If @address is %NULL then the message is sent to the default receiver
4552 * (set by g_socket_connect()).
4554 * @vectors must point to an array of #GOutputVector structs and
4555 * @num_vectors must be the length of this array. (If @num_vectors is -1,
4556 * then @vectors is assumed to be terminated by a #GOutputVector with a
4557 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
4558 * that the sent data will be gathered from. Using multiple
4559 * #GOutputVectors is more memory-efficient than manually copying
4560 * data from multiple sources into a single buffer, and more
4561 * network-efficient than making multiple calls to g_socket_send().
4563 * @messages, if non-%NULL, is taken to point to an array of @num_messages
4564 * #GSocketControlMessage instances. These correspond to the control
4565 * messages to be sent on the socket.
4566 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
4569 * @flags modify how the message is sent. The commonly available arguments
4570 * for this are available in the #GSocketMsgFlags enum, but the
4571 * values there are the same as the system values, and the flags
4572 * are passed in as-is, so you can pass in system-specific flags too.
4574 * If the socket is in blocking mode the call will block until there is
4575 * space for the data in the socket queue. If there is no space available
4576 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4577 * will be returned. To be notified when space is available, wait for the
4578 * %G_IO_OUT condition. Note though that you may still receive
4579 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4580 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4581 * very common due to the way the underlying APIs work.)
4583 * On error -1 is returned and @error is set accordingly.
4585 * Returns: Number of bytes written (which may be less than @size), or -1
4591 g_socket_send_message (GSocket
*socket
,
4592 GSocketAddress
*address
,
4593 GOutputVector
*vectors
,
4595 GSocketControlMessage
**messages
,
4598 GCancellable
*cancellable
,
4601 return g_socket_send_message_with_timeout (socket
, address
,
4602 vectors
, num_vectors
,
4603 messages
, num_messages
, flags
,
4604 socket
->priv
->blocking
? -1 : 0,
4605 cancellable
, error
);
4609 g_socket_send_message_with_timeout (GSocket
*socket
,
4610 GSocketAddress
*address
,
4611 GOutputVector
*vectors
,
4613 GSocketControlMessage
**messages
,
4617 GCancellable
*cancellable
,
4620 GOutputVector one_vector
;
4624 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
4625 g_return_val_if_fail (address
== NULL
|| G_IS_SOCKET_ADDRESS (address
), -1);
4626 g_return_val_if_fail (num_vectors
== 0 || vectors
!= NULL
, -1);
4627 g_return_val_if_fail (num_messages
== 0 || messages
!= NULL
, -1);
4628 g_return_val_if_fail (cancellable
== NULL
|| G_IS_CANCELLABLE (cancellable
), -1);
4629 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, -1);
4631 start_time
= g_get_monotonic_time ();
4633 if (!check_socket (socket
, error
))
4636 if (!check_timeout (socket
, error
))
4639 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
4642 if (num_vectors
== -1)
4644 for (num_vectors
= 0;
4645 vectors
[num_vectors
].buffer
!= NULL
;
4650 if (num_messages
== -1)
4652 for (num_messages
= 0;
4653 messages
!= NULL
&& messages
[num_messages
] != NULL
;
4658 if (num_vectors
== 0)
4662 one_vector
.buffer
= &zero
;
4663 one_vector
.size
= 1;
4665 vectors
= &one_vector
;
4670 GOutputMessage output_message
;
4673 GError
*child_error
= NULL
;
4675 output_message
.address
= address
;
4676 output_message
.vectors
= vectors
;
4677 output_message
.num_vectors
= num_vectors
;
4678 output_message
.bytes_sent
= 0;
4679 output_message
.control_messages
= messages
;
4680 output_message
.num_control_messages
= num_messages
;
4682 output_message_to_msghdr (&output_message
, NULL
, &msg
, NULL
, &child_error
);
4684 if (child_error
!= NULL
)
4686 g_propagate_error (error
, child_error
);
4692 result
= sendmsg (socket
->priv
->fd
, &msg
, flags
| G_SOCKET_DEFAULT_SEND_FLAGS
);
4695 int errsv
= get_socket_errno ();
4701 (errsv
== EWOULDBLOCK
||
4704 if (!block_on_timeout (socket
, G_IO_OUT
, timeout
, start_time
,
4705 cancellable
, error
))
4711 socket_set_error_lazy (error
, errsv
, _("Error sending message: %s"));
4721 struct sockaddr_storage addr
;
4728 /* Win32 doesn't support control messages.
4729 Actually this is possible for raw and datagram sockets
4730 via WSASendMessage on Vista or later, but that doesn't
4732 if (num_messages
!= 0)
4734 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
4735 _("GSocketControlMessage not supported on Windows"));
4740 bufs
= g_newa (WSABUF
, num_vectors
);
4741 for (i
= 0; i
< num_vectors
; i
++)
4743 bufs
[i
].buf
= (char *)vectors
[i
].buffer
;
4744 bufs
[i
].len
= (gulong
)vectors
[i
].size
;
4748 addrlen
= 0; /* Avoid warning */
4751 addrlen
= g_socket_address_get_native_size (address
);
4752 if (!g_socket_address_to_native (address
, &addr
, sizeof addr
, error
))
4758 win32_unset_event_mask (socket
, FD_WRITE
);
4761 result
= WSASendTo (socket
->priv
->fd
,
4764 (const struct sockaddr
*)&addr
, addrlen
,
4767 result
= WSASend (socket
->priv
->fd
,
4774 int errsv
= get_socket_errno ();
4776 if (errsv
== WSAEINTR
)
4779 if (errsv
== WSAEWOULDBLOCK
)
4783 if (!block_on_timeout (socket
, G_IO_OUT
, timeout
,
4784 start_time
, cancellable
, error
))
4791 socket_set_error_lazy (error
, errsv
, _("Error sending message: %s"));
4803 * g_socket_send_messages:
4804 * @socket: a #GSocket
4805 * @messages: (array length=num_messages): an array of #GOutputMessage structs
4806 * @num_messages: the number of elements in @messages
4807 * @flags: an int containing #GSocketMsgFlags flags
4808 * @cancellable: (nullable): a %GCancellable or %NULL
4809 * @error: #GError for error reporting, or %NULL to ignore.
4811 * Send multiple data messages from @socket in one go. This is the most
4812 * complicated and fully-featured version of this call. For easier use, see
4813 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
4815 * @messages must point to an array of #GOutputMessage structs and
4816 * @num_messages must be the length of this array. Each #GOutputMessage
4817 * contains an address to send the data to, and a pointer to an array of
4818 * #GOutputVector structs to describe the buffers that the data to be sent
4819 * for each message will be gathered from. Using multiple #GOutputVectors is
4820 * more memory-efficient than manually copying data from multiple sources
4821 * into a single buffer, and more network-efficient than making multiple
4822 * calls to g_socket_send(). Sending multiple messages in one go avoids the
4823 * overhead of making a lot of syscalls in scenarios where a lot of data
4824 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
4825 * or where the same data needs to be sent to multiple recipients.
4827 * @flags modify how the message is sent. The commonly available arguments
4828 * for this are available in the #GSocketMsgFlags enum, but the
4829 * values there are the same as the system values, and the flags
4830 * are passed in as-is, so you can pass in system-specific flags too.
4832 * If the socket is in blocking mode the call will block until there is
4833 * space for all the data in the socket queue. If there is no space available
4834 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4835 * will be returned if no data was written at all, otherwise the number of
4836 * messages sent will be returned. To be notified when space is available,
4837 * wait for the %G_IO_OUT condition. Note though that you may still receive
4838 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4839 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4840 * very common due to the way the underlying APIs work.)
4842 * On error -1 is returned and @error is set accordingly. An error will only
4843 * be returned if zero messages could be sent; otherwise the number of messages
4844 * successfully sent before the error will be returned.
4846 * Returns: number of messages sent, or -1 on error. Note that the number of
4847 * messages sent may be smaller than @num_messages if the socket is
4848 * non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
4849 * in which case the caller may re-try to send the remaining messages.
4854 g_socket_send_messages (GSocket
*socket
,
4855 GOutputMessage
*messages
,
4858 GCancellable
*cancellable
,
4861 return g_socket_send_messages_with_timeout (socket
, messages
, num_messages
,
4863 socket
->priv
->blocking
? -1 : 0,
4864 cancellable
, error
);
4868 g_socket_send_messages_with_timeout (GSocket
*socket
,
4869 GOutputMessage
*messages
,
4873 GCancellable
*cancellable
,
4878 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
4879 g_return_val_if_fail (num_messages
== 0 || messages
!= NULL
, -1);
4880 g_return_val_if_fail (cancellable
== NULL
|| G_IS_CANCELLABLE (cancellable
), -1);
4881 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, -1);
4883 start_time
= g_get_monotonic_time ();
4885 if (!check_socket (socket
, error
))
4888 if (!check_timeout (socket
, error
))
4891 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
4894 if (num_messages
== 0)
4897 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
4899 struct mmsghdr
*msgvec
;
4903 #define MAX_NUM_MESSAGES UIO_MAXIOV
4905 #define MAX_NUM_MESSAGES 1024
4908 if (num_messages
> MAX_NUM_MESSAGES
)
4909 num_messages
= MAX_NUM_MESSAGES
;
4911 msgvec
= g_newa (struct mmsghdr
, num_messages
);
4913 for (i
= 0; i
< num_messages
; ++i
)
4915 GOutputMessage
*msg
= &messages
[i
];
4916 struct msghdr
*msg_hdr
= &msgvec
[i
].msg_hdr
;
4917 GError
*child_error
= NULL
;
4919 msgvec
[i
].msg_len
= 0;
4921 output_message_to_msghdr (msg
, (i
> 0) ? &messages
[i
- 1] : NULL
,
4922 msg_hdr
, (i
> 0) ? &msgvec
[i
- 1].msg_hdr
: NULL
,
4925 if (child_error
!= NULL
)
4927 g_propagate_error (error
, child_error
);
4932 for (num_sent
= 0; num_sent
< num_messages
;)
4936 ret
= sendmmsg (socket
->priv
->fd
, msgvec
+ num_sent
, num_messages
- num_sent
,
4937 flags
| G_SOCKET_DEFAULT_SEND_FLAGS
);
4941 int errsv
= get_socket_errno ();
4947 (errsv
== EWOULDBLOCK
||
4950 if (!block_on_timeout (socket
, G_IO_OUT
, timeout
, start_time
,
4951 cancellable
, error
))
4955 g_clear_error (error
);
4965 /* If any messages were successfully sent, do not error. */
4969 socket_set_error_lazy (error
, errsv
, _("Error sending message: %s"));
4977 for (i
= 0; i
< num_sent
; ++i
)
4978 messages
[i
].bytes_sent
= msgvec
[i
].msg_len
;
4986 gint64 wait_timeout
;
4988 wait_timeout
= timeout
;
4990 for (i
= 0; i
< num_messages
; ++i
)
4992 GOutputMessage
*msg
= &messages
[i
];
4993 GError
*msg_error
= NULL
;
4995 result
= g_socket_send_message_with_timeout (socket
, msg
->address
,
4998 msg
->control_messages
,
4999 msg
->num_control_messages
,
5000 flags
, wait_timeout
,
5001 cancellable
, &msg_error
);
5003 /* check if we've timed out or how much time to wait at most */
5006 gint64 elapsed
= g_get_monotonic_time () - start_time
;
5007 wait_timeout
= MAX (timeout
- elapsed
, 1);
5012 /* if we couldn't send all messages, just return how many we did
5013 * manage to send, provided we managed to send at least one */
5016 g_error_free (msg_error
);
5021 g_propagate_error (error
, msg_error
);
5026 msg
->bytes_sent
= result
;
5034 static GSocketAddress
*
5035 cache_recv_address (GSocket
*socket
, struct sockaddr
*native
, int native_len
)
5037 GSocketAddress
*saddr
;
5039 guint64 oldest_time
= G_MAXUINT64
;
5040 gint oldest_index
= 0;
5042 if (native_len
<= 0)
5046 for (i
= 0; i
< RECV_ADDR_CACHE_SIZE
; i
++)
5048 GSocketAddress
*tmp
= socket
->priv
->recv_addr_cache
[i
].addr
;
5049 gpointer tmp_native
= socket
->priv
->recv_addr_cache
[i
].native
;
5050 gint tmp_native_len
= socket
->priv
->recv_addr_cache
[i
].native_len
;
5055 if (tmp_native_len
!= native_len
)
5058 if (memcmp (tmp_native
, native
, native_len
) == 0)
5060 saddr
= g_object_ref (tmp
);
5061 socket
->priv
->recv_addr_cache
[i
].last_used
= g_get_monotonic_time ();
5065 if (socket
->priv
->recv_addr_cache
[i
].last_used
< oldest_time
)
5067 oldest_time
= socket
->priv
->recv_addr_cache
[i
].last_used
;
5072 saddr
= g_socket_address_new_from_native (native
, native_len
);
5074 if (socket
->priv
->recv_addr_cache
[oldest_index
].addr
)
5076 g_object_unref (socket
->priv
->recv_addr_cache
[oldest_index
].addr
);
5077 g_free (socket
->priv
->recv_addr_cache
[oldest_index
].native
);
5080 socket
->priv
->recv_addr_cache
[oldest_index
].native
= g_memdup (native
, native_len
);
5081 socket
->priv
->recv_addr_cache
[oldest_index
].native_len
= native_len
;
5082 socket
->priv
->recv_addr_cache
[oldest_index
].addr
= g_object_ref (saddr
);
5083 socket
->priv
->recv_addr_cache
[oldest_index
].last_used
= g_get_monotonic_time ();
5089 g_socket_receive_message_with_timeout (GSocket
*socket
,
5090 GSocketAddress
**address
,
5091 GInputVector
*vectors
,
5093 GSocketControlMessage
***messages
,
5097 GCancellable
*cancellable
,
5100 GInputVector one_vector
;
5104 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
5106 start_time
= g_get_monotonic_time ();
5108 if (!check_socket (socket
, error
))
5111 if (!check_timeout (socket
, error
))
5114 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
5117 if (num_vectors
== -1)
5119 for (num_vectors
= 0;
5120 vectors
[num_vectors
].buffer
!= NULL
;
5125 if (num_vectors
== 0)
5127 one_vector
.buffer
= &one_byte
;
5128 one_vector
.size
= 1;
5130 vectors
= &one_vector
;
5135 GInputMessage input_message
;
5139 input_message
.address
= address
;
5140 input_message
.vectors
= vectors
;
5141 input_message
.num_vectors
= num_vectors
;
5142 input_message
.bytes_received
= 0;
5143 input_message
.flags
= (flags
!= NULL
) ? *flags
: 0;
5144 input_message
.control_messages
= messages
;
5145 input_message
.num_control_messages
= (guint
*) num_messages
;
5147 /* We always set the close-on-exec flag so we don't leak file
5148 * descriptors into child processes. Note that gunixfdmessage.c
5149 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5151 #ifdef MSG_CMSG_CLOEXEC
5152 input_message
.flags
|= MSG_CMSG_CLOEXEC
;
5155 input_message_to_msghdr (&input_message
, &msg
);
5160 result
= recvmsg (socket
->priv
->fd
, &msg
, msg
.msg_flags
);
5161 #ifdef MSG_CMSG_CLOEXEC
5162 if (result
< 0 && get_socket_errno () == EINVAL
)
5164 /* We must be running on an old kernel. Call without the flag. */
5165 msg
.msg_flags
&= ~(MSG_CMSG_CLOEXEC
);
5166 result
= recvmsg (socket
->priv
->fd
, &msg
, msg
.msg_flags
);
5172 int errsv
= get_socket_errno ();
5178 (errsv
== EWOULDBLOCK
||
5181 if (!block_on_timeout (socket
, G_IO_IN
, timeout
, start_time
,
5182 cancellable
, error
))
5188 socket_set_error_lazy (error
, errsv
, _("Error receiving message: %s"));
5194 input_message_from_msghdr (&msg
, &input_message
, socket
);
5197 *flags
= input_message
.flags
;
5203 struct sockaddr_storage addr
;
5205 DWORD bytes_received
;
5212 bufs
= g_newa (WSABUF
, num_vectors
);
5213 for (i
= 0; i
< num_vectors
; i
++)
5215 bufs
[i
].buf
= (char *)vectors
[i
].buffer
;
5216 bufs
[i
].len
= (gulong
)vectors
[i
].size
;
5228 win32_unset_event_mask (socket
, FD_READ
);
5230 addrlen
= sizeof addr
;
5232 result
= WSARecvFrom (socket
->priv
->fd
,
5234 &bytes_received
, &win_flags
,
5235 (struct sockaddr
*)&addr
, &addrlen
,
5238 result
= WSARecv (socket
->priv
->fd
,
5240 &bytes_received
, &win_flags
,
5244 int errsv
= get_socket_errno ();
5246 if (errsv
== WSAEINTR
)
5249 if (errsv
== WSAEWOULDBLOCK
)
5253 if (!block_on_timeout (socket
, G_IO_IN
, timeout
,
5254 start_time
, cancellable
, error
))
5261 socket_set_error_lazy (error
, errsv
, _("Error receiving message: %s"));
5267 /* decode address */
5268 if (address
!= NULL
)
5270 *address
= cache_recv_address (socket
, (struct sockaddr
*)&addr
, addrlen
);
5273 /* capture the flags */
5277 if (messages
!= NULL
)
5279 if (num_messages
!= NULL
)
5282 return bytes_received
;
5288 * g_socket_receive_messages:
5289 * @socket: a #GSocket
5290 * @messages: (array length=num_messages): an array of #GInputMessage structs
5291 * @num_messages: the number of elements in @messages
5292 * @flags: an int containing #GSocketMsgFlags flags for the overall operation
5293 * @cancellable: (nullable): a %GCancellable or %NULL
5294 * @error: #GError for error reporting, or %NULL to ignore
5296 * Receive multiple data messages from @socket in one go. This is the most
5297 * complicated and fully-featured version of this call. For easier use, see
5298 * g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
5300 * @messages must point to an array of #GInputMessage structs and
5301 * @num_messages must be the length of this array. Each #GInputMessage
5302 * contains a pointer to an array of #GInputVector structs describing the
5303 * buffers that the data received in each message will be written to. Using
5304 * multiple #GInputVectors is more memory-efficient than manually copying data
5305 * out of a single buffer to multiple sources, and more system-call-efficient
5306 * than making multiple calls to g_socket_receive(), such as in scenarios where
5307 * a lot of data packets need to be received (e.g. high-bandwidth video
5308 * streaming over RTP/UDP).
5310 * @flags modify how all messages are received. The commonly available
5311 * arguments for this are available in the #GSocketMsgFlags enum, but the
5312 * values there are the same as the system values, and the flags
5313 * are passed in as-is, so you can pass in system-specific flags too. These
5314 * flags affect the overall receive operation. Flags affecting individual
5315 * messages are returned in #GInputMessage.flags.
5317 * The other members of #GInputMessage are treated as described in its
5320 * If #GSocket:blocking is %TRUE the call will block until @num_messages have
5321 * been received, or the end of the stream is reached.
5323 * If #GSocket:blocking is %FALSE the call will return up to @num_messages
5324 * without blocking, or %G_IO_ERROR_WOULD_BLOCK if no messages are queued in the
5325 * operating system to be received.
5327 * In blocking mode, if #GSocket:timeout is positive and is reached before any
5328 * messages are received, %G_IO_ERROR_TIMED_OUT is returned, otherwise up to
5329 * @num_messages are returned. (Note: This is effectively the
5330 * behaviour of `MSG_WAITFORONE` with recvmmsg().)
5332 * To be notified when messages are available, wait for the
5333 * %G_IO_IN condition. Note though that you may still receive
5334 * %G_IO_ERROR_WOULD_BLOCK from g_socket_receive_messages() even if you were
5335 * previously notified of a %G_IO_IN condition.
5337 * If the remote peer closes the connection, any messages queued in the
5338 * operating system will be returned, and subsequent calls to
5339 * g_socket_receive_messages() will return 0 (with no error set).
5341 * On error -1 is returned and @error is set accordingly. An error will only
5342 * be returned if zero messages could be received; otherwise the number of
5343 * messages successfully received before the error will be returned.
5345 * Returns: number of messages received, or -1 on error. Note that the number
5346 * of messages received may be smaller than @num_messages if in non-blocking
5347 * mode, if the peer closed the connection, or if @num_messages
5348 * was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
5349 * to receive the remaining messages.
5354 g_socket_receive_messages (GSocket
*socket
,
5355 GInputMessage
*messages
,
5358 GCancellable
*cancellable
,
5361 if (!check_socket (socket
, error
) ||
5362 !check_timeout (socket
, error
))
5365 return g_socket_receive_messages_with_timeout (socket
, messages
, num_messages
,
5367 socket
->priv
->blocking
? -1 : 0,
5368 cancellable
, error
);
5372 g_socket_receive_messages_with_timeout (GSocket
*socket
,
5373 GInputMessage
*messages
,
5377 GCancellable
*cancellable
,
5382 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
5383 g_return_val_if_fail (num_messages
== 0 || messages
!= NULL
, -1);
5384 g_return_val_if_fail (cancellable
== NULL
||
5385 G_IS_CANCELLABLE (cancellable
), -1);
5386 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, -1);
5388 start_time
= g_get_monotonic_time ();
5390 if (!check_socket (socket
, error
))
5393 if (!check_timeout (socket
, error
))
5396 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
5399 if (num_messages
== 0)
5402 #if !defined (G_OS_WIN32) && defined (HAVE_RECVMMSG)
5404 struct mmsghdr
*msgvec
;
5405 guint i
, num_received
;
5408 #define MAX_NUM_MESSAGES UIO_MAXIOV
5410 #define MAX_NUM_MESSAGES 1024
5413 if (num_messages
> MAX_NUM_MESSAGES
)
5414 num_messages
= MAX_NUM_MESSAGES
;
5416 msgvec
= g_newa (struct mmsghdr
, num_messages
);
5418 for (i
= 0; i
< num_messages
; ++i
)
5420 GInputMessage
*msg
= &messages
[i
];
5421 struct msghdr
*msg_hdr
= &msgvec
[i
].msg_hdr
;
5423 input_message_to_msghdr (msg
, msg_hdr
);
5424 msgvec
[i
].msg_len
= 0;
5427 /* We always set the close-on-exec flag so we don't leak file
5428 * descriptors into child processes. Note that gunixfdmessage.c
5429 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5431 #ifdef MSG_CMSG_CLOEXEC
5432 flags
|= MSG_CMSG_CLOEXEC
;
5435 for (num_received
= 0; num_received
< num_messages
;)
5439 /* We operate in non-blocking mode and handle the timeout ourselves. */
5440 ret
= recvmmsg (socket
->priv
->fd
,
5441 msgvec
+ num_received
,
5442 num_messages
- num_received
,
5443 flags
| G_SOCKET_DEFAULT_SEND_FLAGS
, NULL
);
5444 #ifdef MSG_CMSG_CLOEXEC
5445 if (ret
< 0 && get_socket_errno () == EINVAL
)
5447 /* We must be running on an old kernel. Call without the flag. */
5448 flags
&= ~(MSG_CMSG_CLOEXEC
);
5449 ret
= recvmmsg (socket
->priv
->fd
,
5450 msgvec
+ num_received
,
5451 num_messages
- num_received
,
5452 flags
| G_SOCKET_DEFAULT_SEND_FLAGS
, NULL
);
5458 int errsv
= get_socket_errno ();
5464 (errsv
== EWOULDBLOCK
||
5467 if (!block_on_timeout (socket
, G_IO_IN
, timeout
, start_time
,
5468 cancellable
, error
))
5470 if (num_received
> 0)
5472 g_clear_error (error
);
5482 /* If any messages were successfully received, do not error. */
5483 if (num_received
> 0)
5486 socket_set_error_lazy (error
, errsv
,
5487 _("Error receiving message: %s"));
5497 num_received
+= ret
;
5500 for (i
= 0; i
< num_received
; ++i
)
5502 input_message_from_msghdr (&msgvec
[i
].msg_hdr
, &messages
[i
], socket
);
5503 messages
[i
].bytes_received
= msgvec
[i
].msg_len
;
5506 return num_received
;
5511 gint64 wait_timeout
;
5513 wait_timeout
= timeout
;
5515 for (i
= 0; i
< num_messages
; i
++)
5517 GInputMessage
*msg
= &messages
[i
];
5519 GError
*msg_error
= NULL
;
5521 msg
->flags
= flags
; /* in-out parameter */
5523 len
= g_socket_receive_message_with_timeout (socket
,
5527 msg
->control_messages
,
5528 (gint
*) msg
->num_control_messages
,
5534 /* check if we've timed out or how much time to wait at most */
5537 gint64 elapsed
= g_get_monotonic_time () - start_time
;
5538 wait_timeout
= MAX (timeout
- elapsed
, 1);
5542 msg
->bytes_received
= len
;
5545 (g_error_matches (msg_error
, G_IO_ERROR
, G_IO_ERROR_WOULD_BLOCK
) ||
5546 g_error_matches (msg_error
, G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
)))
5548 g_clear_error (&msg_error
);
5552 if (msg_error
!= NULL
)
5554 g_propagate_error (error
, msg_error
);
5568 * g_socket_receive_message:
5569 * @socket: a #GSocket
5570 * @address: (out) (optional): a pointer to a #GSocketAddress
5572 * @vectors: (array length=num_vectors): an array of #GInputVector structs
5573 * @num_vectors: the number of elements in @vectors, or -1
5574 * @messages: (array length=num_messages) (out) (optional) (nullable): a pointer
5575 * which may be filled with an array of #GSocketControlMessages, or %NULL
5576 * @num_messages: (out): a pointer which will be filled with the number of
5577 * elements in @messages, or %NULL
5578 * @flags: (inout): a pointer to an int containing #GSocketMsgFlags flags
5579 * @cancellable: a %GCancellable or %NULL
5580 * @error: a #GError pointer, or %NULL
5582 * Receive data from a socket. For receiving multiple messages, see
5583 * g_socket_receive_messages(); for easier use, see
5584 * g_socket_receive() and g_socket_receive_from().
5586 * If @address is non-%NULL then @address will be set equal to the
5587 * source address of the received packet.
5588 * @address is owned by the caller.
5590 * @vector must point to an array of #GInputVector structs and
5591 * @num_vectors must be the length of this array. These structs
5592 * describe the buffers that received data will be scattered into.
5593 * If @num_vectors is -1, then @vectors is assumed to be terminated
5594 * by a #GInputVector with a %NULL buffer pointer.
5596 * As a special case, if @num_vectors is 0 (in which case, @vectors
5597 * may of course be %NULL), then a single byte is received and
5598 * discarded. This is to facilitate the common practice of sending a
5599 * single '\0' byte for the purposes of transferring ancillary data.
5601 * @messages, if non-%NULL, will be set to point to a newly-allocated
5602 * array of #GSocketControlMessage instances or %NULL if no such
5603 * messages was received. These correspond to the control messages
5604 * received from the kernel, one #GSocketControlMessage per message
5605 * from the kernel. This array is %NULL-terminated and must be freed
5606 * by the caller using g_free() after calling g_object_unref() on each
5607 * element. If @messages is %NULL, any control messages received will
5610 * @num_messages, if non-%NULL, will be set to the number of control
5611 * messages received.
5613 * If both @messages and @num_messages are non-%NULL, then
5614 * @num_messages gives the number of #GSocketControlMessage instances
5615 * in @messages (ie: not including the %NULL terminator).
5617 * @flags is an in/out parameter. The commonly available arguments
5618 * for this are available in the #GSocketMsgFlags enum, but the
5619 * values there are the same as the system values, and the flags
5620 * are passed in as-is, so you can pass in system-specific flags too
5621 * (and g_socket_receive_message() may pass system-specific flags out).
5622 * Flags passed in to the parameter affect the receive operation; flags returned
5623 * out of it are relevant to the specific returned message.
5625 * As with g_socket_receive(), data may be discarded if @socket is
5626 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
5627 * provide enough buffer space to read a complete message. You can pass
5628 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
5629 * removing it from the receive queue, but there is no portable way to find
5630 * out the length of the message other than by reading it into a
5631 * sufficiently-large buffer.
5633 * If the socket is in blocking mode the call will block until there
5634 * is some data to receive, the connection is closed, or there is an
5635 * error. If there is no data available and the socket is in
5636 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
5637 * returned. To be notified when data is available, wait for the
5638 * %G_IO_IN condition.
5640 * On error -1 is returned and @error is set accordingly.
5642 * Returns: Number of bytes read, or 0 if the connection was closed by
5643 * the peer, or -1 on error
5648 g_socket_receive_message (GSocket
*socket
,
5649 GSocketAddress
**address
,
5650 GInputVector
*vectors
,
5652 GSocketControlMessage
***messages
,
5655 GCancellable
*cancellable
,
5658 return g_socket_receive_message_with_timeout (socket
, address
, vectors
,
5659 num_vectors
, messages
,
5660 num_messages
, flags
,
5661 socket
->priv
->blocking
? -1 : 0,
5662 cancellable
, error
);
5666 * g_socket_get_credentials:
5667 * @socket: a #GSocket.
5668 * @error: #GError for error reporting, or %NULL to ignore.
5670 * Returns the credentials of the foreign process connected to this
5671 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
5674 * If this operation isn't supported on the OS, the method fails with
5675 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
5676 * by reading the %SO_PEERCRED option on the underlying socket.
5678 * Other ways to obtain credentials from a foreign peer includes the
5679 * #GUnixCredentialsMessage type and
5680 * g_unix_connection_send_credentials() /
5681 * g_unix_connection_receive_credentials() functions.
5683 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
5684 * that must be freed with g_object_unref().
5689 g_socket_get_credentials (GSocket
*socket
,
5694 g_return_val_if_fail (G_IS_SOCKET (socket
), NULL
);
5695 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
5699 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
5703 guint8 native_creds_buf
[G_CREDENTIALS_NATIVE_SIZE
];
5704 socklen_t optlen
= sizeof (native_creds_buf
);
5706 if (getsockopt (socket
->priv
->fd
,
5712 ret
= g_credentials_new ();
5713 g_credentials_set_native (ret
,
5714 G_CREDENTIALS_NATIVE_TYPE
,
5718 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
5720 struct unpcbid cred
;
5721 socklen_t optlen
= sizeof (cred
);
5723 if (getsockopt (socket
->priv
->fd
,
5729 ret
= g_credentials_new ();
5730 g_credentials_set_native (ret
,
5731 G_CREDENTIALS_NATIVE_TYPE
,
5735 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
5737 ucred_t
*ucred
= NULL
;
5739 if (getpeerucred (socket
->priv
->fd
, &ucred
) == 0)
5741 ret
= g_credentials_new ();
5742 g_credentials_set_native (ret
,
5743 G_CREDENTIALS_TYPE_SOLARIS_UCRED
,
5749 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
5754 int errsv
= get_socket_errno ();
5758 socket_io_error_from_errno (errsv
),
5759 _("Unable to read socket credentials: %s"),
5760 socket_strerror (errsv
));
5765 g_set_error_literal (error
,
5767 G_IO_ERROR_NOT_SUPPORTED
,
5768 _("g_socket_get_credentials not implemented for this OS"));
5775 * g_socket_get_option:
5776 * @socket: a #GSocket
5777 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5778 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5779 * @value: (out): return location for the option value
5780 * @error: #GError for error reporting, or %NULL to ignore.
5782 * Gets the value of an integer-valued option on @socket, as with
5783 * getsockopt(). (If you need to fetch a non-integer-valued option,
5784 * you will need to call getsockopt() directly.)
5786 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5787 * header pulls in system headers that will define most of the
5788 * standard/portable socket options. For unusual socket protocols or
5789 * platform-dependent options, you may need to include additional
5792 * Note that even for socket options that are a single byte in size,
5793 * @value is still a pointer to a #gint variable, not a #guchar;
5794 * g_socket_get_option() will handle the conversion internally.
5796 * Returns: success or failure. On failure, @error will be set, and
5797 * the system error value (`errno` or WSAGetLastError()) will still
5798 * be set to the result of the getsockopt() call.
5803 g_socket_get_option (GSocket
*socket
,
5811 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
5814 size
= sizeof (gint
);
5815 if (getsockopt (socket
->priv
->fd
, level
, optname
, value
, &size
) != 0)
5817 int errsv
= get_socket_errno ();
5819 g_set_error_literal (error
,
5821 socket_io_error_from_errno (errsv
),
5822 socket_strerror (errsv
));
5824 /* Reset errno in case the caller wants to look at it */
5830 #if G_BYTE_ORDER == G_BIG_ENDIAN
5831 /* If the returned value is smaller than an int then we need to
5832 * slide it over into the low-order bytes of *value.
5834 if (size
!= sizeof (gint
))
5835 *value
= *value
>> (8 * (sizeof (gint
) - size
));
5842 * g_socket_set_option:
5843 * @socket: a #GSocket
5844 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5845 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5846 * @value: the value to set the option to
5847 * @error: #GError for error reporting, or %NULL to ignore.
5849 * Sets the value of an integer-valued option on @socket, as with
5850 * setsockopt(). (If you need to set a non-integer-valued option,
5851 * you will need to call setsockopt() directly.)
5853 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5854 * header pulls in system headers that will define most of the
5855 * standard/portable socket options. For unusual socket protocols or
5856 * platform-dependent options, you may need to include additional
5859 * Returns: success or failure. On failure, @error will be set, and
5860 * the system error value (`errno` or WSAGetLastError()) will still
5861 * be set to the result of the setsockopt() call.
5866 g_socket_set_option (GSocket
*socket
,
5874 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
5876 if (setsockopt (socket
->priv
->fd
, level
, optname
, &value
, sizeof (gint
)) == 0)
5879 #if !defined (__linux__) && !defined (G_OS_WIN32)
5880 /* Linux and Windows let you set a single-byte value from an int,
5881 * but most other platforms don't.
5883 if (errno
== EINVAL
&& value
>= SCHAR_MIN
&& value
<= CHAR_MAX
)
5885 #if G_BYTE_ORDER == G_BIG_ENDIAN
5886 value
= value
<< (8 * (sizeof (gint
) - 1));
5888 if (setsockopt (socket
->priv
->fd
, level
, optname
, &value
, 1) == 0)
5893 errsv
= get_socket_errno ();
5895 g_set_error_literal (error
,
5897 socket_io_error_from_errno (errsv
),
5898 socket_strerror (errsv
));