meson: work around meson not passing on the threads dependency when link_with is...
[glib.git] / gio / gsocket.c
blob567b4802eed7e3aeafda899533b2d0bce0df6daf
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>
28 #include "config.h"
30 #include "gsocket.h"
32 #ifdef G_OS_UNIX
33 #include "glib-unix.h"
34 #endif
36 #include <errno.h>
37 #include <signal.h>
38 #include <string.h>
39 #include <stdlib.h>
41 #ifndef G_OS_WIN32
42 # include <fcntl.h>
43 # include <unistd.h>
44 # include <sys/ioctl.h>
45 #endif
47 #ifdef HAVE_SIOCGIFADDR
48 #include <net/if.h>
49 #endif
51 #ifdef HAVE_SYS_FILIO_H
52 # include <sys/filio.h>
53 #endif
55 #ifdef G_OS_UNIX
56 #include <sys/uio.h>
57 #endif
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"
68 #include "gioerror.h"
69 #include "gioenums.h"
70 #include "gioerror.h"
71 #include "gnetworkingprivate.h"
72 #include "gsocketaddress.h"
73 #include "gsocketcontrolmessage.h"
74 #include "gcredentials.h"
75 #include "gcredentialsprivate.h"
76 #include "glibintl.h"
78 #ifdef G_OS_WIN32
79 /* For Windows XP runtime compatibility, but use the system's if_nametoindex() if available */
80 #include "gwin32networking.h"
81 #endif
83 /**
84 * SECTION:gsocket
85 * @short_description: Low-level socket object
86 * @include: gio/gio.h
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
103 * %NULL.
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
139 * locking.
141 * Since: 2.22
144 static void g_socket_initable_iface_init (GInitableIface *iface);
145 static gboolean g_socket_initable_init (GInitable *initable,
146 GCancellable *cancellable,
147 GError **error);
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,
152 guint num_messages,
153 gint flags,
154 gint64 timeout,
155 GCancellable *cancellable,
156 GError **error);
157 static gint g_socket_datagram_based_send_messages (GDatagramBased *self,
158 GOutputMessage *messages,
159 guint num_messages,
160 gint flags,
161 gint64 timeout,
162 GCancellable *cancellable,
163 GError **error);
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,
171 gint64 timeout,
172 GCancellable *cancellable,
173 GError **error);
175 static GSocketAddress *
176 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len);
178 static gssize
179 g_socket_receive_message_with_timeout (GSocket *socket,
180 GSocketAddress **address,
181 GInputVector *vectors,
182 gint num_vectors,
183 GSocketControlMessage ***messages,
184 gint *num_messages,
185 gint *flags,
186 gint64 timeout,
187 GCancellable *cancellable,
188 GError **error);
189 static gint
190 g_socket_receive_messages_with_timeout (GSocket *socket,
191 GInputMessage *messages,
192 guint num_messages,
193 gint flags,
194 gint64 timeout,
195 GCancellable *cancellable,
196 GError **error);
197 static gssize
198 g_socket_send_message_with_timeout (GSocket *socket,
199 GSocketAddress *address,
200 GOutputVector *vectors,
201 gint num_vectors,
202 GSocketControlMessage **messages,
203 gint num_messages,
204 gint flags,
205 gint64 timeout,
206 GCancellable *cancellable,
207 GError **error);
208 static gint
209 g_socket_send_messages_with_timeout (GSocket *socket,
210 GOutputMessage *messages,
211 guint num_messages,
212 gint flags,
213 gint64 timeout,
214 GCancellable *cancellable,
215 GError **error);
217 enum
219 PROP_0,
220 PROP_FAMILY,
221 PROP_TYPE,
222 PROP_PROTOCOL,
223 PROP_FD,
224 PROP_BLOCKING,
225 PROP_LISTEN_BACKLOG,
226 PROP_KEEPALIVE,
227 PROP_LOCAL_ADDRESS,
228 PROP_REMOTE_ADDRESS,
229 PROP_TIMEOUT,
230 PROP_TTL,
231 PROP_BROADCAST,
232 PROP_MULTICAST_LOOPBACK,
233 PROP_MULTICAST_TTL
236 /* Size of the receiver cache for g_socket_receive_from() */
237 #define RECV_ADDR_CACHE_SIZE 8
239 struct _GSocketPrivate
241 GSocketFamily family;
242 GSocketType type;
243 GSocketProtocol protocol;
244 gint fd;
245 gint listen_backlog;
246 guint timeout;
247 GError *construct_error;
248 GSocketAddress *remote_address;
249 guint inited : 1;
250 guint blocking : 1;
251 guint keepalive : 1;
252 guint closed : 1;
253 guint connected_read : 1;
254 guint connected_write : 1;
255 guint listening : 1;
256 guint timed_out : 1;
257 guint connect_pending : 1;
258 #ifdef G_OS_WIN32
259 WSAEVENT event;
260 gboolean waiting;
261 DWORD waiting_result;
262 int current_events;
263 int current_errors;
264 int selected_events;
265 GList *requested_conditions; /* list of requested GIOCondition * */
266 GMutex win32_source_lock;
267 GCond win32_source_cond;
268 #endif
270 struct {
271 GSocketAddress *addr;
272 struct sockaddr *native;
273 gint native_len;
274 guint64 last_used;
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));
293 static int
294 get_socket_errno (void)
296 #ifndef G_OS_WIN32
297 return errno;
298 #else
299 return WSAGetLastError ();
300 #endif
303 static GIOErrorEnum
304 socket_io_error_from_errno (int err)
306 #ifdef G_OS_WIN32
307 return g_io_error_from_win32_error (err);
308 #else
309 return g_io_error_from_errno (err);
310 #endif
313 static const char *
314 socket_strerror (int err)
316 #ifndef G_OS_WIN32
317 return g_strerror (err);
318 #else
319 const char *msg_ret;
320 char *msg;
322 msg = g_win32_error_message (err);
324 msg_ret = g_intern_string (msg);
325 g_free (msg);
327 return msg_ret;
328 #endif
331 /* Wrapper around g_set_error() to avoid doing excess work */
332 #define socket_set_error_lazy(err, errsv, fmt) \
333 G_STMT_START { \
334 GError **__err = (err); \
335 int __errsv = (errsv); \
337 if (__err) \
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); \
344 else \
345 g_set_error (__err, G_IO_ERROR, __code, fmt, __strerr); \
347 } G_STMT_END
349 #ifdef G_OS_WIN32
350 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
351 static void
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);
359 #else
360 #define win32_unset_event_mask(_socket, _mask)
361 #endif
363 /* Windows has broken prototypes... */
364 #ifdef G_OS_WIN32
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)
375 #endif
377 static gboolean
378 check_socket (GSocket *socket,
379 GError **error)
381 if (!socket->priv->inited)
383 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
384 _("Invalid socket, not initialized"));
385 return FALSE;
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);
393 return FALSE;
396 if (socket->priv->closed)
398 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
399 _("Socket is already closed"));
400 return FALSE;
403 return TRUE;
406 static gboolean
407 check_timeout (GSocket *socket,
408 GError **error)
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"));
415 return FALSE;
418 return TRUE;
421 static void
422 g_socket_details_from_fd (GSocket *socket)
424 struct sockaddr_storage address;
425 gint fd;
426 guint addrlen;
427 int value, family;
428 int errsv;
430 fd = socket->priv->fd;
431 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
433 errsv = get_socket_errno ();
434 goto err;
437 switch (value)
439 case SOCK_STREAM:
440 socket->priv->type = G_SOCKET_TYPE_STREAM;
441 break;
443 case SOCK_DGRAM:
444 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
445 break;
447 case SOCK_SEQPACKET:
448 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
449 break;
451 default:
452 socket->priv->type = G_SOCKET_TYPE_INVALID;
453 break;
456 addrlen = sizeof address;
457 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
459 errsv = get_socket_errno ();
460 goto err;
463 if (addrlen > 0)
465 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
466 sizeof address.ss_family <= addrlen);
467 family = address.ss_family;
469 else
471 /* On Solaris, this happens if the socket is not yet connected.
472 * But we can use SO_DOMAIN as a workaround there.
474 #ifdef SO_DOMAIN
475 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
477 errsv = get_socket_errno ();
478 goto err;
480 #else
481 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
482 errsv = -1;
483 goto err;
484 #endif
487 switch (family)
489 case G_SOCKET_FAMILY_IPV4:
490 case G_SOCKET_FAMILY_IPV6:
491 socket->priv->family = address.ss_family;
492 switch (socket->priv->type)
494 case G_SOCKET_TYPE_STREAM:
495 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
496 break;
498 case G_SOCKET_TYPE_DATAGRAM:
499 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
500 break;
502 case G_SOCKET_TYPE_SEQPACKET:
503 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
504 break;
506 default:
507 break;
509 break;
511 case G_SOCKET_FAMILY_UNIX:
512 socket->priv->family = G_SOCKET_FAMILY_UNIX;
513 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
514 break;
516 default:
517 socket->priv->family = G_SOCKET_FAMILY_INVALID;
518 break;
521 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
523 addrlen = sizeof address;
524 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
526 socket->priv->connected_read = TRUE;
527 socket->priv->connected_write = TRUE;
531 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
533 socket->priv->keepalive = !!value;
535 else
537 /* Can't read, maybe not supported, assume FALSE */
538 socket->priv->keepalive = FALSE;
541 return;
543 err:
544 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
545 socket_io_error_from_errno (errsv),
546 _("creating GSocket from fd: %s"),
547 socket_strerror (errsv));
550 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
551 gint
552 g_socket (gint domain,
553 gint type,
554 gint protocol,
555 GError **error)
557 int fd, errsv;
559 #ifdef SOCK_CLOEXEC
560 fd = socket (domain, type | SOCK_CLOEXEC, protocol);
561 errsv = errno;
562 if (fd != -1)
563 return fd;
565 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
566 if (fd < 0 && (errsv == EINVAL || errsv == EPROTOTYPE))
567 #endif
568 fd = socket (domain, type, protocol);
570 if (fd < 0)
572 int errsv = get_socket_errno ();
574 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
575 _("Unable to create socket: %s"), socket_strerror (errsv));
576 errno = errsv;
577 return -1;
580 #ifndef G_OS_WIN32
582 int flags;
584 /* We always want to set close-on-exec to protect users. If you
585 need to so some weird inheritance to exec you can re-enable this
586 using lower level hacks with g_socket_get_fd(). */
587 flags = fcntl (fd, F_GETFD, 0);
588 if (flags != -1 &&
589 (flags & FD_CLOEXEC) == 0)
591 flags |= FD_CLOEXEC;
592 fcntl (fd, F_SETFD, flags);
595 #endif
597 return fd;
600 static gint
601 g_socket_create_socket (GSocketFamily family,
602 GSocketType type,
603 int protocol,
604 GError **error)
606 gint native_type;
608 switch (type)
610 case G_SOCKET_TYPE_STREAM:
611 native_type = SOCK_STREAM;
612 break;
614 case G_SOCKET_TYPE_DATAGRAM:
615 native_type = SOCK_DGRAM;
616 break;
618 case G_SOCKET_TYPE_SEQPACKET:
619 native_type = SOCK_SEQPACKET;
620 break;
622 default:
623 g_assert_not_reached ();
626 if (family <= 0)
628 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
629 _("Unable to create socket: %s"), _("Unknown family was specified"));
630 return -1;
633 if (protocol == -1)
635 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
636 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
637 return -1;
640 return g_socket (family, native_type, protocol, error);
643 static void
644 g_socket_constructed (GObject *object)
646 GSocket *socket = G_SOCKET (object);
648 if (socket->priv->fd >= 0)
649 /* create socket->priv info from the fd */
650 g_socket_details_from_fd (socket);
652 else
653 /* create the fd from socket->priv info */
654 socket->priv->fd = g_socket_create_socket (socket->priv->family,
655 socket->priv->type,
656 socket->priv->protocol,
657 &socket->priv->construct_error);
659 if (socket->priv->fd != -1)
661 #ifndef G_OS_WIN32
662 GError *error = NULL;
663 #else
664 gulong arg;
665 #endif
667 /* Always use native nonblocking sockets, as Windows sets sockets to
668 * nonblocking automatically in certain operations. This way we make
669 * things work the same on all platforms.
671 #ifndef G_OS_WIN32
672 if (!g_unix_set_fd_nonblocking (socket->priv->fd, TRUE, &error))
674 g_warning ("Error setting socket nonblocking: %s", error->message);
675 g_clear_error (&error);
677 #else
678 arg = TRUE;
680 if (ioctlsocket (socket->priv->fd, FIONBIO, &arg) == SOCKET_ERROR)
682 int errsv = get_socket_errno ();
683 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
685 #endif
687 #ifdef SO_NOSIGPIPE
688 /* See note about SIGPIPE below. */
689 g_socket_set_option (socket, SOL_SOCKET, SO_NOSIGPIPE, TRUE, NULL);
690 #endif
694 static void
695 g_socket_get_property (GObject *object,
696 guint prop_id,
697 GValue *value,
698 GParamSpec *pspec)
700 GSocket *socket = G_SOCKET (object);
701 GSocketAddress *address;
703 switch (prop_id)
705 case PROP_FAMILY:
706 g_value_set_enum (value, socket->priv->family);
707 break;
709 case PROP_TYPE:
710 g_value_set_enum (value, socket->priv->type);
711 break;
713 case PROP_PROTOCOL:
714 g_value_set_enum (value, socket->priv->protocol);
715 break;
717 case PROP_FD:
718 g_value_set_int (value, socket->priv->fd);
719 break;
721 case PROP_BLOCKING:
722 g_value_set_boolean (value, socket->priv->blocking);
723 break;
725 case PROP_LISTEN_BACKLOG:
726 g_value_set_int (value, socket->priv->listen_backlog);
727 break;
729 case PROP_KEEPALIVE:
730 g_value_set_boolean (value, socket->priv->keepalive);
731 break;
733 case PROP_LOCAL_ADDRESS:
734 address = g_socket_get_local_address (socket, NULL);
735 g_value_take_object (value, address);
736 break;
738 case PROP_REMOTE_ADDRESS:
739 address = g_socket_get_remote_address (socket, NULL);
740 g_value_take_object (value, address);
741 break;
743 case PROP_TIMEOUT:
744 g_value_set_uint (value, socket->priv->timeout);
745 break;
747 case PROP_TTL:
748 g_value_set_uint (value, g_socket_get_ttl (socket));
749 break;
751 case PROP_BROADCAST:
752 g_value_set_boolean (value, g_socket_get_broadcast (socket));
753 break;
755 case PROP_MULTICAST_LOOPBACK:
756 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
757 break;
759 case PROP_MULTICAST_TTL:
760 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
761 break;
763 default:
764 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
768 static void
769 g_socket_set_property (GObject *object,
770 guint prop_id,
771 const GValue *value,
772 GParamSpec *pspec)
774 GSocket *socket = G_SOCKET (object);
776 switch (prop_id)
778 case PROP_FAMILY:
779 socket->priv->family = g_value_get_enum (value);
780 break;
782 case PROP_TYPE:
783 socket->priv->type = g_value_get_enum (value);
784 break;
786 case PROP_PROTOCOL:
787 socket->priv->protocol = g_value_get_enum (value);
788 break;
790 case PROP_FD:
791 socket->priv->fd = g_value_get_int (value);
792 break;
794 case PROP_BLOCKING:
795 g_socket_set_blocking (socket, g_value_get_boolean (value));
796 break;
798 case PROP_LISTEN_BACKLOG:
799 g_socket_set_listen_backlog (socket, g_value_get_int (value));
800 break;
802 case PROP_KEEPALIVE:
803 g_socket_set_keepalive (socket, g_value_get_boolean (value));
804 break;
806 case PROP_TIMEOUT:
807 g_socket_set_timeout (socket, g_value_get_uint (value));
808 break;
810 case PROP_TTL:
811 g_socket_set_ttl (socket, g_value_get_uint (value));
812 break;
814 case PROP_BROADCAST:
815 g_socket_set_broadcast (socket, g_value_get_boolean (value));
816 break;
818 case PROP_MULTICAST_LOOPBACK:
819 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
820 break;
822 case PROP_MULTICAST_TTL:
823 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
824 break;
826 default:
827 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
831 static void
832 g_socket_finalize (GObject *object)
834 GSocket *socket = G_SOCKET (object);
835 gint i;
837 g_clear_error (&socket->priv->construct_error);
839 if (socket->priv->fd != -1 &&
840 !socket->priv->closed)
841 g_socket_close (socket, NULL);
843 if (socket->priv->remote_address)
844 g_object_unref (socket->priv->remote_address);
846 #ifdef G_OS_WIN32
847 if (socket->priv->event != WSA_INVALID_EVENT)
849 WSACloseEvent (socket->priv->event);
850 socket->priv->event = WSA_INVALID_EVENT;
853 g_assert (socket->priv->requested_conditions == NULL);
854 g_mutex_clear (&socket->priv->win32_source_lock);
855 g_cond_clear (&socket->priv->win32_source_cond);
856 #endif
858 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
860 if (socket->priv->recv_addr_cache[i].addr)
862 g_object_unref (socket->priv->recv_addr_cache[i].addr);
863 g_free (socket->priv->recv_addr_cache[i].native);
867 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
868 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
871 static void
872 g_socket_class_init (GSocketClass *klass)
874 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
876 #ifdef SIGPIPE
877 /* There is no portable, thread-safe way to avoid having the process
878 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
879 * forced to simply ignore the signal process-wide.
881 * Even if we ignore it though, gdb will still stop if the app
882 * receives a SIGPIPE, which can be confusing and annoying. So when
883 * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
884 * prevent the signal from occurring at all.
886 signal (SIGPIPE, SIG_IGN);
887 #endif
889 gobject_class->finalize = g_socket_finalize;
890 gobject_class->constructed = g_socket_constructed;
891 gobject_class->set_property = g_socket_set_property;
892 gobject_class->get_property = g_socket_get_property;
894 g_object_class_install_property (gobject_class, PROP_FAMILY,
895 g_param_spec_enum ("family",
896 P_("Socket family"),
897 P_("The sockets address family"),
898 G_TYPE_SOCKET_FAMILY,
899 G_SOCKET_FAMILY_INVALID,
900 G_PARAM_CONSTRUCT_ONLY |
901 G_PARAM_READWRITE |
902 G_PARAM_STATIC_STRINGS));
904 g_object_class_install_property (gobject_class, PROP_TYPE,
905 g_param_spec_enum ("type",
906 P_("Socket type"),
907 P_("The sockets type"),
908 G_TYPE_SOCKET_TYPE,
909 G_SOCKET_TYPE_STREAM,
910 G_PARAM_CONSTRUCT_ONLY |
911 G_PARAM_READWRITE |
912 G_PARAM_STATIC_STRINGS));
914 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
915 g_param_spec_enum ("protocol",
916 P_("Socket protocol"),
917 P_("The id of the protocol to use, or -1 for unknown"),
918 G_TYPE_SOCKET_PROTOCOL,
919 G_SOCKET_PROTOCOL_UNKNOWN,
920 G_PARAM_CONSTRUCT_ONLY |
921 G_PARAM_READWRITE |
922 G_PARAM_STATIC_STRINGS));
924 g_object_class_install_property (gobject_class, PROP_FD,
925 g_param_spec_int ("fd",
926 P_("File descriptor"),
927 P_("The sockets file descriptor"),
928 G_MININT,
929 G_MAXINT,
931 G_PARAM_CONSTRUCT_ONLY |
932 G_PARAM_READWRITE |
933 G_PARAM_STATIC_STRINGS));
935 g_object_class_install_property (gobject_class, PROP_BLOCKING,
936 g_param_spec_boolean ("blocking",
937 P_("blocking"),
938 P_("Whether or not I/O on this socket is blocking"),
939 TRUE,
940 G_PARAM_READWRITE |
941 G_PARAM_STATIC_STRINGS));
943 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
944 g_param_spec_int ("listen-backlog",
945 P_("Listen backlog"),
946 P_("Outstanding connections in the listen queue"),
948 SOMAXCONN,
950 G_PARAM_READWRITE |
951 G_PARAM_STATIC_STRINGS));
953 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
954 g_param_spec_boolean ("keepalive",
955 P_("Keep connection alive"),
956 P_("Keep connection alive by sending periodic pings"),
957 FALSE,
958 G_PARAM_READWRITE |
959 G_PARAM_STATIC_STRINGS));
961 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
962 g_param_spec_object ("local-address",
963 P_("Local address"),
964 P_("The local address the socket is bound to"),
965 G_TYPE_SOCKET_ADDRESS,
966 G_PARAM_READABLE |
967 G_PARAM_STATIC_STRINGS));
969 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
970 g_param_spec_object ("remote-address",
971 P_("Remote address"),
972 P_("The remote address the socket is connected to"),
973 G_TYPE_SOCKET_ADDRESS,
974 G_PARAM_READABLE |
975 G_PARAM_STATIC_STRINGS));
978 * GSocket:timeout:
980 * The timeout in seconds on socket I/O
982 * Since: 2.26
984 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
985 g_param_spec_uint ("timeout",
986 P_("Timeout"),
987 P_("The timeout in seconds on socket I/O"),
989 G_MAXUINT,
991 G_PARAM_READWRITE |
992 G_PARAM_STATIC_STRINGS));
995 * GSocket:broadcast:
997 * Whether the socket should allow sending to broadcast addresses.
999 * Since: 2.32
1001 g_object_class_install_property (gobject_class, PROP_BROADCAST,
1002 g_param_spec_boolean ("broadcast",
1003 P_("Broadcast"),
1004 P_("Whether to allow sending to broadcast addresses"),
1005 FALSE,
1006 G_PARAM_READWRITE |
1007 G_PARAM_STATIC_STRINGS));
1010 * GSocket:ttl:
1012 * Time-to-live for outgoing unicast packets
1014 * Since: 2.32
1016 g_object_class_install_property (gobject_class, PROP_TTL,
1017 g_param_spec_uint ("ttl",
1018 P_("TTL"),
1019 P_("Time-to-live of outgoing unicast packets"),
1020 0, G_MAXUINT, 0,
1021 G_PARAM_READWRITE |
1022 G_PARAM_STATIC_STRINGS));
1025 * GSocket:multicast-loopback:
1027 * Whether outgoing multicast packets loop back to the local host.
1029 * Since: 2.32
1031 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
1032 g_param_spec_boolean ("multicast-loopback",
1033 P_("Multicast loopback"),
1034 P_("Whether outgoing multicast packets loop back to the local host"),
1035 TRUE,
1036 G_PARAM_READWRITE |
1037 G_PARAM_STATIC_STRINGS));
1040 * GSocket:multicast-ttl:
1042 * Time-to-live out outgoing multicast packets
1044 * Since: 2.32
1046 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
1047 g_param_spec_uint ("multicast-ttl",
1048 P_("Multicast TTL"),
1049 P_("Time-to-live of outgoing multicast packets"),
1050 0, G_MAXUINT, 1,
1051 G_PARAM_READWRITE |
1052 G_PARAM_STATIC_STRINGS));
1055 static void
1056 g_socket_initable_iface_init (GInitableIface *iface)
1058 iface->init = g_socket_initable_init;
1061 static void
1062 g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface)
1064 iface->receive_messages = g_socket_datagram_based_receive_messages;
1065 iface->send_messages = g_socket_datagram_based_send_messages;
1066 iface->create_source = g_socket_datagram_based_create_source;
1067 iface->condition_check = g_socket_datagram_based_condition_check;
1068 iface->condition_wait = g_socket_datagram_based_condition_wait;
1071 static void
1072 g_socket_init (GSocket *socket)
1074 socket->priv = g_socket_get_instance_private (socket);
1076 socket->priv->fd = -1;
1077 socket->priv->blocking = TRUE;
1078 socket->priv->listen_backlog = 10;
1079 socket->priv->construct_error = NULL;
1080 #ifdef G_OS_WIN32
1081 socket->priv->event = WSA_INVALID_EVENT;
1082 g_mutex_init (&socket->priv->win32_source_lock);
1083 g_cond_init (&socket->priv->win32_source_cond);
1084 #endif
1087 static gboolean
1088 g_socket_initable_init (GInitable *initable,
1089 GCancellable *cancellable,
1090 GError **error)
1092 GSocket *socket;
1094 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
1096 socket = G_SOCKET (initable);
1098 if (cancellable != NULL)
1100 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1101 _("Cancellable initialization not supported"));
1102 return FALSE;
1105 socket->priv->inited = TRUE;
1107 if (socket->priv->construct_error)
1109 if (error)
1110 *error = g_error_copy (socket->priv->construct_error);
1111 return FALSE;
1115 return TRUE;
1118 static gboolean
1119 check_datagram_based (GDatagramBased *self,
1120 GError **error)
1122 switch (g_socket_get_socket_type (G_SOCKET (self)))
1124 case G_SOCKET_TYPE_INVALID:
1125 case G_SOCKET_TYPE_STREAM:
1126 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1127 _("Cannot use datagram operations on a non-datagram "
1128 "socket."));
1129 return FALSE;
1130 case G_SOCKET_TYPE_DATAGRAM:
1131 case G_SOCKET_TYPE_SEQPACKET:
1132 /* Fall through. */
1133 break;
1136 /* Due to us sharing #GSocketSource with the #GSocket implementation, it is
1137 * pretty tricky to split out #GSocket:timeout so that it does not affect
1138 * #GDatagramBased operations (but still affects #GSocket operations). It is
1139 * not worth that effort — just disallow it and require the user to specify
1140 * timeouts on a per-operation basis. */
1141 if (g_socket_get_timeout (G_SOCKET (self)) != 0)
1143 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1144 _("Cannot use datagram operations on a socket with a "
1145 "timeout set."));
1146 return FALSE;
1149 return TRUE;
1152 static gint
1153 g_socket_datagram_based_receive_messages (GDatagramBased *self,
1154 GInputMessage *messages,
1155 guint num_messages,
1156 gint flags,
1157 gint64 timeout,
1158 GCancellable *cancellable,
1159 GError **error)
1161 if (!check_datagram_based (self, error))
1162 return FALSE;
1164 return g_socket_receive_messages_with_timeout (G_SOCKET (self), messages,
1165 num_messages, flags, timeout,
1166 cancellable, error);
1169 static gint
1170 g_socket_datagram_based_send_messages (GDatagramBased *self,
1171 GOutputMessage *messages,
1172 guint num_messages,
1173 gint flags,
1174 gint64 timeout,
1175 GCancellable *cancellable,
1176 GError **error)
1178 if (!check_datagram_based (self, error))
1179 return FALSE;
1181 return g_socket_send_messages_with_timeout (G_SOCKET (self), messages,
1182 num_messages, flags, timeout,
1183 cancellable, error);
1186 static GSource *
1187 g_socket_datagram_based_create_source (GDatagramBased *self,
1188 GIOCondition condition,
1189 GCancellable *cancellable)
1191 if (!check_datagram_based (self, NULL))
1192 return NULL;
1194 return g_socket_create_source (G_SOCKET (self), condition, cancellable);
1197 static GIOCondition
1198 g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
1199 GIOCondition condition)
1201 if (!check_datagram_based (datagram_based, NULL))
1202 return G_IO_ERR;
1204 return g_socket_condition_check (G_SOCKET (datagram_based), condition);
1207 static gboolean
1208 g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
1209 GIOCondition condition,
1210 gint64 timeout,
1211 GCancellable *cancellable,
1212 GError **error)
1214 if (!check_datagram_based (datagram_based, error))
1215 return FALSE;
1217 return g_socket_condition_timed_wait (G_SOCKET (datagram_based), condition,
1218 timeout, cancellable, error);
1222 * g_socket_new:
1223 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1224 * @type: the socket type to use.
1225 * @protocol: the id of the protocol to use, or 0 for default.
1226 * @error: #GError for error reporting, or %NULL to ignore.
1228 * Creates a new #GSocket with the defined family, type and protocol.
1229 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1230 * for the family and type is used.
1232 * The @protocol is a family and type specific int that specifies what
1233 * kind of protocol to use. #GSocketProtocol lists several common ones.
1234 * Many families only support one protocol, and use 0 for this, others
1235 * support several and using 0 means to use the default protocol for
1236 * the family and type.
1238 * The protocol id is passed directly to the operating
1239 * system, so you can use protocols not listed in #GSocketProtocol if you
1240 * know the protocol number used for it.
1242 * Returns: a #GSocket or %NULL on error.
1243 * Free the returned object with g_object_unref().
1245 * Since: 2.22
1247 GSocket *
1248 g_socket_new (GSocketFamily family,
1249 GSocketType type,
1250 GSocketProtocol protocol,
1251 GError **error)
1253 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1254 NULL, error,
1255 "family", family,
1256 "type", type,
1257 "protocol", protocol,
1258 NULL));
1262 * g_socket_new_from_fd:
1263 * @fd: a native socket file descriptor.
1264 * @error: #GError for error reporting, or %NULL to ignore.
1266 * Creates a new #GSocket from a native file descriptor
1267 * or winsock SOCKET handle.
1269 * This reads all the settings from the file descriptor so that
1270 * all properties should work. Note that the file descriptor
1271 * will be set to non-blocking mode, independent on the blocking
1272 * mode of the #GSocket.
1274 * On success, the returned #GSocket takes ownership of @fd. On failure, the
1275 * caller must close @fd themselves.
1277 * Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
1278 * descriptor. Instead, a GError will be set with code %G_IO_ERROR_FAILED
1280 * Returns: a #GSocket or %NULL on error.
1281 * Free the returned object with g_object_unref().
1283 * Since: 2.22
1285 GSocket *
1286 g_socket_new_from_fd (gint fd,
1287 GError **error)
1289 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1290 NULL, error,
1291 "fd", fd,
1292 NULL));
1296 * g_socket_set_blocking:
1297 * @socket: a #GSocket.
1298 * @blocking: Whether to use blocking I/O or not.
1300 * Sets the blocking mode of the socket. In blocking mode
1301 * all operations (which don’t take an explicit blocking parameter) block until
1302 * they succeed or there is an error. In
1303 * non-blocking mode all functions return results immediately or
1304 * with a %G_IO_ERROR_WOULD_BLOCK error.
1306 * All sockets are created in blocking mode. However, note that the
1307 * platform level socket is always non-blocking, and blocking mode
1308 * is a GSocket level feature.
1310 * Since: 2.22
1312 void
1313 g_socket_set_blocking (GSocket *socket,
1314 gboolean blocking)
1316 g_return_if_fail (G_IS_SOCKET (socket));
1318 blocking = !!blocking;
1320 if (socket->priv->blocking == blocking)
1321 return;
1323 socket->priv->blocking = blocking;
1324 g_object_notify (G_OBJECT (socket), "blocking");
1328 * g_socket_get_blocking:
1329 * @socket: a #GSocket.
1331 * Gets the blocking mode of the socket. For details on blocking I/O,
1332 * see g_socket_set_blocking().
1334 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1336 * Since: 2.22
1338 gboolean
1339 g_socket_get_blocking (GSocket *socket)
1341 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1343 return socket->priv->blocking;
1347 * g_socket_set_keepalive:
1348 * @socket: a #GSocket.
1349 * @keepalive: Value for the keepalive flag
1351 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1352 * this flag is set on a socket, the system will attempt to verify that the
1353 * remote socket endpoint is still present if a sufficiently long period of
1354 * time passes with no data being exchanged. If the system is unable to
1355 * verify the presence of the remote endpoint, it will automatically close
1356 * the connection.
1358 * This option is only functional on certain kinds of sockets. (Notably,
1359 * %G_SOCKET_PROTOCOL_TCP sockets.)
1361 * The exact time between pings is system- and protocol-dependent, but will
1362 * normally be at least two hours. Most commonly, you would set this flag
1363 * on a server socket if you want to allow clients to remain idle for long
1364 * periods of time, but also want to ensure that connections are eventually
1365 * garbage-collected if clients crash or become unreachable.
1367 * Since: 2.22
1369 void
1370 g_socket_set_keepalive (GSocket *socket,
1371 gboolean keepalive)
1373 GError *error = NULL;
1375 g_return_if_fail (G_IS_SOCKET (socket));
1377 keepalive = !!keepalive;
1378 if (socket->priv->keepalive == keepalive)
1379 return;
1381 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1382 keepalive, &error))
1384 g_warning ("error setting keepalive: %s", error->message);
1385 g_error_free (error);
1386 return;
1389 socket->priv->keepalive = keepalive;
1390 g_object_notify (G_OBJECT (socket), "keepalive");
1394 * g_socket_get_keepalive:
1395 * @socket: a #GSocket.
1397 * Gets the keepalive mode of the socket. For details on this,
1398 * see g_socket_set_keepalive().
1400 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1402 * Since: 2.22
1404 gboolean
1405 g_socket_get_keepalive (GSocket *socket)
1407 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1409 return socket->priv->keepalive;
1413 * g_socket_get_listen_backlog:
1414 * @socket: a #GSocket.
1416 * Gets the listen backlog setting of the socket. For details on this,
1417 * see g_socket_set_listen_backlog().
1419 * Returns: the maximum number of pending connections.
1421 * Since: 2.22
1423 gint
1424 g_socket_get_listen_backlog (GSocket *socket)
1426 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1428 return socket->priv->listen_backlog;
1432 * g_socket_set_listen_backlog:
1433 * @socket: a #GSocket.
1434 * @backlog: the maximum number of pending connections.
1436 * Sets the maximum number of outstanding connections allowed
1437 * when listening on this socket. If more clients than this are
1438 * connecting to the socket and the application is not handling them
1439 * on time then the new connections will be refused.
1441 * Note that this must be called before g_socket_listen() and has no
1442 * effect if called after that.
1444 * Since: 2.22
1446 void
1447 g_socket_set_listen_backlog (GSocket *socket,
1448 gint backlog)
1450 g_return_if_fail (G_IS_SOCKET (socket));
1451 g_return_if_fail (!socket->priv->listening);
1453 if (backlog != socket->priv->listen_backlog)
1455 socket->priv->listen_backlog = backlog;
1456 g_object_notify (G_OBJECT (socket), "listen-backlog");
1461 * g_socket_get_timeout:
1462 * @socket: a #GSocket.
1464 * Gets the timeout setting of the socket. For details on this, see
1465 * g_socket_set_timeout().
1467 * Returns: the timeout in seconds
1469 * Since: 2.26
1471 guint
1472 g_socket_get_timeout (GSocket *socket)
1474 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1476 return socket->priv->timeout;
1480 * g_socket_set_timeout:
1481 * @socket: a #GSocket.
1482 * @timeout: the timeout for @socket, in seconds, or 0 for none
1484 * Sets the time in seconds after which I/O operations on @socket will
1485 * time out if they have not yet completed.
1487 * On a blocking socket, this means that any blocking #GSocket
1488 * operation will time out after @timeout seconds of inactivity,
1489 * returning %G_IO_ERROR_TIMED_OUT.
1491 * On a non-blocking socket, calls to g_socket_condition_wait() will
1492 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1493 * created with g_socket_create_source() will trigger after
1494 * @timeout seconds of inactivity, with the requested condition
1495 * set, at which point calling g_socket_receive(), g_socket_send(),
1496 * g_socket_check_connect_result(), etc, will fail with
1497 * %G_IO_ERROR_TIMED_OUT.
1499 * If @timeout is 0 (the default), operations will never time out
1500 * on their own.
1502 * Note that if an I/O operation is interrupted by a signal, this may
1503 * cause the timeout to be reset.
1505 * Since: 2.26
1507 void
1508 g_socket_set_timeout (GSocket *socket,
1509 guint timeout)
1511 g_return_if_fail (G_IS_SOCKET (socket));
1513 if (timeout != socket->priv->timeout)
1515 socket->priv->timeout = timeout;
1516 g_object_notify (G_OBJECT (socket), "timeout");
1521 * g_socket_get_ttl:
1522 * @socket: a #GSocket.
1524 * Gets the unicast time-to-live setting on @socket; see
1525 * g_socket_set_ttl() for more details.
1527 * Returns: the time-to-live setting on @socket
1529 * Since: 2.32
1531 guint
1532 g_socket_get_ttl (GSocket *socket)
1534 GError *error = NULL;
1535 gint value;
1537 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1539 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1541 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1542 &value, &error);
1544 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1546 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1547 &value, &error);
1549 else
1550 g_return_val_if_reached (0);
1552 if (error)
1554 g_warning ("error getting unicast ttl: %s", error->message);
1555 g_error_free (error);
1556 return 0;
1559 return value;
1563 * g_socket_set_ttl:
1564 * @socket: a #GSocket.
1565 * @ttl: the time-to-live value for all unicast packets on @socket
1567 * Sets the time-to-live for outgoing unicast packets on @socket.
1568 * By default the platform-specific default value is used.
1570 * Since: 2.32
1572 void
1573 g_socket_set_ttl (GSocket *socket,
1574 guint ttl)
1576 GError *error = NULL;
1578 g_return_if_fail (G_IS_SOCKET (socket));
1580 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1582 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1583 ttl, &error);
1585 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1587 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1588 ttl, NULL);
1589 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1590 ttl, &error);
1592 else
1593 g_return_if_reached ();
1595 if (error)
1597 g_warning ("error setting unicast ttl: %s", error->message);
1598 g_error_free (error);
1599 return;
1602 g_object_notify (G_OBJECT (socket), "ttl");
1606 * g_socket_get_broadcast:
1607 * @socket: a #GSocket.
1609 * Gets the broadcast setting on @socket; if %TRUE,
1610 * it is possible to send packets to broadcast
1611 * addresses.
1613 * Returns: the broadcast setting on @socket
1615 * Since: 2.32
1617 gboolean
1618 g_socket_get_broadcast (GSocket *socket)
1620 GError *error = NULL;
1621 gint value;
1623 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1625 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1626 &value, &error))
1628 g_warning ("error getting broadcast: %s", error->message);
1629 g_error_free (error);
1630 return FALSE;
1633 return !!value;
1637 * g_socket_set_broadcast:
1638 * @socket: a #GSocket.
1639 * @broadcast: whether @socket should allow sending to broadcast
1640 * addresses
1642 * Sets whether @socket should allow sending to broadcast addresses.
1643 * This is %FALSE by default.
1645 * Since: 2.32
1647 void
1648 g_socket_set_broadcast (GSocket *socket,
1649 gboolean broadcast)
1651 GError *error = NULL;
1653 g_return_if_fail (G_IS_SOCKET (socket));
1655 broadcast = !!broadcast;
1657 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1658 broadcast, &error))
1660 g_warning ("error setting broadcast: %s", error->message);
1661 g_error_free (error);
1662 return;
1665 g_object_notify (G_OBJECT (socket), "broadcast");
1669 * g_socket_get_multicast_loopback:
1670 * @socket: a #GSocket.
1672 * Gets the multicast loopback setting on @socket; if %TRUE (the
1673 * default), outgoing multicast packets will be looped back to
1674 * multicast listeners on the same host.
1676 * Returns: the multicast loopback setting on @socket
1678 * Since: 2.32
1680 gboolean
1681 g_socket_get_multicast_loopback (GSocket *socket)
1683 GError *error = NULL;
1684 gint value;
1686 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1688 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1690 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1691 &value, &error);
1693 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1695 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1696 &value, &error);
1698 else
1699 g_return_val_if_reached (FALSE);
1701 if (error)
1703 g_warning ("error getting multicast loopback: %s", error->message);
1704 g_error_free (error);
1705 return FALSE;
1708 return !!value;
1712 * g_socket_set_multicast_loopback:
1713 * @socket: a #GSocket.
1714 * @loopback: whether @socket should receive messages sent to its
1715 * multicast groups from the local host
1717 * Sets whether outgoing multicast packets will be received by sockets
1718 * listening on that multicast address on the same host. This is %TRUE
1719 * by default.
1721 * Since: 2.32
1723 void
1724 g_socket_set_multicast_loopback (GSocket *socket,
1725 gboolean loopback)
1727 GError *error = NULL;
1729 g_return_if_fail (G_IS_SOCKET (socket));
1731 loopback = !!loopback;
1733 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1735 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1736 loopback, &error);
1738 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1740 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1741 loopback, NULL);
1742 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1743 loopback, &error);
1745 else
1746 g_return_if_reached ();
1748 if (error)
1750 g_warning ("error setting multicast loopback: %s", error->message);
1751 g_error_free (error);
1752 return;
1755 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1759 * g_socket_get_multicast_ttl:
1760 * @socket: a #GSocket.
1762 * Gets the multicast time-to-live setting on @socket; see
1763 * g_socket_set_multicast_ttl() for more details.
1765 * Returns: the multicast time-to-live setting on @socket
1767 * Since: 2.32
1769 guint
1770 g_socket_get_multicast_ttl (GSocket *socket)
1772 GError *error = NULL;
1773 gint value;
1775 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1777 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1779 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1780 &value, &error);
1782 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1784 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1785 &value, &error);
1787 else
1788 g_return_val_if_reached (FALSE);
1790 if (error)
1792 g_warning ("error getting multicast ttl: %s", error->message);
1793 g_error_free (error);
1794 return FALSE;
1797 return value;
1801 * g_socket_set_multicast_ttl:
1802 * @socket: a #GSocket.
1803 * @ttl: the time-to-live value for all multicast datagrams on @socket
1805 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1806 * By default, this is 1, meaning that multicast packets will not leave
1807 * the local network.
1809 * Since: 2.32
1811 void
1812 g_socket_set_multicast_ttl (GSocket *socket,
1813 guint ttl)
1815 GError *error = NULL;
1817 g_return_if_fail (G_IS_SOCKET (socket));
1819 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1821 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1822 ttl, &error);
1824 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1826 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1827 ttl, NULL);
1828 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1829 ttl, &error);
1831 else
1832 g_return_if_reached ();
1834 if (error)
1836 g_warning ("error setting multicast ttl: %s", error->message);
1837 g_error_free (error);
1838 return;
1841 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1845 * g_socket_get_family:
1846 * @socket: a #GSocket.
1848 * Gets the socket family of the socket.
1850 * Returns: a #GSocketFamily
1852 * Since: 2.22
1854 GSocketFamily
1855 g_socket_get_family (GSocket *socket)
1857 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1859 return socket->priv->family;
1863 * g_socket_get_socket_type:
1864 * @socket: a #GSocket.
1866 * Gets the socket type of the socket.
1868 * Returns: a #GSocketType
1870 * Since: 2.22
1872 GSocketType
1873 g_socket_get_socket_type (GSocket *socket)
1875 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1877 return socket->priv->type;
1881 * g_socket_get_protocol:
1882 * @socket: a #GSocket.
1884 * Gets the socket protocol id the socket was created with.
1885 * In case the protocol is unknown, -1 is returned.
1887 * Returns: a protocol id, or -1 if unknown
1889 * Since: 2.22
1891 GSocketProtocol
1892 g_socket_get_protocol (GSocket *socket)
1894 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1896 return socket->priv->protocol;
1900 * g_socket_get_fd:
1901 * @socket: a #GSocket.
1903 * Returns the underlying OS socket object. On unix this
1904 * is a socket file descriptor, and on Windows this is
1905 * a Winsock2 SOCKET handle. This may be useful for
1906 * doing platform specific or otherwise unusual operations
1907 * on the socket.
1909 * Returns: the file descriptor of the socket.
1911 * Since: 2.22
1914 g_socket_get_fd (GSocket *socket)
1916 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1918 return socket->priv->fd;
1922 * g_socket_get_local_address:
1923 * @socket: a #GSocket.
1924 * @error: #GError for error reporting, or %NULL to ignore.
1926 * Try to get the local address of a bound socket. This is only
1927 * useful if the socket has been bound to a local address,
1928 * either explicitly or implicitly when connecting.
1930 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1931 * Free the returned object with g_object_unref().
1933 * Since: 2.22
1935 GSocketAddress *
1936 g_socket_get_local_address (GSocket *socket,
1937 GError **error)
1939 struct sockaddr_storage buffer;
1940 guint len = sizeof (buffer);
1942 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1944 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1946 int errsv = get_socket_errno ();
1947 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1948 _("could not get local address: %s"), socket_strerror (errsv));
1949 return NULL;
1952 return g_socket_address_new_from_native (&buffer, len);
1956 * g_socket_get_remote_address:
1957 * @socket: a #GSocket.
1958 * @error: #GError for error reporting, or %NULL to ignore.
1960 * Try to get the remote address of a connected socket. This is only
1961 * useful for connection oriented sockets that have been connected.
1963 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1964 * Free the returned object with g_object_unref().
1966 * Since: 2.22
1968 GSocketAddress *
1969 g_socket_get_remote_address (GSocket *socket,
1970 GError **error)
1972 struct sockaddr_storage buffer;
1973 guint len = sizeof (buffer);
1975 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1977 if (socket->priv->connect_pending)
1979 if (!g_socket_check_connect_result (socket, error))
1980 return NULL;
1981 else
1982 socket->priv->connect_pending = FALSE;
1985 if (!socket->priv->remote_address)
1987 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1989 int errsv = get_socket_errno ();
1990 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1991 _("could not get remote address: %s"), socket_strerror (errsv));
1992 return NULL;
1995 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1998 return g_object_ref (socket->priv->remote_address);
2002 * g_socket_is_connected:
2003 * @socket: a #GSocket.
2005 * Check whether the socket is connected. This is only useful for
2006 * connection-oriented sockets.
2008 * If using g_socket_shutdown(), this function will return %TRUE until the
2009 * socket has been shut down for reading and writing. If you do a non-blocking
2010 * connect, this function will not return %TRUE until after you call
2011 * g_socket_check_connect_result().
2013 * Returns: %TRUE if socket is connected, %FALSE otherwise.
2015 * Since: 2.22
2017 gboolean
2018 g_socket_is_connected (GSocket *socket)
2020 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2022 return (socket->priv->connected_read || socket->priv->connected_write);
2026 * g_socket_listen:
2027 * @socket: a #GSocket.
2028 * @error: #GError for error reporting, or %NULL to ignore.
2030 * Marks the socket as a server socket, i.e. a socket that is used
2031 * to accept incoming requests using g_socket_accept().
2033 * Before calling this the socket must be bound to a local address using
2034 * g_socket_bind().
2036 * To set the maximum amount of outstanding clients, use
2037 * g_socket_set_listen_backlog().
2039 * Returns: %TRUE on success, %FALSE on error.
2041 * Since: 2.22
2043 gboolean
2044 g_socket_listen (GSocket *socket,
2045 GError **error)
2047 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2049 if (!check_socket (socket, error))
2050 return FALSE;
2052 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
2054 int errsv = get_socket_errno ();
2056 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2057 _("could not listen: %s"), socket_strerror (errsv));
2058 return FALSE;
2061 socket->priv->listening = TRUE;
2063 return TRUE;
2067 * g_socket_bind:
2068 * @socket: a #GSocket.
2069 * @address: a #GSocketAddress specifying the local address.
2070 * @allow_reuse: whether to allow reusing this address
2071 * @error: #GError for error reporting, or %NULL to ignore.
2073 * When a socket is created it is attached to an address family, but it
2074 * doesn't have an address in this family. g_socket_bind() assigns the
2075 * address (sometimes called name) of the socket.
2077 * It is generally required to bind to a local address before you can
2078 * receive connections. (See g_socket_listen() and g_socket_accept() ).
2079 * In certain situations, you may also want to bind a socket that will be
2080 * used to initiate connections, though this is not normally required.
2082 * If @socket is a TCP socket, then @allow_reuse controls the setting
2083 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
2084 * server sockets (sockets that you will eventually call
2085 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
2086 * set this flag on a server socket may cause g_socket_bind() to return
2087 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
2088 * immediately restarted.)
2090 * If @socket is a UDP socket, then @allow_reuse determines whether or
2091 * not other UDP sockets can be bound to the same address at the same
2092 * time. In particular, you can have several UDP sockets bound to the
2093 * same address, and they will all receive all of the multicast and
2094 * broadcast packets sent to that address. (The behavior of unicast
2095 * UDP packets to an address with multiple listeners is not defined.)
2097 * Returns: %TRUE on success, %FALSE on error.
2099 * Since: 2.22
2101 gboolean
2102 g_socket_bind (GSocket *socket,
2103 GSocketAddress *address,
2104 gboolean reuse_address,
2105 GError **error)
2107 struct sockaddr_storage addr;
2108 gboolean so_reuseaddr;
2109 #ifdef SO_REUSEPORT
2110 gboolean so_reuseport;
2111 #endif
2113 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2115 if (!check_socket (socket, error))
2116 return FALSE;
2118 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2119 return FALSE;
2121 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
2122 * sockets, but has nasty side effects we don't want for TCP
2123 * sockets.
2125 * On other platforms, we set SO_REUSEPORT, if it exists, for
2126 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
2127 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
2128 * the desired semantics on UDP (as it does on Linux, although
2129 * Linux has SO_REUSEPORT too as of 3.9).
2132 #ifdef G_OS_WIN32
2133 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2134 #else
2135 so_reuseaddr = !!reuse_address;
2136 #endif
2138 #ifdef SO_REUSEPORT
2139 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2140 #endif
2142 /* Ignore errors here, the only likely error is "not supported", and
2143 * this is a "best effort" thing mainly.
2145 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
2146 #ifdef SO_REUSEPORT
2147 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
2148 #endif
2150 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
2151 g_socket_address_get_native_size (address)) < 0)
2153 int errsv = get_socket_errno ();
2154 g_set_error (error,
2155 G_IO_ERROR, socket_io_error_from_errno (errsv),
2156 _("Error binding to address: %s"), socket_strerror (errsv));
2157 return FALSE;
2160 return TRUE;
2163 static gboolean
2164 g_socket_multicast_group_operation (GSocket *socket,
2165 GInetAddress *group,
2166 gboolean source_specific,
2167 const gchar *iface,
2168 gboolean join_group,
2169 GError **error)
2171 const guint8 *native_addr;
2172 gint optname, result;
2174 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2175 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2176 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2178 if (!check_socket (socket, error))
2179 return FALSE;
2181 native_addr = g_inet_address_to_bytes (group);
2182 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2184 #ifdef HAVE_IP_MREQN
2185 struct ip_mreqn mc_req;
2186 #else
2187 struct ip_mreq mc_req;
2188 #endif
2190 memset (&mc_req, 0, sizeof (mc_req));
2191 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2193 #ifdef HAVE_IP_MREQN
2194 if (iface)
2195 mc_req.imr_ifindex = if_nametoindex (iface);
2196 else
2197 mc_req.imr_ifindex = 0; /* Pick any. */
2198 #elif defined(G_OS_WIN32)
2199 if (iface)
2200 mc_req.imr_interface.s_addr = g_htonl (if_nametoindex (iface));
2201 else
2202 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2203 #else
2204 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2205 #endif
2207 if (source_specific)
2209 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2210 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2211 #else
2212 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2213 join_group ?
2214 _("Error joining multicast group: %s") :
2215 _("Error leaving multicast group: %s"),
2216 _("No support for source-specific multicast"));
2217 return FALSE;
2218 #endif
2220 else
2221 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2222 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2223 &mc_req, sizeof (mc_req));
2225 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2227 struct ipv6_mreq mc_req_ipv6;
2229 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2230 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2231 #ifdef HAVE_IF_NAMETOINDEX
2232 if (iface)
2233 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2234 else
2235 #endif
2236 mc_req_ipv6.ipv6mr_interface = 0;
2238 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2239 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2240 &mc_req_ipv6, sizeof (mc_req_ipv6));
2242 else
2243 g_return_val_if_reached (FALSE);
2245 if (result < 0)
2247 int errsv = get_socket_errno ();
2249 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2250 join_group ?
2251 _("Error joining multicast group: %s") :
2252 _("Error leaving multicast group: %s"),
2253 socket_strerror (errsv));
2254 return FALSE;
2257 return TRUE;
2261 * g_socket_join_multicast_group:
2262 * @socket: a #GSocket.
2263 * @group: a #GInetAddress specifying the group address to join.
2264 * @iface: (nullable): Name of the interface to use, or %NULL
2265 * @source_specific: %TRUE if source-specific multicast should be used
2266 * @error: #GError for error reporting, or %NULL to ignore.
2268 * Registers @socket to receive multicast messages sent to @group.
2269 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2270 * been bound to an appropriate interface and port with
2271 * g_socket_bind().
2273 * If @iface is %NULL, the system will automatically pick an interface
2274 * to bind to based on @group.
2276 * If @source_specific is %TRUE, source-specific multicast as defined
2277 * in RFC 4604 is used. Note that on older platforms this may fail
2278 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2280 * To bind to a given source-specific multicast address, use
2281 * g_socket_join_multicast_group_ssm() instead.
2283 * Returns: %TRUE on success, %FALSE on error.
2285 * Since: 2.32
2287 gboolean
2288 g_socket_join_multicast_group (GSocket *socket,
2289 GInetAddress *group,
2290 gboolean source_specific,
2291 const gchar *iface,
2292 GError **error)
2294 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2298 * g_socket_leave_multicast_group:
2299 * @socket: a #GSocket.
2300 * @group: a #GInetAddress specifying the group address to leave.
2301 * @iface: (nullable): Interface used
2302 * @source_specific: %TRUE if source-specific multicast was used
2303 * @error: #GError for error reporting, or %NULL to ignore.
2305 * Removes @socket from the multicast group defined by @group, @iface,
2306 * and @source_specific (which must all have the same values they had
2307 * when you joined the group).
2309 * @socket remains bound to its address and port, and can still receive
2310 * unicast messages after calling this.
2312 * To unbind to a given source-specific multicast address, use
2313 * g_socket_leave_multicast_group_ssm() instead.
2315 * Returns: %TRUE on success, %FALSE on error.
2317 * Since: 2.32
2319 gboolean
2320 g_socket_leave_multicast_group (GSocket *socket,
2321 GInetAddress *group,
2322 gboolean source_specific,
2323 const gchar *iface,
2324 GError **error)
2326 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2329 static gboolean
2330 g_socket_multicast_group_operation_ssm (GSocket *socket,
2331 GInetAddress *group,
2332 GInetAddress *source_specific,
2333 const gchar *iface,
2334 gboolean join_group,
2335 GError **error)
2337 gint result;
2339 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2340 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2341 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2342 g_return_val_if_fail (iface == NULL || *iface != '\0', FALSE);
2343 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2345 if (!source_specific)
2347 return g_socket_multicast_group_operation (socket, group, FALSE, iface,
2348 join_group, error);
2351 if (!check_socket (socket, error))
2352 return FALSE;
2354 switch (g_inet_address_get_family (group))
2356 case G_SOCKET_FAMILY_INVALID:
2357 case G_SOCKET_FAMILY_UNIX:
2359 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2360 join_group ?
2361 _("Error joining multicast group: %s") :
2362 _("Error leaving multicast group: %s"),
2363 _("Unsupported socket family"));
2364 return FALSE;
2366 break;
2368 case G_SOCKET_FAMILY_IPV4:
2370 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2371 gint optname;
2372 struct ip_mreq_source mc_req_src;
2374 if (g_inet_address_get_family (source_specific) !=
2375 G_SOCKET_FAMILY_IPV4)
2377 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2378 join_group ?
2379 _("Error joining multicast group: %s") :
2380 _("Error leaving multicast group: %s"),
2381 _("source-specific not an IPv4 address"));
2382 return FALSE;
2385 memset (&mc_req_src, 0, sizeof (mc_req_src));
2387 /* By default use the default IPv4 multicast interface. */
2388 mc_req_src.imr_interface.s_addr = g_htonl (INADDR_ANY);
2390 if (iface)
2392 #if defined(G_OS_WIN32) && defined (HAVE_IF_NAMETOINDEX)
2393 guint iface_index = if_nametoindex (iface);
2394 if (iface_index == 0)
2396 int errsv = errno;
2398 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2399 _("Interface not found: %s"), g_strerror (errsv));
2400 return FALSE;
2402 /* (0.0.0.iface_index) only works on Windows. */
2403 mc_req_src.imr_interface.s_addr = g_htonl (iface_index);
2404 #elif defined (HAVE_SIOCGIFADDR)
2405 int ret;
2406 struct ifreq ifr;
2407 struct sockaddr_in *iface_addr;
2408 size_t if_name_len = strlen (iface);
2410 memset (&ifr, 0, sizeof (ifr));
2412 if (if_name_len >= sizeof (ifr.ifr_name))
2414 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FILENAME_TOO_LONG,
2415 _("Interface name too long"));
2416 return FALSE;
2419 memcpy (ifr.ifr_name, iface, if_name_len);
2421 /* Get the IPv4 address of the given network interface name. */
2422 ret = ioctl (socket->priv->fd, SIOCGIFADDR, &ifr);
2423 if (ret < 0)
2425 int errsv = errno;
2427 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2428 _("Interface not found: %s"), g_strerror (errsv));
2429 return FALSE;
2432 iface_addr = (struct sockaddr_in *) &ifr.ifr_addr;
2433 mc_req_src.imr_interface.s_addr = iface_addr->sin_addr.s_addr;
2434 #endif /* defined(G_OS_WIN32) && defined (HAVE_IF_NAMETOINDEX) */
2436 memcpy (&mc_req_src.imr_multiaddr, g_inet_address_to_bytes (group),
2437 g_inet_address_get_native_size (group));
2438 memcpy (&mc_req_src.imr_sourceaddr,
2439 g_inet_address_to_bytes (source_specific),
2440 g_inet_address_get_native_size (source_specific));
2442 optname =
2443 join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2444 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2445 &mc_req_src, sizeof (mc_req_src));
2446 #else
2447 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2448 join_group ?
2449 _("Error joining multicast group: %s") :
2450 _("Error leaving multicast group: %s"),
2451 _("No support for IPv4 source-specific multicast"));
2452 return FALSE;
2453 #endif /* IP_ADD_SOURCE_MEMBERSHIP */
2455 break;
2457 case G_SOCKET_FAMILY_IPV6:
2459 #ifdef MCAST_JOIN_SOURCE_GROUP
2460 gboolean res;
2461 gint optname;
2462 struct group_source_req mc_req_src;
2463 GSocketAddress *saddr_group, *saddr_source_specific;
2464 guint iface_index = 0;
2466 #if defined (HAVE_IF_NAMETOINDEX)
2467 if (iface)
2469 iface_index = if_nametoindex (iface);
2470 if (iface_index == 0)
2472 int errsv = errno;
2474 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2475 _("Interface not found: %s"), g_strerror (errsv));
2476 return FALSE;
2479 #endif /* defined (HAVE_IF_NAMETOINDEX) */
2480 mc_req_src.gsr_interface = iface_index;
2482 saddr_group = g_inet_socket_address_new (group, 0);
2483 res = g_socket_address_to_native (saddr_group, &mc_req_src.gsr_group,
2484 sizeof (mc_req_src.gsr_group),
2485 error);
2486 g_object_unref (saddr_group);
2487 if (!res)
2488 return FALSE;
2490 saddr_source_specific = g_inet_socket_address_new (source_specific, 0);
2491 res = g_socket_address_to_native (saddr_source_specific,
2492 &mc_req_src.gsr_source,
2493 sizeof (mc_req_src.gsr_source),
2494 error);
2495 g_object_unref (saddr_source_specific);
2497 if (!res)
2498 return FALSE;
2500 optname =
2501 join_group ? MCAST_JOIN_SOURCE_GROUP : MCAST_LEAVE_SOURCE_GROUP;
2502 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2503 &mc_req_src, sizeof (mc_req_src));
2504 #else
2505 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2506 join_group ?
2507 _("Error joining multicast group: %s") :
2508 _("Error leaving multicast group: %s"),
2509 _("No support for IPv6 source-specific multicast"));
2510 return FALSE;
2511 #endif /* MCAST_JOIN_SOURCE_GROUP */
2513 break;
2515 default:
2516 g_return_val_if_reached (FALSE);
2519 if (result < 0)
2521 int errsv = get_socket_errno ();
2523 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2524 join_group ?
2525 _("Error joining multicast group: %s") :
2526 _("Error leaving multicast group: %s"),
2527 socket_strerror (errsv));
2528 return FALSE;
2531 return TRUE;
2535 * g_socket_join_multicast_group_ssm:
2536 * @socket: a #GSocket.
2537 * @group: a #GInetAddress specifying the group address to join.
2538 * @source_specific: (nullable): a #GInetAddress specifying the
2539 * source-specific multicast address or %NULL to ignore.
2540 * @iface: (nullable): Name of the interface to use, or %NULL
2541 * @error: #GError for error reporting, or %NULL to ignore.
2543 * Registers @socket to receive multicast messages sent to @group.
2544 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2545 * been bound to an appropriate interface and port with
2546 * g_socket_bind().
2548 * If @iface is %NULL, the system will automatically pick an interface
2549 * to bind to based on @group.
2551 * If @source_specific is not %NULL, use source-specific multicast as
2552 * defined in RFC 4604. Note that on older platforms this may fail
2553 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2555 * Note that this function can be called multiple times for the same
2556 * @group with different @source_specific in order to receive multicast
2557 * packets from more than one source.
2559 * Returns: %TRUE on success, %FALSE on error.
2561 * Since: 2.56
2563 gboolean
2564 g_socket_join_multicast_group_ssm (GSocket *socket,
2565 GInetAddress *group,
2566 GInetAddress *source_specific,
2567 const gchar *iface,
2568 GError **error)
2570 return g_socket_multicast_group_operation_ssm (socket, group,
2571 source_specific, iface, TRUE, error);
2575 * g_socket_leave_multicast_group_ssm:
2576 * @socket: a #GSocket.
2577 * @group: a #GInetAddress specifying the group address to leave.
2578 * @source_specific: (nullable): a #GInetAddress specifying the
2579 * source-specific multicast address or %NULL to ignore.
2580 * @iface: (nullable): Name of the interface to use, or %NULL
2581 * @error: #GError for error reporting, or %NULL to ignore.
2583 * Removes @socket from the multicast group defined by @group, @iface,
2584 * and @source_specific (which must all have the same values they had
2585 * when you joined the group).
2587 * @socket remains bound to its address and port, and can still receive
2588 * unicast messages after calling this.
2590 * Returns: %TRUE on success, %FALSE on error.
2592 * Since: 2.56
2594 gboolean
2595 g_socket_leave_multicast_group_ssm (GSocket *socket,
2596 GInetAddress *group,
2597 GInetAddress *source_specific,
2598 const gchar *iface,
2599 GError **error)
2601 return g_socket_multicast_group_operation_ssm (socket, group,
2602 source_specific, iface, FALSE, error);
2606 * g_socket_speaks_ipv4:
2607 * @socket: a #GSocket
2609 * Checks if a socket is capable of speaking IPv4.
2611 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2612 * and under some combinations of circumstances IPv6 sockets are also
2613 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2614 * information.
2616 * No other types of sockets are currently considered as being capable
2617 * of speaking IPv4.
2619 * Returns: %TRUE if this socket can be used with IPv4.
2621 * Since: 2.22
2623 gboolean
2624 g_socket_speaks_ipv4 (GSocket *socket)
2626 switch (socket->priv->family)
2628 case G_SOCKET_FAMILY_IPV4:
2629 return TRUE;
2631 case G_SOCKET_FAMILY_IPV6:
2632 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2634 gint v6_only;
2636 if (!g_socket_get_option (socket,
2637 IPPROTO_IPV6, IPV6_V6ONLY,
2638 &v6_only, NULL))
2639 return FALSE;
2641 return !v6_only;
2643 #else
2644 return FALSE;
2645 #endif
2647 default:
2648 return FALSE;
2653 * g_socket_accept:
2654 * @socket: a #GSocket.
2655 * @cancellable: (nullable): a %GCancellable or %NULL
2656 * @error: #GError for error reporting, or %NULL to ignore.
2658 * Accept incoming connections on a connection-based socket. This removes
2659 * the first outstanding connection request from the listening socket and
2660 * creates a #GSocket object for it.
2662 * The @socket must be bound to a local address with g_socket_bind() and
2663 * must be listening for incoming connections (g_socket_listen()).
2665 * If there are no outstanding connections then the operation will block
2666 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2667 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2669 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2670 * Free the returned object with g_object_unref().
2672 * Since: 2.22
2674 GSocket *
2675 g_socket_accept (GSocket *socket,
2676 GCancellable *cancellable,
2677 GError **error)
2679 GSocket *new_socket;
2680 gint ret;
2682 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2684 if (!check_socket (socket, error))
2685 return NULL;
2687 if (!check_timeout (socket, error))
2688 return NULL;
2690 while (TRUE)
2692 win32_unset_event_mask (socket, FD_ACCEPT);
2694 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2696 int errsv = get_socket_errno ();
2698 if (errsv == EINTR)
2699 continue;
2701 #ifdef WSAEWOULDBLOCK
2702 if (errsv == WSAEWOULDBLOCK)
2703 #else
2704 if (errsv == EWOULDBLOCK ||
2705 errsv == EAGAIN)
2706 #endif
2708 if (socket->priv->blocking)
2710 if (!g_socket_condition_wait (socket,
2711 G_IO_IN, cancellable, error))
2712 return NULL;
2714 continue;
2718 socket_set_error_lazy (error, errsv, _("Error accepting connection: %s"));
2719 return NULL;
2721 break;
2724 #ifdef G_OS_WIN32
2726 /* The socket inherits the accepting sockets event mask and even object,
2727 we need to remove that */
2728 WSAEventSelect (ret, NULL, 0);
2730 #else
2732 int flags;
2734 /* We always want to set close-on-exec to protect users. If you
2735 need to so some weird inheritance to exec you can re-enable this
2736 using lower level hacks with g_socket_get_fd(). */
2737 flags = fcntl (ret, F_GETFD, 0);
2738 if (flags != -1 &&
2739 (flags & FD_CLOEXEC) == 0)
2741 flags |= FD_CLOEXEC;
2742 fcntl (ret, F_SETFD, flags);
2745 #endif
2747 new_socket = g_socket_new_from_fd (ret, error);
2748 if (new_socket == NULL)
2750 #ifdef G_OS_WIN32
2751 closesocket (ret);
2752 #else
2753 close (ret);
2754 #endif
2756 else
2757 new_socket->priv->protocol = socket->priv->protocol;
2759 return new_socket;
2763 * g_socket_connect:
2764 * @socket: a #GSocket.
2765 * @address: a #GSocketAddress specifying the remote address.
2766 * @cancellable: (nullable): a %GCancellable or %NULL
2767 * @error: #GError for error reporting, or %NULL to ignore.
2769 * Connect the socket to the specified remote address.
2771 * For connection oriented socket this generally means we attempt to make
2772 * a connection to the @address. For a connection-less socket it sets
2773 * the default address for g_socket_send() and discards all incoming datagrams
2774 * from other sources.
2776 * Generally connection oriented sockets can only connect once, but
2777 * connection-less sockets can connect multiple times to change the
2778 * default address.
2780 * If the connect call needs to do network I/O it will block, unless
2781 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2782 * and the user can be notified of the connection finishing by waiting
2783 * for the G_IO_OUT condition. The result of the connection must then be
2784 * checked with g_socket_check_connect_result().
2786 * Returns: %TRUE if connected, %FALSE on error.
2788 * Since: 2.22
2790 gboolean
2791 g_socket_connect (GSocket *socket,
2792 GSocketAddress *address,
2793 GCancellable *cancellable,
2794 GError **error)
2796 struct sockaddr_storage buffer;
2798 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2800 if (!check_socket (socket, error))
2801 return FALSE;
2803 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2804 return FALSE;
2806 if (socket->priv->remote_address)
2807 g_object_unref (socket->priv->remote_address);
2808 socket->priv->remote_address = g_object_ref (address);
2810 while (1)
2812 win32_unset_event_mask (socket, FD_CONNECT);
2814 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2815 g_socket_address_get_native_size (address)) < 0)
2817 int errsv = get_socket_errno ();
2819 if (errsv == EINTR)
2820 continue;
2822 #ifndef G_OS_WIN32
2823 if (errsv == EINPROGRESS)
2824 #else
2825 if (errsv == WSAEWOULDBLOCK)
2826 #endif
2828 if (socket->priv->blocking)
2830 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2832 if (g_socket_check_connect_result (socket, error))
2833 break;
2836 else
2838 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2839 _("Connection in progress"));
2840 socket->priv->connect_pending = TRUE;
2843 else
2844 g_set_error_literal (error, G_IO_ERROR,
2845 socket_io_error_from_errno (errsv),
2846 socket_strerror (errsv));
2848 return FALSE;
2850 break;
2853 socket->priv->connected_read = TRUE;
2854 socket->priv->connected_write = TRUE;
2856 return TRUE;
2860 * g_socket_check_connect_result:
2861 * @socket: a #GSocket
2862 * @error: #GError for error reporting, or %NULL to ignore.
2864 * Checks and resets the pending connect error for the socket.
2865 * This is used to check for errors when g_socket_connect() is
2866 * used in non-blocking mode.
2868 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2870 * Since: 2.22
2872 gboolean
2873 g_socket_check_connect_result (GSocket *socket,
2874 GError **error)
2876 int value;
2878 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2880 if (!check_socket (socket, error))
2881 return FALSE;
2883 if (!check_timeout (socket, error))
2884 return FALSE;
2886 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
2888 g_prefix_error (error, _("Unable to get pending error: "));
2889 return FALSE;
2892 if (value != 0)
2894 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2895 socket_strerror (value));
2896 if (socket->priv->remote_address)
2898 g_object_unref (socket->priv->remote_address);
2899 socket->priv->remote_address = NULL;
2901 return FALSE;
2904 socket->priv->connected_read = TRUE;
2905 socket->priv->connected_write = TRUE;
2907 return TRUE;
2911 * g_socket_get_available_bytes:
2912 * @socket: a #GSocket
2914 * Get the amount of data pending in the OS input buffer, without blocking.
2916 * If @socket is a UDP or SCTP socket, this will return the size of
2917 * just the next packet, even if additional packets are buffered after
2918 * that one.
2920 * Note that on Windows, this function is rather inefficient in the
2921 * UDP case, and so if you know any plausible upper bound on the size
2922 * of the incoming packet, it is better to just do a
2923 * g_socket_receive() with a buffer of that size, rather than calling
2924 * g_socket_get_available_bytes() first and then doing a receive of
2925 * exactly the right size.
2927 * Returns: the number of bytes that can be read from the socket
2928 * without blocking or truncating, or -1 on error.
2930 * Since: 2.32
2932 gssize
2933 g_socket_get_available_bytes (GSocket *socket)
2935 #ifdef G_OS_WIN32
2936 const gint bufsize = 64 * 1024;
2937 static guchar *buf = NULL;
2938 u_long avail;
2939 #else
2940 gint avail;
2941 #endif
2943 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2945 #if defined (SO_NREAD)
2946 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
2947 return -1;
2948 #elif !defined (G_OS_WIN32)
2949 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2950 avail = -1;
2951 #else
2952 if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
2954 if (G_UNLIKELY (g_once_init_enter (&buf)))
2955 g_once_init_leave (&buf, g_malloc (bufsize));
2957 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
2958 if (avail == -1 && get_socket_errno () == WSAEWOULDBLOCK)
2959 avail = 0;
2961 else
2963 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
2964 avail = -1;
2966 #endif
2968 return avail;
2971 /* Block on a timed wait for @condition until (@start_time + @timeout).
2972 * Return %G_IO_ERROR_TIMED_OUT if the timeout is reached; otherwise %TRUE.
2974 static gboolean
2975 block_on_timeout (GSocket *socket,
2976 GIOCondition condition,
2977 gint64 timeout,
2978 gint64 start_time,
2979 GCancellable *cancellable,
2980 GError **error)
2982 gint64 wait_timeout = -1;
2984 g_return_val_if_fail (timeout != 0, TRUE);
2986 /* check if we've timed out or how much time to wait at most */
2987 if (timeout >= 0)
2989 gint64 elapsed = g_get_monotonic_time () - start_time;
2991 if (elapsed >= timeout)
2993 g_set_error_literal (error,
2994 G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2995 _("Socket I/O timed out"));
2996 return FALSE;
2999 wait_timeout = timeout - elapsed;
3002 return g_socket_condition_timed_wait (socket, condition, wait_timeout,
3003 cancellable, error);
3006 static gssize
3007 g_socket_receive_with_timeout (GSocket *socket,
3008 guint8 *buffer,
3009 gsize size,
3010 gint64 timeout,
3011 GCancellable *cancellable,
3012 GError **error)
3014 gssize ret;
3015 gint64 start_time;
3017 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3019 start_time = g_get_monotonic_time ();
3021 if (!check_socket (socket, error))
3022 return -1;
3024 if (!check_timeout (socket, error))
3025 return -1;
3027 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3028 return -1;
3030 while (1)
3032 win32_unset_event_mask (socket, FD_READ);
3034 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
3036 int errsv = get_socket_errno ();
3038 if (errsv == EINTR)
3039 continue;
3041 #ifdef WSAEWOULDBLOCK
3042 if (errsv == WSAEWOULDBLOCK)
3043 #else
3044 if (errsv == EWOULDBLOCK ||
3045 errsv == EAGAIN)
3046 #endif
3048 if (timeout != 0)
3050 if (!block_on_timeout (socket, G_IO_IN, timeout, start_time,
3051 cancellable, error))
3052 return -1;
3054 continue;
3058 socket_set_error_lazy (error, errsv, _("Error receiving data: %s"));
3059 return -1;
3062 break;
3065 return ret;
3069 * g_socket_receive:
3070 * @socket: a #GSocket
3071 * @buffer: (array length=size) (element-type guint8): a buffer to
3072 * read data into (which should be at least @size bytes long).
3073 * @size: the number of bytes you want to read from the socket
3074 * @cancellable: (nullable): a %GCancellable or %NULL
3075 * @error: #GError for error reporting, or %NULL to ignore.
3077 * Receive data (up to @size bytes) from a socket. This is mainly used by
3078 * connection-oriented sockets; it is identical to g_socket_receive_from()
3079 * with @address set to %NULL.
3081 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
3082 * g_socket_receive() will always read either 0 or 1 complete messages from
3083 * the socket. If the received message is too large to fit in @buffer, then
3084 * the data beyond @size bytes will be discarded, without any explicit
3085 * indication that this has occurred.
3087 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
3088 * number of bytes, up to @size. If more than @size bytes have been
3089 * received, the additional data will be returned in future calls to
3090 * g_socket_receive().
3092 * If the socket is in blocking mode the call will block until there
3093 * is some data to receive, the connection is closed, or there is an
3094 * error. If there is no data available and the socket is in
3095 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3096 * returned. To be notified when data is available, wait for the
3097 * %G_IO_IN condition.
3099 * On error -1 is returned and @error is set accordingly.
3101 * Returns: Number of bytes read, or 0 if the connection was closed by
3102 * the peer, or -1 on error
3104 * Since: 2.22
3106 gssize
3107 g_socket_receive (GSocket *socket,
3108 gchar *buffer,
3109 gsize size,
3110 GCancellable *cancellable,
3111 GError **error)
3113 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3114 socket->priv->blocking ? -1 : 0,
3115 cancellable, error);
3119 * g_socket_receive_with_blocking:
3120 * @socket: a #GSocket
3121 * @buffer: (array length=size) (element-type guint8): a buffer to
3122 * read data into (which should be at least @size bytes long).
3123 * @size: the number of bytes you want to read from the socket
3124 * @blocking: whether to do blocking or non-blocking I/O
3125 * @cancellable: (nullable): a %GCancellable or %NULL
3126 * @error: #GError for error reporting, or %NULL to ignore.
3128 * This behaves exactly the same as g_socket_receive(), except that
3129 * the choice of blocking or non-blocking behavior is determined by
3130 * the @blocking argument rather than by @socket's properties.
3132 * Returns: Number of bytes read, or 0 if the connection was closed by
3133 * the peer, or -1 on error
3135 * Since: 2.26
3137 gssize
3138 g_socket_receive_with_blocking (GSocket *socket,
3139 gchar *buffer,
3140 gsize size,
3141 gboolean blocking,
3142 GCancellable *cancellable,
3143 GError **error)
3145 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3146 blocking ? -1 : 0, cancellable, error);
3150 * g_socket_receive_from:
3151 * @socket: a #GSocket
3152 * @address: (out) (optional): a pointer to a #GSocketAddress
3153 * pointer, or %NULL
3154 * @buffer: (array length=size) (element-type guint8): a buffer to
3155 * read data into (which should be at least @size bytes long).
3156 * @size: the number of bytes you want to read from the socket
3157 * @cancellable: (nullable): a %GCancellable or %NULL
3158 * @error: #GError for error reporting, or %NULL to ignore.
3160 * Receive data (up to @size bytes) from a socket.
3162 * If @address is non-%NULL then @address will be set equal to the
3163 * source address of the received packet.
3164 * @address is owned by the caller.
3166 * See g_socket_receive() for additional information.
3168 * Returns: Number of bytes read, or 0 if the connection was closed by
3169 * the peer, or -1 on error
3171 * Since: 2.22
3173 gssize
3174 g_socket_receive_from (GSocket *socket,
3175 GSocketAddress **address,
3176 gchar *buffer,
3177 gsize size,
3178 GCancellable *cancellable,
3179 GError **error)
3181 GInputVector v;
3183 v.buffer = buffer;
3184 v.size = size;
3186 return g_socket_receive_message (socket,
3187 address,
3188 &v, 1,
3189 NULL, 0, NULL,
3190 cancellable,
3191 error);
3194 /* See the comment about SIGPIPE above. */
3195 #ifdef MSG_NOSIGNAL
3196 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
3197 #else
3198 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
3199 #endif
3201 static gssize
3202 g_socket_send_with_timeout (GSocket *socket,
3203 const guint8 *buffer,
3204 gsize size,
3205 gint64 timeout,
3206 GCancellable *cancellable,
3207 GError **error)
3209 gssize ret;
3210 gint64 start_time;
3212 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3214 start_time = g_get_monotonic_time ();
3216 if (!check_socket (socket, error))
3217 return -1;
3219 if (!check_timeout (socket, error))
3220 return -1;
3222 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3223 return -1;
3225 while (1)
3227 win32_unset_event_mask (socket, FD_WRITE);
3229 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
3231 int errsv = get_socket_errno ();
3233 if (errsv == EINTR)
3234 continue;
3236 #ifdef WSAEWOULDBLOCK
3237 if (errsv == WSAEWOULDBLOCK)
3238 #else
3239 if (errsv == EWOULDBLOCK ||
3240 errsv == EAGAIN)
3241 #endif
3243 if (timeout != 0)
3245 if (!block_on_timeout (socket, G_IO_OUT, timeout, start_time,
3246 cancellable, error))
3247 return -1;
3249 continue;
3253 socket_set_error_lazy (error, errsv, _("Error sending data: %s"));
3254 return -1;
3256 break;
3259 return ret;
3263 * g_socket_send:
3264 * @socket: a #GSocket
3265 * @buffer: (array length=size) (element-type guint8): the buffer
3266 * containing the data to send.
3267 * @size: the number of bytes to send
3268 * @cancellable: (nullable): a %GCancellable or %NULL
3269 * @error: #GError for error reporting, or %NULL to ignore.
3271 * Tries to send @size bytes from @buffer on the socket. This is
3272 * mainly used by connection-oriented sockets; it is identical to
3273 * g_socket_send_to() with @address set to %NULL.
3275 * If the socket is in blocking mode the call will block until there is
3276 * space for the data in the socket queue. If there is no space available
3277 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3278 * will be returned. To be notified when space is available, wait for the
3279 * %G_IO_OUT condition. Note though that you may still receive
3280 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3281 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3282 * very common due to the way the underlying APIs work.)
3284 * On error -1 is returned and @error is set accordingly.
3286 * Returns: Number of bytes written (which may be less than @size), or -1
3287 * on error
3289 * Since: 2.22
3291 gssize
3292 g_socket_send (GSocket *socket,
3293 const gchar *buffer,
3294 gsize size,
3295 GCancellable *cancellable,
3296 GError **error)
3298 return g_socket_send_with_blocking (socket, buffer, size,
3299 socket->priv->blocking,
3300 cancellable, error);
3304 * g_socket_send_with_blocking:
3305 * @socket: a #GSocket
3306 * @buffer: (array length=size) (element-type guint8): the buffer
3307 * containing the data to send.
3308 * @size: the number of bytes to send
3309 * @blocking: whether to do blocking or non-blocking I/O
3310 * @cancellable: (nullable): a %GCancellable or %NULL
3311 * @error: #GError for error reporting, or %NULL to ignore.
3313 * This behaves exactly the same as g_socket_send(), except that
3314 * the choice of blocking or non-blocking behavior is determined by
3315 * the @blocking argument rather than by @socket's properties.
3317 * Returns: Number of bytes written (which may be less than @size), or -1
3318 * on error
3320 * Since: 2.26
3322 gssize
3323 g_socket_send_with_blocking (GSocket *socket,
3324 const gchar *buffer,
3325 gsize size,
3326 gboolean blocking,
3327 GCancellable *cancellable,
3328 GError **error)
3330 return g_socket_send_with_timeout (socket, (const guint8 *) buffer, size,
3331 blocking ? -1 : 0, cancellable, error);
3335 * g_socket_send_to:
3336 * @socket: a #GSocket
3337 * @address: (nullable): a #GSocketAddress, or %NULL
3338 * @buffer: (array length=size) (element-type guint8): the buffer
3339 * containing the data to send.
3340 * @size: the number of bytes to send
3341 * @cancellable: (nullable): a %GCancellable or %NULL
3342 * @error: #GError for error reporting, or %NULL to ignore.
3344 * Tries to send @size bytes from @buffer to @address. If @address is
3345 * %NULL then the message is sent to the default receiver (set by
3346 * g_socket_connect()).
3348 * See g_socket_send() for additional information.
3350 * Returns: Number of bytes written (which may be less than @size), or -1
3351 * on error
3353 * Since: 2.22
3355 gssize
3356 g_socket_send_to (GSocket *socket,
3357 GSocketAddress *address,
3358 const gchar *buffer,
3359 gsize size,
3360 GCancellable *cancellable,
3361 GError **error)
3363 GOutputVector v;
3365 v.buffer = buffer;
3366 v.size = size;
3368 return g_socket_send_message (socket,
3369 address,
3370 &v, 1,
3371 NULL, 0,
3373 cancellable,
3374 error);
3378 * g_socket_shutdown:
3379 * @socket: a #GSocket
3380 * @shutdown_read: whether to shut down the read side
3381 * @shutdown_write: whether to shut down the write side
3382 * @error: #GError for error reporting, or %NULL to ignore.
3384 * Shut down part or all of a full-duplex connection.
3386 * If @shutdown_read is %TRUE then the receiving side of the connection
3387 * is shut down, and further reading is disallowed.
3389 * If @shutdown_write is %TRUE then the sending side of the connection
3390 * is shut down, and further writing is disallowed.
3392 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
3394 * One example where it is useful to shut down only one side of a connection is
3395 * graceful disconnect for TCP connections where you close the sending side,
3396 * then wait for the other side to close the connection, thus ensuring that the
3397 * other side saw all sent data.
3399 * Returns: %TRUE on success, %FALSE on error
3401 * Since: 2.22
3403 gboolean
3404 g_socket_shutdown (GSocket *socket,
3405 gboolean shutdown_read,
3406 gboolean shutdown_write,
3407 GError **error)
3409 int how;
3411 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3413 if (!check_socket (socket, error))
3414 return FALSE;
3416 /* Do nothing? */
3417 if (!shutdown_read && !shutdown_write)
3418 return TRUE;
3420 #ifndef G_OS_WIN32
3421 if (shutdown_read && shutdown_write)
3422 how = SHUT_RDWR;
3423 else if (shutdown_read)
3424 how = SHUT_RD;
3425 else
3426 how = SHUT_WR;
3427 #else
3428 if (shutdown_read && shutdown_write)
3429 how = SD_BOTH;
3430 else if (shutdown_read)
3431 how = SD_RECEIVE;
3432 else
3433 how = SD_SEND;
3434 #endif
3436 if (shutdown (socket->priv->fd, how) != 0)
3438 int errsv = get_socket_errno ();
3439 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
3440 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
3441 return FALSE;
3444 if (shutdown_read)
3445 socket->priv->connected_read = FALSE;
3446 if (shutdown_write)
3447 socket->priv->connected_write = FALSE;
3449 return TRUE;
3453 * g_socket_close:
3454 * @socket: a #GSocket
3455 * @error: #GError for error reporting, or %NULL to ignore.
3457 * Closes the socket, shutting down any active connection.
3459 * Closing a socket does not wait for all outstanding I/O operations
3460 * to finish, so the caller should not rely on them to be guaranteed
3461 * to complete even if the close returns with no error.
3463 * Once the socket is closed, all other operations will return
3464 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
3465 * return an error.
3467 * Sockets will be automatically closed when the last reference
3468 * is dropped, but you might want to call this function to make sure
3469 * resources are released as early as possible.
3471 * Beware that due to the way that TCP works, it is possible for
3472 * recently-sent data to be lost if either you close a socket while the
3473 * %G_IO_IN condition is set, or else if the remote connection tries to
3474 * send something to you after you close the socket but before it has
3475 * finished reading all of the data you sent. There is no easy generic
3476 * way to avoid this problem; the easiest fix is to design the network
3477 * protocol such that the client will never send data "out of turn".
3478 * Another solution is for the server to half-close the connection by
3479 * calling g_socket_shutdown() with only the @shutdown_write flag set,
3480 * and then wait for the client to notice this and close its side of the
3481 * connection, after which the server can safely call g_socket_close().
3482 * (This is what #GTcpConnection does if you call
3483 * g_tcp_connection_set_graceful_disconnect(). But of course, this
3484 * only works if the client will close its connection after the server
3485 * does.)
3487 * Returns: %TRUE on success, %FALSE on error
3489 * Since: 2.22
3491 gboolean
3492 g_socket_close (GSocket *socket,
3493 GError **error)
3495 int res;
3497 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3499 if (socket->priv->closed)
3500 return TRUE; /* Multiple close not an error */
3502 if (!check_socket (socket, error))
3503 return FALSE;
3505 while (1)
3507 #ifdef G_OS_WIN32
3508 res = closesocket (socket->priv->fd);
3509 #else
3510 res = close (socket->priv->fd);
3511 #endif
3512 if (res == -1)
3514 int errsv = get_socket_errno ();
3516 if (errsv == EINTR)
3517 continue;
3519 g_set_error (error, G_IO_ERROR,
3520 socket_io_error_from_errno (errsv),
3521 _("Error closing socket: %s"),
3522 socket_strerror (errsv));
3523 return FALSE;
3525 break;
3528 socket->priv->fd = -1;
3529 socket->priv->connected_read = FALSE;
3530 socket->priv->connected_write = FALSE;
3531 socket->priv->closed = TRUE;
3532 if (socket->priv->remote_address)
3534 g_object_unref (socket->priv->remote_address);
3535 socket->priv->remote_address = NULL;
3538 return TRUE;
3542 * g_socket_is_closed:
3543 * @socket: a #GSocket
3545 * Checks whether a socket is closed.
3547 * Returns: %TRUE if socket is closed, %FALSE otherwise
3549 * Since: 2.22
3551 gboolean
3552 g_socket_is_closed (GSocket *socket)
3554 return socket->priv->closed;
3557 #ifdef G_OS_WIN32
3558 /* Broken source, used on errors */
3559 static gboolean
3560 broken_dispatch (GSource *source,
3561 GSourceFunc callback,
3562 gpointer user_data)
3564 return TRUE;
3567 static GSourceFuncs broken_funcs =
3569 NULL,
3570 NULL,
3571 broken_dispatch,
3572 NULL
3575 static gint
3576 network_events_for_condition (GIOCondition condition)
3578 int event_mask = 0;
3580 if (condition & G_IO_IN)
3581 event_mask |= (FD_READ | FD_ACCEPT);
3582 if (condition & G_IO_OUT)
3583 event_mask |= (FD_WRITE | FD_CONNECT);
3584 event_mask |= FD_CLOSE;
3586 return event_mask;
3589 static void
3590 ensure_event (GSocket *socket)
3592 if (socket->priv->event == WSA_INVALID_EVENT)
3593 socket->priv->event = WSACreateEvent();
3596 static void
3597 update_select_events (GSocket *socket)
3599 int event_mask;
3600 GIOCondition *ptr;
3601 GList *l;
3602 WSAEVENT event;
3604 ensure_event (socket);
3606 event_mask = 0;
3607 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3609 ptr = l->data;
3610 event_mask |= network_events_for_condition (*ptr);
3613 if (event_mask != socket->priv->selected_events)
3615 /* If no events selected, disable event so we can unset
3616 nonblocking mode */
3618 if (event_mask == 0)
3619 event = NULL;
3620 else
3621 event = socket->priv->event;
3623 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3624 socket->priv->selected_events = event_mask;
3628 static void
3629 add_condition_watch (GSocket *socket,
3630 GIOCondition *condition)
3632 g_mutex_lock (&socket->priv->win32_source_lock);
3633 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3635 socket->priv->requested_conditions =
3636 g_list_prepend (socket->priv->requested_conditions, condition);
3638 update_select_events (socket);
3639 g_mutex_unlock (&socket->priv->win32_source_lock);
3642 static void
3643 remove_condition_watch (GSocket *socket,
3644 GIOCondition *condition)
3646 g_mutex_lock (&socket->priv->win32_source_lock);
3647 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3649 socket->priv->requested_conditions =
3650 g_list_remove (socket->priv->requested_conditions, condition);
3652 update_select_events (socket);
3653 g_mutex_unlock (&socket->priv->win32_source_lock);
3656 static GIOCondition
3657 update_condition_unlocked (GSocket *socket)
3659 WSANETWORKEVENTS events;
3660 GIOCondition condition;
3662 if (WSAEnumNetworkEvents (socket->priv->fd,
3663 socket->priv->event,
3664 &events) == 0)
3666 socket->priv->current_events |= events.lNetworkEvents;
3667 if (events.lNetworkEvents & FD_WRITE &&
3668 events.iErrorCode[FD_WRITE_BIT] != 0)
3669 socket->priv->current_errors |= FD_WRITE;
3670 if (events.lNetworkEvents & FD_CONNECT &&
3671 events.iErrorCode[FD_CONNECT_BIT] != 0)
3672 socket->priv->current_errors |= FD_CONNECT;
3675 condition = 0;
3676 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3677 condition |= G_IO_IN;
3679 if (socket->priv->current_events & FD_CLOSE)
3681 int r, errsv, buffer;
3683 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3684 if (r < 0)
3685 errsv = get_socket_errno ();
3687 if (r > 0 ||
3688 (r < 0 && errsv == WSAENOTCONN))
3689 condition |= G_IO_IN;
3690 else if (r == 0 ||
3691 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3692 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3693 condition |= G_IO_HUP;
3694 else
3695 condition |= G_IO_ERR;
3698 if (socket->priv->closed)
3699 condition |= G_IO_HUP;
3701 /* Never report both G_IO_OUT and HUP, these are
3702 mutually exclusive (can't write to a closed socket) */
3703 if ((condition & G_IO_HUP) == 0 &&
3704 socket->priv->current_events & FD_WRITE)
3706 if (socket->priv->current_errors & FD_WRITE)
3707 condition |= G_IO_ERR;
3708 else
3709 condition |= G_IO_OUT;
3711 else
3713 if (socket->priv->current_events & FD_CONNECT)
3715 if (socket->priv->current_errors & FD_CONNECT)
3716 condition |= (G_IO_HUP | G_IO_ERR);
3717 else
3718 condition |= G_IO_OUT;
3722 return condition;
3725 static GIOCondition
3726 update_condition (GSocket *socket)
3728 GIOCondition res;
3729 g_mutex_lock (&socket->priv->win32_source_lock);
3730 res = update_condition_unlocked (socket);
3731 g_mutex_unlock (&socket->priv->win32_source_lock);
3732 return res;
3734 #endif
3736 typedef struct {
3737 GSource source;
3738 #ifdef G_OS_WIN32
3739 GPollFD pollfd;
3740 #else
3741 gpointer fd_tag;
3742 #endif
3743 GSocket *socket;
3744 GIOCondition condition;
3745 } GSocketSource;
3747 static gboolean
3748 socket_source_prepare (GSource *source,
3749 gint *timeout)
3751 GSocketSource *socket_source = (GSocketSource *)source;
3753 *timeout = -1;
3755 #ifdef G_OS_WIN32
3756 if ((socket_source->pollfd.revents & G_IO_NVAL) != 0)
3757 return TRUE;
3759 if (g_socket_is_closed (socket_source->socket))
3761 g_source_remove_poll (source, &socket_source->pollfd);
3762 socket_source->pollfd.revents = G_IO_NVAL;
3763 return TRUE;
3766 return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3767 #else
3768 return g_socket_is_closed (socket_source->socket) && socket_source->fd_tag != NULL;
3769 #endif
3772 #ifdef G_OS_WIN32
3773 static gboolean
3774 socket_source_check_win32 (GSource *source)
3776 int timeout;
3778 return socket_source_prepare (source, &timeout);
3780 #endif
3782 static gboolean
3783 socket_source_dispatch (GSource *source,
3784 GSourceFunc callback,
3785 gpointer user_data)
3787 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3788 GSocketSource *socket_source = (GSocketSource *)source;
3789 GSocket *socket = socket_source->socket;
3790 gint64 timeout;
3791 guint events;
3792 gboolean ret;
3794 #ifdef G_OS_WIN32
3795 events = update_condition (socket_source->socket);
3796 #else
3797 if (g_socket_is_closed (socket_source->socket))
3799 if (socket_source->fd_tag)
3800 g_source_remove_unix_fd (source, socket_source->fd_tag);
3801 socket_source->fd_tag = NULL;
3802 events = G_IO_NVAL;
3804 else
3806 events = g_source_query_unix_fd (source, socket_source->fd_tag);
3808 #endif
3810 timeout = g_source_get_ready_time (source);
3811 if (timeout >= 0 && timeout < g_source_get_time (source) &&
3812 !g_socket_is_closed (socket_source->socket))
3814 socket->priv->timed_out = TRUE;
3815 events |= (G_IO_IN | G_IO_OUT);
3818 ret = (*func) (socket, events & socket_source->condition, user_data);
3820 if (socket->priv->timeout && !g_socket_is_closed (socket_source->socket))
3821 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3822 else
3823 g_source_set_ready_time (source, -1);
3825 return ret;
3828 static void
3829 socket_source_finalize (GSource *source)
3831 GSocketSource *socket_source = (GSocketSource *)source;
3832 GSocket *socket;
3834 socket = socket_source->socket;
3836 #ifdef G_OS_WIN32
3837 remove_condition_watch (socket, &socket_source->condition);
3838 #endif
3840 g_object_unref (socket);
3843 static gboolean
3844 socket_source_closure_callback (GSocket *socket,
3845 GIOCondition condition,
3846 gpointer data)
3848 GClosure *closure = data;
3850 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3851 GValue result_value = G_VALUE_INIT;
3852 gboolean result;
3854 g_value_init (&result_value, G_TYPE_BOOLEAN);
3856 g_value_init (&params[0], G_TYPE_SOCKET);
3857 g_value_set_object (&params[0], socket);
3858 g_value_init (&params[1], G_TYPE_IO_CONDITION);
3859 g_value_set_flags (&params[1], condition);
3861 g_closure_invoke (closure, &result_value, 2, params, NULL);
3863 result = g_value_get_boolean (&result_value);
3864 g_value_unset (&result_value);
3865 g_value_unset (&params[0]);
3866 g_value_unset (&params[1]);
3868 return result;
3871 static GSourceFuncs socket_source_funcs =
3873 socket_source_prepare,
3874 #ifdef G_OS_WIN32
3875 socket_source_check_win32,
3876 #else
3877 NULL,
3878 #endif
3879 socket_source_dispatch,
3880 socket_source_finalize,
3881 (GSourceFunc)socket_source_closure_callback,
3884 static GSource *
3885 socket_source_new (GSocket *socket,
3886 GIOCondition condition,
3887 GCancellable *cancellable)
3889 GSource *source;
3890 GSocketSource *socket_source;
3892 #ifdef G_OS_WIN32
3893 ensure_event (socket);
3895 if (socket->priv->event == WSA_INVALID_EVENT)
3897 g_warning ("Failed to create WSAEvent");
3898 return g_source_new (&broken_funcs, sizeof (GSource));
3900 #endif
3902 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
3904 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3905 g_source_set_name (source, "GSocket");
3906 socket_source = (GSocketSource *)source;
3908 socket_source->socket = g_object_ref (socket);
3909 socket_source->condition = condition;
3911 if (cancellable)
3913 GSource *cancellable_source;
3915 cancellable_source = g_cancellable_source_new (cancellable);
3916 g_source_add_child_source (source, cancellable_source);
3917 g_source_set_dummy_callback (cancellable_source);
3918 g_source_unref (cancellable_source);
3921 #ifdef G_OS_WIN32
3922 add_condition_watch (socket, &socket_source->condition);
3923 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3924 socket_source->pollfd.events = condition;
3925 socket_source->pollfd.revents = 0;
3926 g_source_add_poll (source, &socket_source->pollfd);
3927 #else
3928 socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
3929 #endif
3931 if (socket->priv->timeout)
3932 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3933 else
3934 g_source_set_ready_time (source, -1);
3936 return source;
3940 * g_socket_create_source: (skip)
3941 * @socket: a #GSocket
3942 * @condition: a #GIOCondition mask to monitor
3943 * @cancellable: (nullable): a %GCancellable or %NULL
3945 * Creates a #GSource that can be attached to a %GMainContext to monitor
3946 * for the availability of the specified @condition on the socket. The #GSource
3947 * keeps a reference to the @socket.
3949 * The callback on the source is of the #GSocketSourceFunc type.
3951 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3952 * these conditions will always be reported output if they are true.
3954 * @cancellable if not %NULL can be used to cancel the source, which will
3955 * cause the source to trigger, reporting the current condition (which
3956 * is likely 0 unless cancellation happened at the same time as a
3957 * condition change). You can check for this in the callback using
3958 * g_cancellable_is_cancelled().
3960 * If @socket has a timeout set, and it is reached before @condition
3961 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3962 * %G_IO_OUT depending on @condition. However, @socket will have been
3963 * marked as having had a timeout, and so the next #GSocket I/O method
3964 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3966 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3968 * Since: 2.22
3970 GSource *
3971 g_socket_create_source (GSocket *socket,
3972 GIOCondition condition,
3973 GCancellable *cancellable)
3975 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3977 return socket_source_new (socket, condition, cancellable);
3981 * g_socket_condition_check:
3982 * @socket: a #GSocket
3983 * @condition: a #GIOCondition mask to check
3985 * Checks on the readiness of @socket to perform operations.
3986 * The operations specified in @condition are checked for and masked
3987 * against the currently-satisfied conditions on @socket. The result
3988 * is returned.
3990 * Note that on Windows, it is possible for an operation to return
3991 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3992 * g_socket_condition_check() has claimed that the socket is ready for
3993 * writing. Rather than calling g_socket_condition_check() and then
3994 * writing to the socket if it succeeds, it is generally better to
3995 * simply try writing to the socket right away, and try again later if
3996 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3998 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3999 * these conditions will always be set in the output if they are true.
4001 * This call never blocks.
4003 * Returns: the @GIOCondition mask of the current state
4005 * Since: 2.22
4007 GIOCondition
4008 g_socket_condition_check (GSocket *socket,
4009 GIOCondition condition)
4011 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
4013 if (!check_socket (socket, NULL))
4014 return 0;
4016 #ifdef G_OS_WIN32
4018 GIOCondition current_condition;
4020 condition |= G_IO_ERR | G_IO_HUP;
4022 add_condition_watch (socket, &condition);
4023 current_condition = update_condition (socket);
4024 remove_condition_watch (socket, &condition);
4025 return condition & current_condition;
4027 #else
4029 GPollFD poll_fd;
4030 gint result;
4031 poll_fd.fd = socket->priv->fd;
4032 poll_fd.events = condition;
4033 poll_fd.revents = 0;
4036 result = g_poll (&poll_fd, 1, 0);
4037 while (result == -1 && get_socket_errno () == EINTR);
4039 return poll_fd.revents;
4041 #endif
4045 * g_socket_condition_wait:
4046 * @socket: a #GSocket
4047 * @condition: a #GIOCondition mask to wait for
4048 * @cancellable: (nullable): a #GCancellable, or %NULL
4049 * @error: a #GError pointer, or %NULL
4051 * Waits for @condition to become true on @socket. When the condition
4052 * is met, %TRUE is returned.
4054 * If @cancellable is cancelled before the condition is met, or if the
4055 * socket has a timeout set and it is reached before the condition is
4056 * met, then %FALSE is returned and @error, if non-%NULL, is set to
4057 * the appropriate value (%G_IO_ERROR_CANCELLED or
4058 * %G_IO_ERROR_TIMED_OUT).
4060 * See also g_socket_condition_timed_wait().
4062 * Returns: %TRUE if the condition was met, %FALSE otherwise
4064 * Since: 2.22
4066 gboolean
4067 g_socket_condition_wait (GSocket *socket,
4068 GIOCondition condition,
4069 GCancellable *cancellable,
4070 GError **error)
4072 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4074 return g_socket_condition_timed_wait (socket, condition, -1,
4075 cancellable, error);
4079 * g_socket_condition_timed_wait:
4080 * @socket: a #GSocket
4081 * @condition: a #GIOCondition mask to wait for
4082 * @timeout: the maximum time (in microseconds) to wait, or -1
4083 * @cancellable: (nullable): a #GCancellable, or %NULL
4084 * @error: a #GError pointer, or %NULL
4086 * Waits for up to @timeout microseconds for @condition to become true
4087 * on @socket. If the condition is met, %TRUE is returned.
4089 * If @cancellable is cancelled before the condition is met, or if
4090 * @timeout (or the socket's #GSocket:timeout) is reached before the
4091 * condition is met, then %FALSE is returned and @error, if non-%NULL,
4092 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
4093 * %G_IO_ERROR_TIMED_OUT).
4095 * If you don't want a timeout, use g_socket_condition_wait().
4096 * (Alternatively, you can pass -1 for @timeout.)
4098 * Note that although @timeout is in microseconds for consistency with
4099 * other GLib APIs, this function actually only has millisecond
4100 * resolution, and the behavior is undefined if @timeout is not an
4101 * exact number of milliseconds.
4103 * Returns: %TRUE if the condition was met, %FALSE otherwise
4105 * Since: 2.32
4107 gboolean
4108 g_socket_condition_timed_wait (GSocket *socket,
4109 GIOCondition condition,
4110 gint64 timeout,
4111 GCancellable *cancellable,
4112 GError **error)
4114 gint64 start_time;
4116 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4118 if (!check_socket (socket, error))
4119 return FALSE;
4121 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4122 return FALSE;
4124 if (socket->priv->timeout &&
4125 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
4126 timeout = (gint64) socket->priv->timeout * 1000;
4127 else if (timeout != -1)
4128 timeout = timeout / 1000;
4130 start_time = g_get_monotonic_time ();
4132 #ifdef G_OS_WIN32
4134 GIOCondition current_condition;
4135 WSAEVENT events[2];
4136 DWORD res;
4137 GPollFD cancel_fd;
4138 int num_events;
4140 /* Always check these */
4141 condition |= G_IO_ERR | G_IO_HUP;
4143 add_condition_watch (socket, &condition);
4145 num_events = 0;
4146 events[num_events++] = socket->priv->event;
4148 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
4149 events[num_events++] = (WSAEVENT)cancel_fd.fd;
4151 if (timeout == -1)
4152 timeout = WSA_INFINITE;
4154 g_mutex_lock (&socket->priv->win32_source_lock);
4155 current_condition = update_condition_unlocked (socket);
4156 while ((condition & current_condition) == 0)
4158 if (!socket->priv->waiting)
4160 socket->priv->waiting = TRUE;
4161 socket->priv->waiting_result = 0;
4162 g_mutex_unlock (&socket->priv->win32_source_lock);
4164 res = WSAWaitForMultipleEvents (num_events, events, FALSE, timeout, FALSE);
4166 g_mutex_lock (&socket->priv->win32_source_lock);
4167 socket->priv->waiting = FALSE;
4168 socket->priv->waiting_result = res;
4169 g_cond_broadcast (&socket->priv->win32_source_cond);
4171 else
4173 if (timeout != WSA_INFINITE)
4175 if (!g_cond_wait_until (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock, timeout))
4177 res = WSA_WAIT_TIMEOUT;
4178 break;
4180 else
4182 res = socket->priv->waiting_result;
4185 else
4187 g_cond_wait (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock);
4188 res = socket->priv->waiting_result;
4192 if (res == WSA_WAIT_FAILED)
4194 int errsv = get_socket_errno ();
4196 g_set_error (error, G_IO_ERROR,
4197 socket_io_error_from_errno (errsv),
4198 _("Waiting for socket condition: %s"),
4199 socket_strerror (errsv));
4200 break;
4202 else if (res == WSA_WAIT_TIMEOUT)
4204 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4205 _("Socket I/O timed out"));
4206 break;
4209 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4210 break;
4212 current_condition = update_condition_unlocked (socket);
4214 if (timeout != WSA_INFINITE)
4216 timeout -= (g_get_monotonic_time () - start_time) * 1000;
4217 if (timeout < 0)
4218 timeout = 0;
4221 g_mutex_unlock (&socket->priv->win32_source_lock);
4222 remove_condition_watch (socket, &condition);
4223 if (num_events > 1)
4224 g_cancellable_release_fd (cancellable);
4226 return (condition & current_condition) != 0;
4228 #else
4230 GPollFD poll_fd[2];
4231 gint result;
4232 gint num;
4234 poll_fd[0].fd = socket->priv->fd;
4235 poll_fd[0].events = condition;
4236 num = 1;
4238 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
4239 num++;
4241 while (TRUE)
4243 int errsv;
4244 result = g_poll (poll_fd, num, timeout);
4245 errsv = errno;
4246 if (result != -1 || errsv != EINTR)
4247 break;
4249 if (timeout != -1)
4251 timeout -= (g_get_monotonic_time () - start_time) / 1000;
4252 if (timeout < 0)
4253 timeout = 0;
4257 if (num > 1)
4258 g_cancellable_release_fd (cancellable);
4260 if (result == 0)
4262 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4263 _("Socket I/O timed out"));
4264 return FALSE;
4267 return !g_cancellable_set_error_if_cancelled (cancellable, error);
4269 #endif
4272 #ifndef G_OS_WIN32
4274 /* Unfortunately these have to be macros rather than inline functions due to
4275 * using alloca(). */
4276 #define output_message_to_msghdr(message, prev_message, msg, prev_msg, error) \
4277 G_STMT_START { \
4278 const GOutputMessage *_message = (message); \
4279 const GOutputMessage *_prev_message = (prev_message); \
4280 struct msghdr *_msg = (msg); \
4281 const struct msghdr *_prev_msg = (prev_msg); \
4282 GError **_error = (error); \
4284 _msg->msg_flags = 0; \
4286 /* name */ \
4287 if (_prev_message != NULL && _prev_message->address == _message->address) \
4289 _msg->msg_name = _prev_msg->msg_name; \
4290 _msg->msg_namelen = _prev_msg->msg_namelen; \
4292 else if (_message->address != NULL) \
4294 _msg->msg_namelen = g_socket_address_get_native_size (_message->address); \
4295 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4296 if (!g_socket_address_to_native (_message->address, _msg->msg_name, \
4297 _msg->msg_namelen, _error)) \
4298 break; \
4300 else \
4302 _msg->msg_name = NULL; \
4303 _msg->msg_namelen = 0; \
4306 /* iov */ \
4308 /* this entire expression will be evaluated at compile time */ \
4309 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4310 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4311 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4312 G_STRUCT_OFFSET (GOutputVector, buffer) && \
4313 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4314 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4315 G_STRUCT_OFFSET (GOutputVector, size)) \
4316 /* ABI is compatible */ \
4318 _msg->msg_iov = (struct iovec *) _message->vectors; \
4319 _msg->msg_iovlen = _message->num_vectors; \
4321 else \
4322 /* ABI is incompatible */ \
4324 gint i; \
4326 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4327 for (i = 0; i < _message->num_vectors; i++) \
4329 _msg->msg_iov[i].iov_base = (void *) _message->vectors[i].buffer; \
4330 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4332 _msg->msg_iovlen = _message->num_vectors; \
4336 /* control */ \
4338 struct cmsghdr *cmsg; \
4339 gint i; \
4341 _msg->msg_controllen = 0; \
4342 for (i = 0; i < _message->num_control_messages; i++) \
4343 _msg->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (_message->control_messages[i])); \
4345 if (_msg->msg_controllen == 0) \
4346 _msg->msg_control = NULL; \
4347 else \
4349 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4350 memset (_msg->msg_control, '\0', _msg->msg_controllen); \
4353 cmsg = CMSG_FIRSTHDR (_msg); \
4354 for (i = 0; i < _message->num_control_messages; i++) \
4356 cmsg->cmsg_level = g_socket_control_message_get_level (_message->control_messages[i]); \
4357 cmsg->cmsg_type = g_socket_control_message_get_msg_type (_message->control_messages[i]); \
4358 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (_message->control_messages[i])); \
4359 g_socket_control_message_serialize (_message->control_messages[i], \
4360 CMSG_DATA (cmsg)); \
4361 cmsg = CMSG_NXTHDR (_msg, cmsg); \
4363 g_assert (cmsg == NULL); \
4365 } G_STMT_END
4367 #define input_message_to_msghdr(message, msg) \
4368 G_STMT_START { \
4369 const GInputMessage *_message = (message); \
4370 struct msghdr *_msg = (msg); \
4372 /* name */ \
4373 if (_message->address) \
4375 _msg->msg_namelen = sizeof (struct sockaddr_storage); \
4376 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4378 else \
4380 _msg->msg_name = NULL; \
4381 _msg->msg_namelen = 0; \
4384 /* iov */ \
4385 /* this entire expression will be evaluated at compile time */ \
4386 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4387 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4388 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4389 G_STRUCT_OFFSET (GInputVector, buffer) && \
4390 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4391 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4392 G_STRUCT_OFFSET (GInputVector, size)) \
4393 /* ABI is compatible */ \
4395 _msg->msg_iov = (struct iovec *) _message->vectors; \
4396 _msg->msg_iovlen = _message->num_vectors; \
4398 else \
4399 /* ABI is incompatible */ \
4401 guint i; \
4403 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4404 for (i = 0; i < _message->num_vectors; i++) \
4406 _msg->msg_iov[i].iov_base = _message->vectors[i].buffer; \
4407 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4409 _msg->msg_iovlen = _message->num_vectors; \
4412 /* control */ \
4413 if (_message->control_messages == NULL) \
4415 _msg->msg_controllen = 0; \
4416 _msg->msg_control = NULL; \
4418 else \
4420 _msg->msg_controllen = 2048; \
4421 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4424 /* flags */ \
4425 _msg->msg_flags = _message->flags; \
4426 } G_STMT_END
4428 static void
4429 input_message_from_msghdr (const struct msghdr *msg,
4430 GInputMessage *message,
4431 GSocket *socket)
4433 /* decode address */
4434 if (message->address != NULL)
4436 *message->address = cache_recv_address (socket, msg->msg_name,
4437 msg->msg_namelen);
4440 /* decode control messages */
4442 GPtrArray *my_messages = NULL;
4443 struct cmsghdr *cmsg;
4445 if (msg->msg_controllen >= sizeof (struct cmsghdr))
4447 g_assert (message->control_messages != NULL);
4448 for (cmsg = CMSG_FIRSTHDR (msg);
4449 cmsg != NULL;
4450 cmsg = CMSG_NXTHDR ((struct msghdr *) msg, cmsg))
4452 GSocketControlMessage *control_message;
4454 control_message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4455 cmsg->cmsg_type,
4456 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4457 CMSG_DATA (cmsg));
4458 if (control_message == NULL)
4459 /* We've already spewed about the problem in the
4460 deserialization code, so just continue */
4461 continue;
4463 if (my_messages == NULL)
4464 my_messages = g_ptr_array_new ();
4465 g_ptr_array_add (my_messages, control_message);
4469 if (message->num_control_messages)
4470 *message->num_control_messages = my_messages != NULL ? my_messages->len : 0;
4472 if (message->control_messages)
4474 if (my_messages == NULL)
4476 *message->control_messages = NULL;
4478 else
4480 g_ptr_array_add (my_messages, NULL);
4481 *message->control_messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4484 else
4486 g_assert (my_messages == NULL);
4490 /* capture the flags */
4491 message->flags = msg->msg_flags;
4493 #endif
4496 * g_socket_send_message:
4497 * @socket: a #GSocket
4498 * @address: (nullable): a #GSocketAddress, or %NULL
4499 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4500 * @num_vectors: the number of elements in @vectors, or -1
4501 * @messages: (array length=num_messages) (nullable): a pointer to an
4502 * array of #GSocketControlMessages, or %NULL.
4503 * @num_messages: number of elements in @messages, or -1.
4504 * @flags: an int containing #GSocketMsgFlags flags
4505 * @cancellable: (nullable): a %GCancellable or %NULL
4506 * @error: #GError for error reporting, or %NULL to ignore.
4508 * Send data to @address on @socket. For sending multiple messages see
4509 * g_socket_send_messages(); for easier use, see
4510 * g_socket_send() and g_socket_send_to().
4512 * If @address is %NULL then the message is sent to the default receiver
4513 * (set by g_socket_connect()).
4515 * @vectors must point to an array of #GOutputVector structs and
4516 * @num_vectors must be the length of this array. (If @num_vectors is -1,
4517 * then @vectors is assumed to be terminated by a #GOutputVector with a
4518 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
4519 * that the sent data will be gathered from. Using multiple
4520 * #GOutputVectors is more memory-efficient than manually copying
4521 * data from multiple sources into a single buffer, and more
4522 * network-efficient than making multiple calls to g_socket_send().
4524 * @messages, if non-%NULL, is taken to point to an array of @num_messages
4525 * #GSocketControlMessage instances. These correspond to the control
4526 * messages to be sent on the socket.
4527 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
4528 * array.
4530 * @flags modify how the message is sent. The commonly available arguments
4531 * for this are available in the #GSocketMsgFlags enum, but the
4532 * values there are the same as the system values, and the flags
4533 * are passed in as-is, so you can pass in system-specific flags too.
4535 * If the socket is in blocking mode the call will block until there is
4536 * space for the data in the socket queue. If there is no space available
4537 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4538 * will be returned. To be notified when space is available, wait for the
4539 * %G_IO_OUT condition. Note though that you may still receive
4540 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4541 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4542 * very common due to the way the underlying APIs work.)
4544 * On error -1 is returned and @error is set accordingly.
4546 * Returns: Number of bytes written (which may be less than @size), or -1
4547 * on error
4549 * Since: 2.22
4551 gssize
4552 g_socket_send_message (GSocket *socket,
4553 GSocketAddress *address,
4554 GOutputVector *vectors,
4555 gint num_vectors,
4556 GSocketControlMessage **messages,
4557 gint num_messages,
4558 gint flags,
4559 GCancellable *cancellable,
4560 GError **error)
4562 return g_socket_send_message_with_timeout (socket, address,
4563 vectors, num_vectors,
4564 messages, num_messages, flags,
4565 socket->priv->blocking ? -1 : 0,
4566 cancellable, error);
4569 static gssize
4570 g_socket_send_message_with_timeout (GSocket *socket,
4571 GSocketAddress *address,
4572 GOutputVector *vectors,
4573 gint num_vectors,
4574 GSocketControlMessage **messages,
4575 gint num_messages,
4576 gint flags,
4577 gint64 timeout,
4578 GCancellable *cancellable,
4579 GError **error)
4581 GOutputVector one_vector;
4582 char zero;
4583 gint64 start_time;
4585 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4586 g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), -1);
4587 g_return_val_if_fail (num_vectors == 0 || vectors != NULL, -1);
4588 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
4589 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
4590 g_return_val_if_fail (error == NULL || *error == NULL, -1);
4592 start_time = g_get_monotonic_time ();
4594 if (!check_socket (socket, error))
4595 return -1;
4597 if (!check_timeout (socket, error))
4598 return -1;
4600 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4601 return -1;
4603 if (num_vectors == -1)
4605 for (num_vectors = 0;
4606 vectors[num_vectors].buffer != NULL;
4607 num_vectors++)
4611 if (num_messages == -1)
4613 for (num_messages = 0;
4614 messages != NULL && messages[num_messages] != NULL;
4615 num_messages++)
4619 if (num_vectors == 0)
4621 zero = '\0';
4623 one_vector.buffer = &zero;
4624 one_vector.size = 1;
4625 num_vectors = 1;
4626 vectors = &one_vector;
4629 #ifndef G_OS_WIN32
4631 GOutputMessage output_message;
4632 struct msghdr msg;
4633 gssize result;
4634 GError *child_error = NULL;
4636 output_message.address = address;
4637 output_message.vectors = vectors;
4638 output_message.num_vectors = num_vectors;
4639 output_message.bytes_sent = 0;
4640 output_message.control_messages = messages;
4641 output_message.num_control_messages = num_messages;
4643 output_message_to_msghdr (&output_message, NULL, &msg, NULL, &child_error);
4645 if (child_error != NULL)
4647 g_propagate_error (error, child_error);
4648 return -1;
4651 while (1)
4653 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4654 if (result < 0)
4656 int errsv = get_socket_errno ();
4658 if (errsv == EINTR)
4659 continue;
4661 if (timeout != 0 &&
4662 (errsv == EWOULDBLOCK ||
4663 errsv == EAGAIN))
4665 if (!block_on_timeout (socket, G_IO_OUT, timeout, start_time,
4666 cancellable, error))
4667 return -1;
4669 continue;
4672 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4673 return -1;
4675 break;
4678 return result;
4680 #else
4682 struct sockaddr_storage addr;
4683 guint addrlen;
4684 DWORD bytes_sent;
4685 int result;
4686 WSABUF *bufs;
4687 gint i;
4689 /* Win32 doesn't support control messages.
4690 Actually this is possible for raw and datagram sockets
4691 via WSASendMessage on Vista or later, but that doesn't
4692 seem very useful */
4693 if (num_messages != 0)
4695 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
4696 _("GSocketControlMessage not supported on Windows"));
4697 return -1;
4700 /* iov */
4701 bufs = g_newa (WSABUF, num_vectors);
4702 for (i = 0; i < num_vectors; i++)
4704 bufs[i].buf = (char *)vectors[i].buffer;
4705 bufs[i].len = (gulong)vectors[i].size;
4708 /* name */
4709 addrlen = 0; /* Avoid warning */
4710 if (address)
4712 addrlen = g_socket_address_get_native_size (address);
4713 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
4714 return -1;
4717 while (1)
4719 win32_unset_event_mask (socket, FD_WRITE);
4721 if (address)
4722 result = WSASendTo (socket->priv->fd,
4723 bufs, num_vectors,
4724 &bytes_sent, flags,
4725 (const struct sockaddr *)&addr, addrlen,
4726 NULL, NULL);
4727 else
4728 result = WSASend (socket->priv->fd,
4729 bufs, num_vectors,
4730 &bytes_sent, flags,
4731 NULL, NULL);
4733 if (result != 0)
4735 int errsv = get_socket_errno ();
4737 if (errsv == WSAEINTR)
4738 continue;
4740 if (errsv == WSAEWOULDBLOCK)
4742 if (timeout != 0)
4744 if (!block_on_timeout (socket, G_IO_OUT, timeout,
4745 start_time, cancellable, error))
4746 return -1;
4748 continue;
4752 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4753 return -1;
4755 break;
4758 return bytes_sent;
4760 #endif
4764 * g_socket_send_messages:
4765 * @socket: a #GSocket
4766 * @messages: (array length=num_messages): an array of #GOutputMessage structs
4767 * @num_messages: the number of elements in @messages
4768 * @flags: an int containing #GSocketMsgFlags flags
4769 * @cancellable: (nullable): a %GCancellable or %NULL
4770 * @error: #GError for error reporting, or %NULL to ignore.
4772 * Send multiple data messages from @socket in one go. This is the most
4773 * complicated and fully-featured version of this call. For easier use, see
4774 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
4776 * @messages must point to an array of #GOutputMessage structs and
4777 * @num_messages must be the length of this array. Each #GOutputMessage
4778 * contains an address to send the data to, and a pointer to an array of
4779 * #GOutputVector structs to describe the buffers that the data to be sent
4780 * for each message will be gathered from. Using multiple #GOutputVectors is
4781 * more memory-efficient than manually copying data from multiple sources
4782 * into a single buffer, and more network-efficient than making multiple
4783 * calls to g_socket_send(). Sending multiple messages in one go avoids the
4784 * overhead of making a lot of syscalls in scenarios where a lot of data
4785 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
4786 * or where the same data needs to be sent to multiple recipients.
4788 * @flags modify how the message is sent. The commonly available arguments
4789 * for this are available in the #GSocketMsgFlags enum, but the
4790 * values there are the same as the system values, and the flags
4791 * are passed in as-is, so you can pass in system-specific flags too.
4793 * If the socket is in blocking mode the call will block until there is
4794 * space for all the data in the socket queue. If there is no space available
4795 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4796 * will be returned if no data was written at all, otherwise the number of
4797 * messages sent will be returned. To be notified when space is available,
4798 * wait for the %G_IO_OUT condition. Note though that you may still receive
4799 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4800 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4801 * very common due to the way the underlying APIs work.)
4803 * On error -1 is returned and @error is set accordingly. An error will only
4804 * be returned if zero messages could be sent; otherwise the number of messages
4805 * successfully sent before the error will be returned.
4807 * Returns: number of messages sent, or -1 on error. Note that the number of
4808 * messages sent may be smaller than @num_messages if the socket is
4809 * non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
4810 * in which case the caller may re-try to send the remaining messages.
4812 * Since: 2.44
4814 gint
4815 g_socket_send_messages (GSocket *socket,
4816 GOutputMessage *messages,
4817 guint num_messages,
4818 gint flags,
4819 GCancellable *cancellable,
4820 GError **error)
4822 return g_socket_send_messages_with_timeout (socket, messages, num_messages,
4823 flags,
4824 socket->priv->blocking ? -1 : 0,
4825 cancellable, error);
4828 static gint
4829 g_socket_send_messages_with_timeout (GSocket *socket,
4830 GOutputMessage *messages,
4831 guint num_messages,
4832 gint flags,
4833 gint64 timeout,
4834 GCancellable *cancellable,
4835 GError **error)
4837 gint64 start_time;
4839 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4840 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
4841 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
4842 g_return_val_if_fail (error == NULL || *error == NULL, -1);
4844 start_time = g_get_monotonic_time ();
4846 if (!check_socket (socket, error))
4847 return -1;
4849 if (!check_timeout (socket, error))
4850 return -1;
4852 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4853 return -1;
4855 if (num_messages == 0)
4856 return 0;
4858 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
4860 struct mmsghdr *msgvec;
4861 gint i, num_sent;
4863 #ifdef UIO_MAXIOV
4864 #define MAX_NUM_MESSAGES UIO_MAXIOV
4865 #else
4866 #define MAX_NUM_MESSAGES 1024
4867 #endif
4869 if (num_messages > MAX_NUM_MESSAGES)
4870 num_messages = MAX_NUM_MESSAGES;
4872 msgvec = g_newa (struct mmsghdr, num_messages);
4874 for (i = 0; i < num_messages; ++i)
4876 GOutputMessage *msg = &messages[i];
4877 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
4878 GError *child_error = NULL;
4880 msgvec[i].msg_len = 0;
4882 output_message_to_msghdr (msg, (i > 0) ? &messages[i - 1] : NULL,
4883 msg_hdr, (i > 0) ? &msgvec[i - 1].msg_hdr : NULL,
4884 &child_error);
4886 if (child_error != NULL)
4888 g_propagate_error (error, child_error);
4889 return -1;
4893 for (num_sent = 0; num_sent < num_messages;)
4895 gint ret;
4897 ret = sendmmsg (socket->priv->fd, msgvec + num_sent, num_messages - num_sent,
4898 flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4900 if (ret < 0)
4902 int errsv = get_socket_errno ();
4904 if (errsv == EINTR)
4905 continue;
4907 if (timeout != 0 &&
4908 (errsv == EWOULDBLOCK ||
4909 errsv == EAGAIN))
4911 if (!block_on_timeout (socket, G_IO_OUT, timeout, start_time,
4912 cancellable, error))
4914 if (num_sent > 0)
4916 g_clear_error (error);
4917 break;
4920 return -1;
4923 continue;
4926 /* If any messages were successfully sent, do not error. */
4927 if (num_sent > 0)
4928 break;
4930 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4932 return -1;
4935 num_sent += ret;
4938 for (i = 0; i < num_sent; ++i)
4939 messages[i].bytes_sent = msgvec[i].msg_len;
4941 return num_sent;
4943 #else
4945 gssize result;
4946 gint i;
4947 gint64 wait_timeout;
4949 wait_timeout = timeout;
4951 for (i = 0; i < num_messages; ++i)
4953 GOutputMessage *msg = &messages[i];
4954 GError *msg_error = NULL;
4956 result = g_socket_send_message_with_timeout (socket, msg->address,
4957 msg->vectors,
4958 msg->num_vectors,
4959 msg->control_messages,
4960 msg->num_control_messages,
4961 flags, wait_timeout,
4962 cancellable, &msg_error);
4964 /* check if we've timed out or how much time to wait at most */
4965 if (timeout > 0)
4967 gint64 elapsed = g_get_monotonic_time () - start_time;
4968 wait_timeout = MAX (timeout - elapsed, 1);
4971 if (result < 0)
4973 /* if we couldn't send all messages, just return how many we did
4974 * manage to send, provided we managed to send at least one */
4975 if (i > 0)
4977 g_error_free (msg_error);
4978 return i;
4980 else
4982 g_propagate_error (error, msg_error);
4983 return -1;
4987 msg->bytes_sent = result;
4990 return i;
4992 #endif
4995 static GSocketAddress *
4996 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
4998 GSocketAddress *saddr;
4999 gint i;
5000 guint64 oldest_time = G_MAXUINT64;
5001 gint oldest_index = 0;
5003 if (native_len <= 0)
5004 return NULL;
5006 saddr = NULL;
5007 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
5009 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
5010 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
5011 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
5013 if (!tmp)
5014 continue;
5016 if (tmp_native_len != native_len)
5017 continue;
5019 if (memcmp (tmp_native, native, native_len) == 0)
5021 saddr = g_object_ref (tmp);
5022 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
5023 return saddr;
5026 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
5028 oldest_time = socket->priv->recv_addr_cache[i].last_used;
5029 oldest_index = i;
5033 saddr = g_socket_address_new_from_native (native, native_len);
5035 if (socket->priv->recv_addr_cache[oldest_index].addr)
5037 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
5038 g_free (socket->priv->recv_addr_cache[oldest_index].native);
5041 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
5042 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
5043 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
5044 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
5046 return saddr;
5049 static gssize
5050 g_socket_receive_message_with_timeout (GSocket *socket,
5051 GSocketAddress **address,
5052 GInputVector *vectors,
5053 gint num_vectors,
5054 GSocketControlMessage ***messages,
5055 gint *num_messages,
5056 gint *flags,
5057 gint64 timeout,
5058 GCancellable *cancellable,
5059 GError **error)
5061 GInputVector one_vector;
5062 char one_byte;
5063 gint64 start_time;
5065 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5067 start_time = g_get_monotonic_time ();
5069 if (!check_socket (socket, error))
5070 return -1;
5072 if (!check_timeout (socket, error))
5073 return -1;
5075 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5076 return -1;
5078 if (num_vectors == -1)
5080 for (num_vectors = 0;
5081 vectors[num_vectors].buffer != NULL;
5082 num_vectors++)
5086 if (num_vectors == 0)
5088 one_vector.buffer = &one_byte;
5089 one_vector.size = 1;
5090 num_vectors = 1;
5091 vectors = &one_vector;
5094 #ifndef G_OS_WIN32
5096 GInputMessage input_message;
5097 struct msghdr msg;
5098 gssize result;
5100 input_message.address = address;
5101 input_message.vectors = vectors;
5102 input_message.num_vectors = num_vectors;
5103 input_message.bytes_received = 0;
5104 input_message.flags = (flags != NULL) ? *flags : 0;
5105 input_message.control_messages = messages;
5106 input_message.num_control_messages = (guint *) num_messages;
5108 /* We always set the close-on-exec flag so we don't leak file
5109 * descriptors into child processes. Note that gunixfdmessage.c
5110 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5112 #ifdef MSG_CMSG_CLOEXEC
5113 input_message.flags |= MSG_CMSG_CLOEXEC;
5114 #endif
5116 input_message_to_msghdr (&input_message, &msg);
5118 /* do it */
5119 while (1)
5121 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5122 #ifdef MSG_CMSG_CLOEXEC
5123 if (result < 0 && get_socket_errno () == EINVAL)
5125 /* We must be running on an old kernel. Call without the flag. */
5126 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
5127 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5129 #endif
5131 if (result < 0)
5133 int errsv = get_socket_errno ();
5135 if (errsv == EINTR)
5136 continue;
5138 if (timeout != 0 &&
5139 (errsv == EWOULDBLOCK ||
5140 errsv == EAGAIN))
5142 if (!block_on_timeout (socket, G_IO_IN, timeout, start_time,
5143 cancellable, error))
5144 return -1;
5146 continue;
5149 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5150 return -1;
5152 break;
5155 input_message_from_msghdr (&msg, &input_message, socket);
5157 if (flags != NULL)
5158 *flags = input_message.flags;
5160 return result;
5162 #else
5164 struct sockaddr_storage addr;
5165 int addrlen;
5166 DWORD bytes_received;
5167 DWORD win_flags;
5168 int result;
5169 WSABUF *bufs;
5170 gint i;
5172 /* iov */
5173 bufs = g_newa (WSABUF, num_vectors);
5174 for (i = 0; i < num_vectors; i++)
5176 bufs[i].buf = (char *)vectors[i].buffer;
5177 bufs[i].len = (gulong)vectors[i].size;
5180 /* flags */
5181 if (flags != NULL)
5182 win_flags = *flags;
5183 else
5184 win_flags = 0;
5186 /* do it */
5187 while (1)
5189 win32_unset_event_mask (socket, FD_READ);
5191 addrlen = sizeof addr;
5192 if (address)
5193 result = WSARecvFrom (socket->priv->fd,
5194 bufs, num_vectors,
5195 &bytes_received, &win_flags,
5196 (struct sockaddr *)&addr, &addrlen,
5197 NULL, NULL);
5198 else
5199 result = WSARecv (socket->priv->fd,
5200 bufs, num_vectors,
5201 &bytes_received, &win_flags,
5202 NULL, NULL);
5203 if (result != 0)
5205 int errsv = get_socket_errno ();
5207 if (errsv == WSAEINTR)
5208 continue;
5210 if (errsv == WSAEWOULDBLOCK)
5212 if (timeout != 0)
5214 if (!block_on_timeout (socket, G_IO_IN, timeout,
5215 start_time, cancellable, error))
5216 return -1;
5218 continue;
5222 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5223 return -1;
5225 break;
5228 /* decode address */
5229 if (address != NULL)
5231 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
5234 /* capture the flags */
5235 if (flags != NULL)
5236 *flags = win_flags;
5238 if (messages != NULL)
5239 *messages = NULL;
5240 if (num_messages != NULL)
5241 *num_messages = 0;
5243 return bytes_received;
5245 #endif
5249 * g_socket_receive_messages:
5250 * @socket: a #GSocket
5251 * @messages: (array length=num_messages): an array of #GInputMessage structs
5252 * @num_messages: the number of elements in @messages
5253 * @flags: an int containing #GSocketMsgFlags flags for the overall operation
5254 * @cancellable: (nullable): a %GCancellable or %NULL
5255 * @error: #GError for error reporting, or %NULL to ignore
5257 * Receive multiple data messages from @socket in one go. This is the most
5258 * complicated and fully-featured version of this call. For easier use, see
5259 * g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
5261 * @messages must point to an array of #GInputMessage structs and
5262 * @num_messages must be the length of this array. Each #GInputMessage
5263 * contains a pointer to an array of #GInputVector structs describing the
5264 * buffers that the data received in each message will be written to. Using
5265 * multiple #GInputVectors is more memory-efficient than manually copying data
5266 * out of a single buffer to multiple sources, and more system-call-efficient
5267 * than making multiple calls to g_socket_receive(), such as in scenarios where
5268 * a lot of data packets need to be received (e.g. high-bandwidth video
5269 * streaming over RTP/UDP).
5271 * @flags modify how all messages are received. The commonly available
5272 * arguments for this are available in the #GSocketMsgFlags enum, but the
5273 * values there are the same as the system values, and the flags
5274 * are passed in as-is, so you can pass in system-specific flags too. These
5275 * flags affect the overall receive operation. Flags affecting individual
5276 * messages are returned in #GInputMessage.flags.
5278 * The other members of #GInputMessage are treated as described in its
5279 * documentation.
5281 * If #GSocket:blocking is %TRUE the call will block until @num_messages have
5282 * been received, or the end of the stream is reached.
5284 * If #GSocket:blocking is %FALSE the call will return up to @num_messages
5285 * without blocking, or %G_IO_ERROR_WOULD_BLOCK if no messages are queued in the
5286 * operating system to be received.
5288 * In blocking mode, if #GSocket:timeout is positive and is reached before any
5289 * messages are received, %G_IO_ERROR_TIMED_OUT is returned, otherwise up to
5290 * @num_messages are returned. (Note: This is effectively the
5291 * behaviour of `MSG_WAITFORONE` with recvmmsg().)
5293 * To be notified when messages are available, wait for the
5294 * %G_IO_IN condition. Note though that you may still receive
5295 * %G_IO_ERROR_WOULD_BLOCK from g_socket_receive_messages() even if you were
5296 * previously notified of a %G_IO_IN condition.
5298 * If the remote peer closes the connection, any messages queued in the
5299 * operating system will be returned, and subsequent calls to
5300 * g_socket_receive_messages() will return 0 (with no error set).
5302 * On error -1 is returned and @error is set accordingly. An error will only
5303 * be returned if zero messages could be received; otherwise the number of
5304 * messages successfully received before the error will be returned.
5306 * Returns: number of messages received, or -1 on error. Note that the number
5307 * of messages received may be smaller than @num_messages if in non-blocking
5308 * mode, if the peer closed the connection, or if @num_messages
5309 * was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
5310 * to receive the remaining messages.
5312 * Since: 2.48
5314 gint
5315 g_socket_receive_messages (GSocket *socket,
5316 GInputMessage *messages,
5317 guint num_messages,
5318 gint flags,
5319 GCancellable *cancellable,
5320 GError **error)
5322 if (!check_socket (socket, error) ||
5323 !check_timeout (socket, error))
5324 return -1;
5326 return g_socket_receive_messages_with_timeout (socket, messages, num_messages,
5327 flags,
5328 socket->priv->blocking ? -1 : 0,
5329 cancellable, error);
5332 static gint
5333 g_socket_receive_messages_with_timeout (GSocket *socket,
5334 GInputMessage *messages,
5335 guint num_messages,
5336 gint flags,
5337 gint64 timeout,
5338 GCancellable *cancellable,
5339 GError **error)
5341 gint64 start_time;
5343 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5344 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5345 g_return_val_if_fail (cancellable == NULL ||
5346 G_IS_CANCELLABLE (cancellable), -1);
5347 g_return_val_if_fail (error == NULL || *error == NULL, -1);
5349 start_time = g_get_monotonic_time ();
5351 if (!check_socket (socket, error))
5352 return -1;
5354 if (!check_timeout (socket, error))
5355 return -1;
5357 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5358 return -1;
5360 if (num_messages == 0)
5361 return 0;
5363 #if !defined (G_OS_WIN32) && defined (HAVE_RECVMMSG)
5365 struct mmsghdr *msgvec;
5366 guint i, num_received;
5368 #ifdef UIO_MAXIOV
5369 #define MAX_NUM_MESSAGES UIO_MAXIOV
5370 #else
5371 #define MAX_NUM_MESSAGES 1024
5372 #endif
5374 if (num_messages > MAX_NUM_MESSAGES)
5375 num_messages = MAX_NUM_MESSAGES;
5377 msgvec = g_newa (struct mmsghdr, num_messages);
5379 for (i = 0; i < num_messages; ++i)
5381 GInputMessage *msg = &messages[i];
5382 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5384 input_message_to_msghdr (msg, msg_hdr);
5385 msgvec[i].msg_len = 0;
5388 /* We always set the close-on-exec flag so we don't leak file
5389 * descriptors into child processes. Note that gunixfdmessage.c
5390 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5392 #ifdef MSG_CMSG_CLOEXEC
5393 flags |= MSG_CMSG_CLOEXEC;
5394 #endif
5396 for (num_received = 0; num_received < num_messages;)
5398 gint ret;
5400 /* We operate in non-blocking mode and handle the timeout ourselves. */
5401 ret = recvmmsg (socket->priv->fd,
5402 msgvec + num_received,
5403 num_messages - num_received,
5404 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5405 #ifdef MSG_CMSG_CLOEXEC
5406 if (ret < 0 && get_socket_errno () == EINVAL)
5408 /* We must be running on an old kernel. Call without the flag. */
5409 flags &= ~(MSG_CMSG_CLOEXEC);
5410 ret = recvmmsg (socket->priv->fd,
5411 msgvec + num_received,
5412 num_messages - num_received,
5413 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5415 #endif
5417 if (ret < 0)
5419 int errsv = get_socket_errno ();
5421 if (errsv == EINTR)
5422 continue;
5424 if (timeout != 0 &&
5425 (errsv == EWOULDBLOCK ||
5426 errsv == EAGAIN))
5428 if (!block_on_timeout (socket, G_IO_IN, timeout, start_time,
5429 cancellable, error))
5431 if (num_received > 0)
5433 g_clear_error (error);
5434 break;
5437 return -1;
5440 continue;
5443 /* If any messages were successfully received, do not error. */
5444 if (num_received > 0)
5445 break;
5447 socket_set_error_lazy (error, errsv,
5448 _("Error receiving message: %s"));
5450 return -1;
5452 else if (ret == 0)
5454 /* EOS. */
5455 break;
5458 num_received += ret;
5461 for (i = 0; i < num_received; ++i)
5463 input_message_from_msghdr (&msgvec[i].msg_hdr, &messages[i], socket);
5464 messages[i].bytes_received = msgvec[i].msg_len;
5467 return num_received;
5469 #else
5471 guint i;
5472 gint64 wait_timeout;
5474 wait_timeout = timeout;
5476 for (i = 0; i < num_messages; i++)
5478 GInputMessage *msg = &messages[i];
5479 gssize len;
5480 GError *msg_error = NULL;
5482 msg->flags = flags; /* in-out parameter */
5484 len = g_socket_receive_message_with_timeout (socket,
5485 msg->address,
5486 msg->vectors,
5487 msg->num_vectors,
5488 msg->control_messages,
5489 (gint *) msg->num_control_messages,
5490 &msg->flags,
5491 wait_timeout,
5492 cancellable,
5493 &msg_error);
5495 /* check if we've timed out or how much time to wait at most */
5496 if (timeout > 0)
5498 gint64 elapsed = g_get_monotonic_time () - start_time;
5499 wait_timeout = MAX (timeout - elapsed, 1);
5502 if (len >= 0)
5503 msg->bytes_received = len;
5505 if (i != 0 &&
5506 (g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK) ||
5507 g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)))
5509 g_clear_error (&msg_error);
5510 break;
5513 if (msg_error != NULL)
5515 g_propagate_error (error, msg_error);
5516 return -1;
5519 if (len == 0)
5520 break;
5523 return i;
5525 #endif
5529 * g_socket_receive_message:
5530 * @socket: a #GSocket
5531 * @address: (out) (optional): a pointer to a #GSocketAddress
5532 * pointer, or %NULL
5533 * @vectors: (array length=num_vectors): an array of #GInputVector structs
5534 * @num_vectors: the number of elements in @vectors, or -1
5535 * @messages: (array length=num_messages) (out) (optional) (nullable): a pointer
5536 * which may be filled with an array of #GSocketControlMessages, or %NULL
5537 * @num_messages: (out): a pointer which will be filled with the number of
5538 * elements in @messages, or %NULL
5539 * @flags: (inout): a pointer to an int containing #GSocketMsgFlags flags
5540 * @cancellable: a %GCancellable or %NULL
5541 * @error: a #GError pointer, or %NULL
5543 * Receive data from a socket. For receiving multiple messages, see
5544 * g_socket_receive_messages(); for easier use, see
5545 * g_socket_receive() and g_socket_receive_from().
5547 * If @address is non-%NULL then @address will be set equal to the
5548 * source address of the received packet.
5549 * @address is owned by the caller.
5551 * @vector must point to an array of #GInputVector structs and
5552 * @num_vectors must be the length of this array. These structs
5553 * describe the buffers that received data will be scattered into.
5554 * If @num_vectors is -1, then @vectors is assumed to be terminated
5555 * by a #GInputVector with a %NULL buffer pointer.
5557 * As a special case, if @num_vectors is 0 (in which case, @vectors
5558 * may of course be %NULL), then a single byte is received and
5559 * discarded. This is to facilitate the common practice of sending a
5560 * single '\0' byte for the purposes of transferring ancillary data.
5562 * @messages, if non-%NULL, will be set to point to a newly-allocated
5563 * array of #GSocketControlMessage instances or %NULL if no such
5564 * messages was received. These correspond to the control messages
5565 * received from the kernel, one #GSocketControlMessage per message
5566 * from the kernel. This array is %NULL-terminated and must be freed
5567 * by the caller using g_free() after calling g_object_unref() on each
5568 * element. If @messages is %NULL, any control messages received will
5569 * be discarded.
5571 * @num_messages, if non-%NULL, will be set to the number of control
5572 * messages received.
5574 * If both @messages and @num_messages are non-%NULL, then
5575 * @num_messages gives the number of #GSocketControlMessage instances
5576 * in @messages (ie: not including the %NULL terminator).
5578 * @flags is an in/out parameter. The commonly available arguments
5579 * for this are available in the #GSocketMsgFlags enum, but the
5580 * values there are the same as the system values, and the flags
5581 * are passed in as-is, so you can pass in system-specific flags too
5582 * (and g_socket_receive_message() may pass system-specific flags out).
5583 * Flags passed in to the parameter affect the receive operation; flags returned
5584 * out of it are relevant to the specific returned message.
5586 * As with g_socket_receive(), data may be discarded if @socket is
5587 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
5588 * provide enough buffer space to read a complete message. You can pass
5589 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
5590 * removing it from the receive queue, but there is no portable way to find
5591 * out the length of the message other than by reading it into a
5592 * sufficiently-large buffer.
5594 * If the socket is in blocking mode the call will block until there
5595 * is some data to receive, the connection is closed, or there is an
5596 * error. If there is no data available and the socket is in
5597 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
5598 * returned. To be notified when data is available, wait for the
5599 * %G_IO_IN condition.
5601 * On error -1 is returned and @error is set accordingly.
5603 * Returns: Number of bytes read, or 0 if the connection was closed by
5604 * the peer, or -1 on error
5606 * Since: 2.22
5608 gssize
5609 g_socket_receive_message (GSocket *socket,
5610 GSocketAddress **address,
5611 GInputVector *vectors,
5612 gint num_vectors,
5613 GSocketControlMessage ***messages,
5614 gint *num_messages,
5615 gint *flags,
5616 GCancellable *cancellable,
5617 GError **error)
5619 return g_socket_receive_message_with_timeout (socket, address, vectors,
5620 num_vectors, messages,
5621 num_messages, flags,
5622 socket->priv->blocking ? -1 : 0,
5623 cancellable, error);
5627 * g_socket_get_credentials:
5628 * @socket: a #GSocket.
5629 * @error: #GError for error reporting, or %NULL to ignore.
5631 * Returns the credentials of the foreign process connected to this
5632 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
5633 * sockets).
5635 * If this operation isn't supported on the OS, the method fails with
5636 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
5637 * by reading the %SO_PEERCRED option on the underlying socket.
5639 * Other ways to obtain credentials from a foreign peer includes the
5640 * #GUnixCredentialsMessage type and
5641 * g_unix_connection_send_credentials() /
5642 * g_unix_connection_receive_credentials() functions.
5644 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
5645 * that must be freed with g_object_unref().
5647 * Since: 2.26
5649 GCredentials *
5650 g_socket_get_credentials (GSocket *socket,
5651 GError **error)
5653 GCredentials *ret;
5655 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
5656 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5658 ret = NULL;
5660 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
5662 #ifdef SO_PEERCRED
5664 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
5665 socklen_t optlen = sizeof (native_creds_buf);
5667 if (getsockopt (socket->priv->fd,
5668 SOL_SOCKET,
5669 SO_PEERCRED,
5670 native_creds_buf,
5671 &optlen) == 0)
5673 ret = g_credentials_new ();
5674 g_credentials_set_native (ret,
5675 G_CREDENTIALS_NATIVE_TYPE,
5676 native_creds_buf);
5679 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
5681 struct unpcbid cred;
5682 socklen_t optlen = sizeof (cred);
5684 if (getsockopt (socket->priv->fd,
5686 LOCAL_PEEREID,
5687 &cred,
5688 &optlen) == 0)
5690 ret = g_credentials_new ();
5691 g_credentials_set_native (ret,
5692 G_CREDENTIALS_NATIVE_TYPE,
5693 &cred);
5696 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
5698 ucred_t *ucred = NULL;
5700 if (getpeerucred (socket->priv->fd, &ucred) == 0)
5702 ret = g_credentials_new ();
5703 g_credentials_set_native (ret,
5704 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
5705 ucred);
5706 ucred_free (ucred);
5709 #else
5710 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
5711 #endif
5713 if (!ret)
5715 int errsv = get_socket_errno ();
5717 g_set_error (error,
5718 G_IO_ERROR,
5719 socket_io_error_from_errno (errsv),
5720 _("Unable to read socket credentials: %s"),
5721 socket_strerror (errsv));
5724 #else
5726 g_set_error_literal (error,
5727 G_IO_ERROR,
5728 G_IO_ERROR_NOT_SUPPORTED,
5729 _("g_socket_get_credentials not implemented for this OS"));
5730 #endif
5732 return ret;
5736 * g_socket_get_option:
5737 * @socket: a #GSocket
5738 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5739 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5740 * @value: (out): return location for the option value
5741 * @error: #GError for error reporting, or %NULL to ignore.
5743 * Gets the value of an integer-valued option on @socket, as with
5744 * getsockopt(). (If you need to fetch a non-integer-valued option,
5745 * you will need to call getsockopt() directly.)
5747 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5748 * header pulls in system headers that will define most of the
5749 * standard/portable socket options. For unusual socket protocols or
5750 * platform-dependent options, you may need to include additional
5751 * headers.
5753 * Note that even for socket options that are a single byte in size,
5754 * @value is still a pointer to a #gint variable, not a #guchar;
5755 * g_socket_get_option() will handle the conversion internally.
5757 * Returns: success or failure. On failure, @error will be set, and
5758 * the system error value (`errno` or WSAGetLastError()) will still
5759 * be set to the result of the getsockopt() call.
5761 * Since: 2.36
5763 gboolean
5764 g_socket_get_option (GSocket *socket,
5765 gint level,
5766 gint optname,
5767 gint *value,
5768 GError **error)
5770 guint size;
5772 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
5774 *value = 0;
5775 size = sizeof (gint);
5776 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
5778 int errsv = get_socket_errno ();
5780 g_set_error_literal (error,
5781 G_IO_ERROR,
5782 socket_io_error_from_errno (errsv),
5783 socket_strerror (errsv));
5784 #ifndef G_OS_WIN32
5785 /* Reset errno in case the caller wants to look at it */
5786 errno = errsv;
5787 #endif
5788 return FALSE;
5791 #if G_BYTE_ORDER == G_BIG_ENDIAN
5792 /* If the returned value is smaller than an int then we need to
5793 * slide it over into the low-order bytes of *value.
5795 if (size != sizeof (gint))
5796 *value = *value >> (8 * (sizeof (gint) - size));
5797 #endif
5799 return TRUE;
5803 * g_socket_set_option:
5804 * @socket: a #GSocket
5805 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5806 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5807 * @value: the value to set the option to
5808 * @error: #GError for error reporting, or %NULL to ignore.
5810 * Sets the value of an integer-valued option on @socket, as with
5811 * setsockopt(). (If you need to set a non-integer-valued option,
5812 * you will need to call setsockopt() directly.)
5814 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5815 * header pulls in system headers that will define most of the
5816 * standard/portable socket options. For unusual socket protocols or
5817 * platform-dependent options, you may need to include additional
5818 * headers.
5820 * Returns: success or failure. On failure, @error will be set, and
5821 * the system error value (`errno` or WSAGetLastError()) will still
5822 * be set to the result of the setsockopt() call.
5824 * Since: 2.36
5826 gboolean
5827 g_socket_set_option (GSocket *socket,
5828 gint level,
5829 gint optname,
5830 gint value,
5831 GError **error)
5833 gint errsv;
5835 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
5837 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
5838 return TRUE;
5840 #if !defined (__linux__) && !defined (G_OS_WIN32)
5841 /* Linux and Windows let you set a single-byte value from an int,
5842 * but most other platforms don't.
5844 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
5846 #if G_BYTE_ORDER == G_BIG_ENDIAN
5847 value = value << (8 * (sizeof (gint) - 1));
5848 #endif
5849 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
5850 return TRUE;
5852 #endif
5854 errsv = get_socket_errno ();
5856 g_set_error_literal (error,
5857 G_IO_ERROR,
5858 socket_io_error_from_errno (errsv),
5859 socket_strerror (errsv));
5860 #ifndef G_OS_WIN32
5861 errno = errsv;
5862 #endif
5863 return FALSE;