genmarshal Only wrap body prototypes in C++ guards
[glib.git] / gio / gsocket.c
blobeea502cede32ee7af63bdb8e59fc0cdc88213e99
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_SYS_FILIO_H
48 # include <sys/filio.h>
49 #endif
51 #ifdef G_OS_UNIX
52 #include <sys/uio.h>
53 #endif
55 #define GOBJECT_COMPILATION
56 #include "gobject/gtype-private.h" /* For _PRELUDE type define */
57 #undef GOBJECT_COMPILATION
58 #include "gcancellable.h"
59 #include "gdatagrambased.h"
60 #include "gioenumtypes.h"
61 #include "ginetaddress.h"
62 #include "ginitable.h"
63 #include "gioerror.h"
64 #include "gioenums.h"
65 #include "gioerror.h"
66 #include "gnetworkingprivate.h"
67 #include "gsocketaddress.h"
68 #include "gsocketcontrolmessage.h"
69 #include "gcredentials.h"
70 #include "gcredentialsprivate.h"
71 #include "glibintl.h"
73 #ifdef G_OS_WIN32
74 /* For Windows XP runtime compatibility, but use the system's if_nametoindex() if available */
75 #include "gwin32networking.h"
76 #endif
78 /**
79 * SECTION:gsocket
80 * @short_description: Low-level socket object
81 * @include: gio/gio.h
82 * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
84 * A #GSocket is a low-level networking primitive. It is a more or less
85 * direct mapping of the BSD socket API in a portable GObject based API.
86 * It supports both the UNIX socket implementations and winsock2 on Windows.
88 * #GSocket is the platform independent base upon which the higher level
89 * network primitives are based. Applications are not typically meant to
90 * use it directly, but rather through classes like #GSocketClient,
91 * #GSocketService and #GSocketConnection. However there may be cases where
92 * direct use of #GSocket is useful.
94 * #GSocket implements the #GInitable interface, so if it is manually constructed
95 * by e.g. g_object_new() you must call g_initable_init() and check the
96 * results before using the object. This is done automatically in
97 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
98 * %NULL.
100 * Sockets operate in two general modes, blocking or non-blocking. When
101 * in blocking mode all operations (which don’t take an explicit blocking
102 * parameter) block until the requested operation
103 * is finished or there is an error. In non-blocking mode all calls that
104 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
105 * To know when a call would successfully run you can call g_socket_condition_check(),
106 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
107 * attach it to a #GMainContext to get callbacks when I/O is possible.
108 * Note that all sockets are always set to non blocking mode in the system, and
109 * blocking mode is emulated in GSocket.
111 * When working in non-blocking mode applications should always be able to
112 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
113 * function said that I/O was possible. This can easily happen in case
114 * of a race condition in the application, but it can also happen for other
115 * reasons. For instance, on Windows a socket is always seen as writable
116 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
118 * #GSockets can be either connection oriented or datagram based.
119 * For connection oriented types you must first establish a connection by
120 * either connecting to an address or accepting a connection from another
121 * address. For connectionless socket types the target/source address is
122 * specified or received in each I/O operation.
124 * All socket file descriptors are set to be close-on-exec.
126 * Note that creating a #GSocket causes the signal %SIGPIPE to be
127 * ignored for the remainder of the program. If you are writing a
128 * command-line utility that uses #GSocket, you may need to take into
129 * account the fact that your program will not automatically be killed
130 * if it tries to write to %stdout after it has been closed.
132 * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
133 * a #GSocket concurrently from multiple threads, you must implement your own
134 * locking.
136 * Since: 2.22
139 static void g_socket_initable_iface_init (GInitableIface *iface);
140 static gboolean g_socket_initable_init (GInitable *initable,
141 GCancellable *cancellable,
142 GError **error);
144 static void g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface);
145 static gint g_socket_datagram_based_receive_messages (GDatagramBased *self,
146 GInputMessage *messages,
147 guint num_messages,
148 gint flags,
149 gint64 timeout,
150 GCancellable *cancellable,
151 GError **error);
152 static gint g_socket_datagram_based_send_messages (GDatagramBased *self,
153 GOutputMessage *messages,
154 guint num_messages,
155 gint flags,
156 gint64 timeout,
157 GCancellable *cancellable,
158 GError **error);
159 static GSource *g_socket_datagram_based_create_source (GDatagramBased *self,
160 GIOCondition condition,
161 GCancellable *cancellable);
162 static GIOCondition g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
163 GIOCondition condition);
164 static gboolean g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
165 GIOCondition condition,
166 gint64 timeout,
167 GCancellable *cancellable,
168 GError **error);
170 static GSocketAddress *
171 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len);
173 static gssize
174 g_socket_receive_message_with_timeout (GSocket *socket,
175 GSocketAddress **address,
176 GInputVector *vectors,
177 gint num_vectors,
178 GSocketControlMessage ***messages,
179 gint *num_messages,
180 gint *flags,
181 gint64 timeout,
182 GCancellable *cancellable,
183 GError **error);
184 static gint
185 g_socket_receive_messages_with_timeout (GSocket *socket,
186 GInputMessage *messages,
187 guint num_messages,
188 gint flags,
189 gint64 timeout,
190 GCancellable *cancellable,
191 GError **error);
192 static gssize
193 g_socket_send_message_with_timeout (GSocket *socket,
194 GSocketAddress *address,
195 GOutputVector *vectors,
196 gint num_vectors,
197 GSocketControlMessage **messages,
198 gint num_messages,
199 gint flags,
200 gint64 timeout,
201 GCancellable *cancellable,
202 GError **error);
203 static gint
204 g_socket_send_messages_with_timeout (GSocket *socket,
205 GOutputMessage *messages,
206 guint num_messages,
207 gint flags,
208 gint64 timeout,
209 GCancellable *cancellable,
210 GError **error);
212 enum
214 PROP_0,
215 PROP_FAMILY,
216 PROP_TYPE,
217 PROP_PROTOCOL,
218 PROP_FD,
219 PROP_BLOCKING,
220 PROP_LISTEN_BACKLOG,
221 PROP_KEEPALIVE,
222 PROP_LOCAL_ADDRESS,
223 PROP_REMOTE_ADDRESS,
224 PROP_TIMEOUT,
225 PROP_TTL,
226 PROP_BROADCAST,
227 PROP_MULTICAST_LOOPBACK,
228 PROP_MULTICAST_TTL
231 /* Size of the receiver cache for g_socket_receive_from() */
232 #define RECV_ADDR_CACHE_SIZE 8
234 struct _GSocketPrivate
236 GSocketFamily family;
237 GSocketType type;
238 GSocketProtocol protocol;
239 gint fd;
240 gint listen_backlog;
241 guint timeout;
242 GError *construct_error;
243 GSocketAddress *remote_address;
244 guint inited : 1;
245 guint blocking : 1;
246 guint keepalive : 1;
247 guint closed : 1;
248 guint connected_read : 1;
249 guint connected_write : 1;
250 guint listening : 1;
251 guint timed_out : 1;
252 guint connect_pending : 1;
253 #ifdef G_OS_WIN32
254 WSAEVENT event;
255 gboolean waiting;
256 DWORD waiting_result;
257 int current_events;
258 int current_errors;
259 int selected_events;
260 GList *requested_conditions; /* list of requested GIOCondition * */
261 GMutex win32_source_lock;
262 GCond win32_source_cond;
263 #endif
265 struct {
266 GSocketAddress *addr;
267 struct sockaddr *native;
268 gint native_len;
269 guint64 last_used;
270 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
273 _G_DEFINE_TYPE_EXTENDED_WITH_PRELUDE (GSocket, g_socket, G_TYPE_OBJECT, 0,
274 /* Need a prelude for https://bugzilla.gnome.org/show_bug.cgi?id=674885 */
275 g_type_ensure (G_TYPE_SOCKET_FAMILY);
276 g_type_ensure (G_TYPE_SOCKET_TYPE);
277 g_type_ensure (G_TYPE_SOCKET_PROTOCOL);
278 g_type_ensure (G_TYPE_SOCKET_ADDRESS);
279 /* And networking init is appropriate for the prelude */
280 g_networking_init ();
281 , /* And now the regular type init code */
282 G_ADD_PRIVATE (GSocket)
283 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
284 g_socket_initable_iface_init);
285 G_IMPLEMENT_INTERFACE (G_TYPE_DATAGRAM_BASED,
286 g_socket_datagram_based_iface_init));
288 static int
289 get_socket_errno (void)
291 #ifndef G_OS_WIN32
292 return errno;
293 #else
294 return WSAGetLastError ();
295 #endif
298 static GIOErrorEnum
299 socket_io_error_from_errno (int err)
301 #ifdef G_OS_WIN32
302 return g_io_error_from_win32_error (err);
303 #else
304 return g_io_error_from_errno (err);
305 #endif
308 static const char *
309 socket_strerror (int err)
311 #ifndef G_OS_WIN32
312 return g_strerror (err);
313 #else
314 const char *msg_ret;
315 char *msg;
317 msg = g_win32_error_message (err);
319 msg_ret = g_intern_string (msg);
320 g_free (msg);
322 return msg_ret;
323 #endif
326 /* Wrapper around g_set_error() to avoid doing excess work */
327 #define socket_set_error_lazy(err, errsv, fmt) \
328 G_STMT_START { \
329 GError **__err = (err); \
330 int __errsv = (errsv); \
332 if (__err) \
334 int __code = socket_io_error_from_errno (__errsv); \
335 const char *__strerr = socket_strerror (__errsv); \
337 if (__code == G_IO_ERROR_WOULD_BLOCK) \
338 g_set_error_literal (__err, G_IO_ERROR, __code, __strerr); \
339 else \
340 g_set_error (__err, G_IO_ERROR, __code, fmt, __strerr); \
342 } G_STMT_END
344 #ifdef G_OS_WIN32
345 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
346 static void
347 _win32_unset_event_mask (GSocket *socket, int mask)
349 g_mutex_lock (&socket->priv->win32_source_lock);
350 socket->priv->current_events &= ~mask;
351 socket->priv->current_errors &= ~mask;
352 g_mutex_unlock (&socket->priv->win32_source_lock);
354 #else
355 #define win32_unset_event_mask(_socket, _mask)
356 #endif
358 /* Windows has broken prototypes... */
359 #ifdef G_OS_WIN32
360 #define getsockopt(sockfd, level, optname, optval, optlen) \
361 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
362 #define setsockopt(sockfd, level, optname, optval, optlen) \
363 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
364 #define getsockname(sockfd, addr, addrlen) \
365 getsockname (sockfd, addr, (int *)addrlen)
366 #define getpeername(sockfd, addr, addrlen) \
367 getpeername (sockfd, addr, (int *)addrlen)
368 #define recv(sockfd, buf, len, flags) \
369 recv (sockfd, (gpointer)buf, len, flags)
370 #endif
372 static gboolean
373 check_socket (GSocket *socket,
374 GError **error)
376 if (!socket->priv->inited)
378 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
379 _("Invalid socket, not initialized"));
380 return FALSE;
383 if (socket->priv->construct_error)
385 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
386 _("Invalid socket, initialization failed due to: %s"),
387 socket->priv->construct_error->message);
388 return FALSE;
391 if (socket->priv->closed)
393 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
394 _("Socket is already closed"));
395 return FALSE;
398 return TRUE;
401 static gboolean
402 check_timeout (GSocket *socket,
403 GError **error)
405 if (socket->priv->timed_out)
407 socket->priv->timed_out = FALSE;
408 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
409 _("Socket I/O timed out"));
410 return FALSE;
413 return TRUE;
416 static void
417 g_socket_details_from_fd (GSocket *socket)
419 struct sockaddr_storage address;
420 gint fd;
421 guint addrlen;
422 int value, family;
423 int errsv;
425 fd = socket->priv->fd;
426 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
428 errsv = get_socket_errno ();
429 goto err;
432 switch (value)
434 case SOCK_STREAM:
435 socket->priv->type = G_SOCKET_TYPE_STREAM;
436 break;
438 case SOCK_DGRAM:
439 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
440 break;
442 case SOCK_SEQPACKET:
443 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
444 break;
446 default:
447 socket->priv->type = G_SOCKET_TYPE_INVALID;
448 break;
451 addrlen = sizeof address;
452 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
454 errsv = get_socket_errno ();
455 goto err;
458 if (addrlen > 0)
460 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
461 sizeof address.ss_family <= addrlen);
462 family = address.ss_family;
464 else
466 /* On Solaris, this happens if the socket is not yet connected.
467 * But we can use SO_DOMAIN as a workaround there.
469 #ifdef SO_DOMAIN
470 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
472 errsv = get_socket_errno ();
473 goto err;
475 #else
476 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
477 errsv = -1;
478 goto err;
479 #endif
482 switch (family)
484 case G_SOCKET_FAMILY_IPV4:
485 case G_SOCKET_FAMILY_IPV6:
486 socket->priv->family = address.ss_family;
487 switch (socket->priv->type)
489 case G_SOCKET_TYPE_STREAM:
490 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
491 break;
493 case G_SOCKET_TYPE_DATAGRAM:
494 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
495 break;
497 case G_SOCKET_TYPE_SEQPACKET:
498 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
499 break;
501 default:
502 break;
504 break;
506 case G_SOCKET_FAMILY_UNIX:
507 socket->priv->family = G_SOCKET_FAMILY_UNIX;
508 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
509 break;
511 default:
512 socket->priv->family = G_SOCKET_FAMILY_INVALID;
513 break;
516 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
518 addrlen = sizeof address;
519 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
521 socket->priv->connected_read = TRUE;
522 socket->priv->connected_write = TRUE;
526 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
528 socket->priv->keepalive = !!value;
530 else
532 /* Can't read, maybe not supported, assume FALSE */
533 socket->priv->keepalive = FALSE;
536 return;
538 err:
539 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
540 socket_io_error_from_errno (errsv),
541 _("creating GSocket from fd: %s"),
542 socket_strerror (errsv));
545 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
546 gint
547 g_socket (gint domain,
548 gint type,
549 gint protocol,
550 GError **error)
552 int fd, errsv;
554 #ifdef SOCK_CLOEXEC
555 fd = socket (domain, type | SOCK_CLOEXEC, protocol);
556 errsv = errno;
557 if (fd != -1)
558 return fd;
560 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
561 if (fd < 0 && (errsv == EINVAL || errsv == EPROTOTYPE))
562 #endif
563 fd = socket (domain, type, protocol);
565 if (fd < 0)
567 int errsv = get_socket_errno ();
569 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
570 _("Unable to create socket: %s"), socket_strerror (errsv));
571 errno = errsv;
572 return -1;
575 #ifndef G_OS_WIN32
577 int flags;
579 /* We always want to set close-on-exec to protect users. If you
580 need to so some weird inheritance to exec you can re-enable this
581 using lower level hacks with g_socket_get_fd(). */
582 flags = fcntl (fd, F_GETFD, 0);
583 if (flags != -1 &&
584 (flags & FD_CLOEXEC) == 0)
586 flags |= FD_CLOEXEC;
587 fcntl (fd, F_SETFD, flags);
590 #endif
592 return fd;
595 static gint
596 g_socket_create_socket (GSocketFamily family,
597 GSocketType type,
598 int protocol,
599 GError **error)
601 gint native_type;
603 switch (type)
605 case G_SOCKET_TYPE_STREAM:
606 native_type = SOCK_STREAM;
607 break;
609 case G_SOCKET_TYPE_DATAGRAM:
610 native_type = SOCK_DGRAM;
611 break;
613 case G_SOCKET_TYPE_SEQPACKET:
614 native_type = SOCK_SEQPACKET;
615 break;
617 default:
618 g_assert_not_reached ();
621 if (family <= 0)
623 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
624 _("Unable to create socket: %s"), _("Unknown family was specified"));
625 return -1;
628 if (protocol == -1)
630 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
631 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
632 return -1;
635 return g_socket (family, native_type, protocol, error);
638 static void
639 g_socket_constructed (GObject *object)
641 GSocket *socket = G_SOCKET (object);
643 if (socket->priv->fd >= 0)
644 /* create socket->priv info from the fd */
645 g_socket_details_from_fd (socket);
647 else
648 /* create the fd from socket->priv info */
649 socket->priv->fd = g_socket_create_socket (socket->priv->family,
650 socket->priv->type,
651 socket->priv->protocol,
652 &socket->priv->construct_error);
654 if (socket->priv->fd != -1)
656 #ifndef G_OS_WIN32
657 GError *error = NULL;
658 #else
659 gulong arg;
660 #endif
662 /* Always use native nonblocking sockets, as Windows sets sockets to
663 * nonblocking automatically in certain operations. This way we make
664 * things work the same on all platforms.
666 #ifndef G_OS_WIN32
667 if (!g_unix_set_fd_nonblocking (socket->priv->fd, TRUE, &error))
669 g_warning ("Error setting socket nonblocking: %s", error->message);
670 g_clear_error (&error);
672 #else
673 arg = TRUE;
675 if (ioctlsocket (socket->priv->fd, FIONBIO, &arg) == SOCKET_ERROR)
677 int errsv = get_socket_errno ();
678 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
680 #endif
682 #ifdef SO_NOSIGPIPE
683 /* See note about SIGPIPE below. */
684 g_socket_set_option (socket, SOL_SOCKET, SO_NOSIGPIPE, TRUE, NULL);
685 #endif
689 static void
690 g_socket_get_property (GObject *object,
691 guint prop_id,
692 GValue *value,
693 GParamSpec *pspec)
695 GSocket *socket = G_SOCKET (object);
696 GSocketAddress *address;
698 switch (prop_id)
700 case PROP_FAMILY:
701 g_value_set_enum (value, socket->priv->family);
702 break;
704 case PROP_TYPE:
705 g_value_set_enum (value, socket->priv->type);
706 break;
708 case PROP_PROTOCOL:
709 g_value_set_enum (value, socket->priv->protocol);
710 break;
712 case PROP_FD:
713 g_value_set_int (value, socket->priv->fd);
714 break;
716 case PROP_BLOCKING:
717 g_value_set_boolean (value, socket->priv->blocking);
718 break;
720 case PROP_LISTEN_BACKLOG:
721 g_value_set_int (value, socket->priv->listen_backlog);
722 break;
724 case PROP_KEEPALIVE:
725 g_value_set_boolean (value, socket->priv->keepalive);
726 break;
728 case PROP_LOCAL_ADDRESS:
729 address = g_socket_get_local_address (socket, NULL);
730 g_value_take_object (value, address);
731 break;
733 case PROP_REMOTE_ADDRESS:
734 address = g_socket_get_remote_address (socket, NULL);
735 g_value_take_object (value, address);
736 break;
738 case PROP_TIMEOUT:
739 g_value_set_uint (value, socket->priv->timeout);
740 break;
742 case PROP_TTL:
743 g_value_set_uint (value, g_socket_get_ttl (socket));
744 break;
746 case PROP_BROADCAST:
747 g_value_set_boolean (value, g_socket_get_broadcast (socket));
748 break;
750 case PROP_MULTICAST_LOOPBACK:
751 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
752 break;
754 case PROP_MULTICAST_TTL:
755 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
756 break;
758 default:
759 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
763 static void
764 g_socket_set_property (GObject *object,
765 guint prop_id,
766 const GValue *value,
767 GParamSpec *pspec)
769 GSocket *socket = G_SOCKET (object);
771 switch (prop_id)
773 case PROP_FAMILY:
774 socket->priv->family = g_value_get_enum (value);
775 break;
777 case PROP_TYPE:
778 socket->priv->type = g_value_get_enum (value);
779 break;
781 case PROP_PROTOCOL:
782 socket->priv->protocol = g_value_get_enum (value);
783 break;
785 case PROP_FD:
786 socket->priv->fd = g_value_get_int (value);
787 break;
789 case PROP_BLOCKING:
790 g_socket_set_blocking (socket, g_value_get_boolean (value));
791 break;
793 case PROP_LISTEN_BACKLOG:
794 g_socket_set_listen_backlog (socket, g_value_get_int (value));
795 break;
797 case PROP_KEEPALIVE:
798 g_socket_set_keepalive (socket, g_value_get_boolean (value));
799 break;
801 case PROP_TIMEOUT:
802 g_socket_set_timeout (socket, g_value_get_uint (value));
803 break;
805 case PROP_TTL:
806 g_socket_set_ttl (socket, g_value_get_uint (value));
807 break;
809 case PROP_BROADCAST:
810 g_socket_set_broadcast (socket, g_value_get_boolean (value));
811 break;
813 case PROP_MULTICAST_LOOPBACK:
814 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
815 break;
817 case PROP_MULTICAST_TTL:
818 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
819 break;
821 default:
822 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
826 static void
827 g_socket_finalize (GObject *object)
829 GSocket *socket = G_SOCKET (object);
830 gint i;
832 g_clear_error (&socket->priv->construct_error);
834 if (socket->priv->fd != -1 &&
835 !socket->priv->closed)
836 g_socket_close (socket, NULL);
838 if (socket->priv->remote_address)
839 g_object_unref (socket->priv->remote_address);
841 #ifdef G_OS_WIN32
842 if (socket->priv->event != WSA_INVALID_EVENT)
844 WSACloseEvent (socket->priv->event);
845 socket->priv->event = WSA_INVALID_EVENT;
848 g_assert (socket->priv->requested_conditions == NULL);
849 g_mutex_clear (&socket->priv->win32_source_lock);
850 g_cond_clear (&socket->priv->win32_source_cond);
851 #endif
853 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
855 if (socket->priv->recv_addr_cache[i].addr)
857 g_object_unref (socket->priv->recv_addr_cache[i].addr);
858 g_free (socket->priv->recv_addr_cache[i].native);
862 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
863 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
866 static void
867 g_socket_class_init (GSocketClass *klass)
869 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
871 #ifdef SIGPIPE
872 /* There is no portable, thread-safe way to avoid having the process
873 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
874 * forced to simply ignore the signal process-wide.
876 * Even if we ignore it though, gdb will still stop if the app
877 * receives a SIGPIPE, which can be confusing and annoying. So when
878 * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
879 * prevent the signal from occurring at all.
881 signal (SIGPIPE, SIG_IGN);
882 #endif
884 gobject_class->finalize = g_socket_finalize;
885 gobject_class->constructed = g_socket_constructed;
886 gobject_class->set_property = g_socket_set_property;
887 gobject_class->get_property = g_socket_get_property;
889 g_object_class_install_property (gobject_class, PROP_FAMILY,
890 g_param_spec_enum ("family",
891 P_("Socket family"),
892 P_("The sockets address family"),
893 G_TYPE_SOCKET_FAMILY,
894 G_SOCKET_FAMILY_INVALID,
895 G_PARAM_CONSTRUCT_ONLY |
896 G_PARAM_READWRITE |
897 G_PARAM_STATIC_STRINGS));
899 g_object_class_install_property (gobject_class, PROP_TYPE,
900 g_param_spec_enum ("type",
901 P_("Socket type"),
902 P_("The sockets type"),
903 G_TYPE_SOCKET_TYPE,
904 G_SOCKET_TYPE_STREAM,
905 G_PARAM_CONSTRUCT_ONLY |
906 G_PARAM_READWRITE |
907 G_PARAM_STATIC_STRINGS));
909 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
910 g_param_spec_enum ("protocol",
911 P_("Socket protocol"),
912 P_("The id of the protocol to use, or -1 for unknown"),
913 G_TYPE_SOCKET_PROTOCOL,
914 G_SOCKET_PROTOCOL_UNKNOWN,
915 G_PARAM_CONSTRUCT_ONLY |
916 G_PARAM_READWRITE |
917 G_PARAM_STATIC_STRINGS));
919 g_object_class_install_property (gobject_class, PROP_FD,
920 g_param_spec_int ("fd",
921 P_("File descriptor"),
922 P_("The sockets file descriptor"),
923 G_MININT,
924 G_MAXINT,
926 G_PARAM_CONSTRUCT_ONLY |
927 G_PARAM_READWRITE |
928 G_PARAM_STATIC_STRINGS));
930 g_object_class_install_property (gobject_class, PROP_BLOCKING,
931 g_param_spec_boolean ("blocking",
932 P_("blocking"),
933 P_("Whether or not I/O on this socket is blocking"),
934 TRUE,
935 G_PARAM_READWRITE |
936 G_PARAM_STATIC_STRINGS));
938 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
939 g_param_spec_int ("listen-backlog",
940 P_("Listen backlog"),
941 P_("Outstanding connections in the listen queue"),
943 SOMAXCONN,
945 G_PARAM_READWRITE |
946 G_PARAM_STATIC_STRINGS));
948 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
949 g_param_spec_boolean ("keepalive",
950 P_("Keep connection alive"),
951 P_("Keep connection alive by sending periodic pings"),
952 FALSE,
953 G_PARAM_READWRITE |
954 G_PARAM_STATIC_STRINGS));
956 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
957 g_param_spec_object ("local-address",
958 P_("Local address"),
959 P_("The local address the socket is bound to"),
960 G_TYPE_SOCKET_ADDRESS,
961 G_PARAM_READABLE |
962 G_PARAM_STATIC_STRINGS));
964 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
965 g_param_spec_object ("remote-address",
966 P_("Remote address"),
967 P_("The remote address the socket is connected to"),
968 G_TYPE_SOCKET_ADDRESS,
969 G_PARAM_READABLE |
970 G_PARAM_STATIC_STRINGS));
973 * GSocket:timeout:
975 * The timeout in seconds on socket I/O
977 * Since: 2.26
979 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
980 g_param_spec_uint ("timeout",
981 P_("Timeout"),
982 P_("The timeout in seconds on socket I/O"),
984 G_MAXUINT,
986 G_PARAM_READWRITE |
987 G_PARAM_STATIC_STRINGS));
990 * GSocket:broadcast:
992 * Whether the socket should allow sending to broadcast addresses.
994 * Since: 2.32
996 g_object_class_install_property (gobject_class, PROP_BROADCAST,
997 g_param_spec_boolean ("broadcast",
998 P_("Broadcast"),
999 P_("Whether to allow sending to broadcast addresses"),
1000 FALSE,
1001 G_PARAM_READWRITE |
1002 G_PARAM_STATIC_STRINGS));
1005 * GSocket:ttl:
1007 * Time-to-live for outgoing unicast packets
1009 * Since: 2.32
1011 g_object_class_install_property (gobject_class, PROP_TTL,
1012 g_param_spec_uint ("ttl",
1013 P_("TTL"),
1014 P_("Time-to-live of outgoing unicast packets"),
1015 0, G_MAXUINT, 0,
1016 G_PARAM_READWRITE |
1017 G_PARAM_STATIC_STRINGS));
1020 * GSocket:multicast-loopback:
1022 * Whether outgoing multicast packets loop back to the local host.
1024 * Since: 2.32
1026 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
1027 g_param_spec_boolean ("multicast-loopback",
1028 P_("Multicast loopback"),
1029 P_("Whether outgoing multicast packets loop back to the local host"),
1030 TRUE,
1031 G_PARAM_READWRITE |
1032 G_PARAM_STATIC_STRINGS));
1035 * GSocket:multicast-ttl:
1037 * Time-to-live out outgoing multicast packets
1039 * Since: 2.32
1041 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
1042 g_param_spec_uint ("multicast-ttl",
1043 P_("Multicast TTL"),
1044 P_("Time-to-live of outgoing multicast packets"),
1045 0, G_MAXUINT, 1,
1046 G_PARAM_READWRITE |
1047 G_PARAM_STATIC_STRINGS));
1050 static void
1051 g_socket_initable_iface_init (GInitableIface *iface)
1053 iface->init = g_socket_initable_init;
1056 static void
1057 g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface)
1059 iface->receive_messages = g_socket_datagram_based_receive_messages;
1060 iface->send_messages = g_socket_datagram_based_send_messages;
1061 iface->create_source = g_socket_datagram_based_create_source;
1062 iface->condition_check = g_socket_datagram_based_condition_check;
1063 iface->condition_wait = g_socket_datagram_based_condition_wait;
1066 static void
1067 g_socket_init (GSocket *socket)
1069 socket->priv = g_socket_get_instance_private (socket);
1071 socket->priv->fd = -1;
1072 socket->priv->blocking = TRUE;
1073 socket->priv->listen_backlog = 10;
1074 socket->priv->construct_error = NULL;
1075 #ifdef G_OS_WIN32
1076 socket->priv->event = WSA_INVALID_EVENT;
1077 g_mutex_init (&socket->priv->win32_source_lock);
1078 g_cond_init (&socket->priv->win32_source_cond);
1079 #endif
1082 static gboolean
1083 g_socket_initable_init (GInitable *initable,
1084 GCancellable *cancellable,
1085 GError **error)
1087 GSocket *socket;
1089 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
1091 socket = G_SOCKET (initable);
1093 if (cancellable != NULL)
1095 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1096 _("Cancellable initialization not supported"));
1097 return FALSE;
1100 socket->priv->inited = TRUE;
1102 if (socket->priv->construct_error)
1104 if (error)
1105 *error = g_error_copy (socket->priv->construct_error);
1106 return FALSE;
1110 return TRUE;
1113 static gboolean
1114 check_datagram_based (GDatagramBased *self,
1115 GError **error)
1117 switch (g_socket_get_socket_type (G_SOCKET (self)))
1119 case G_SOCKET_TYPE_INVALID:
1120 case G_SOCKET_TYPE_STREAM:
1121 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1122 _("Cannot use datagram operations on a non-datagram "
1123 "socket."));
1124 return FALSE;
1125 case G_SOCKET_TYPE_DATAGRAM:
1126 case G_SOCKET_TYPE_SEQPACKET:
1127 /* Fall through. */
1128 break;
1131 /* Due to us sharing #GSocketSource with the #GSocket implementation, it is
1132 * pretty tricky to split out #GSocket:timeout so that it does not affect
1133 * #GDatagramBased operations (but still affects #GSocket operations). It is
1134 * not worth that effort — just disallow it and require the user to specify
1135 * timeouts on a per-operation basis. */
1136 if (g_socket_get_timeout (G_SOCKET (self)) != 0)
1138 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1139 _("Cannot use datagram operations on a socket with a "
1140 "timeout set."));
1141 return FALSE;
1144 return TRUE;
1147 static gint
1148 g_socket_datagram_based_receive_messages (GDatagramBased *self,
1149 GInputMessage *messages,
1150 guint num_messages,
1151 gint flags,
1152 gint64 timeout,
1153 GCancellable *cancellable,
1154 GError **error)
1156 if (!check_datagram_based (self, error))
1157 return FALSE;
1159 return g_socket_receive_messages_with_timeout (G_SOCKET (self), messages,
1160 num_messages, flags, timeout,
1161 cancellable, error);
1164 static gint
1165 g_socket_datagram_based_send_messages (GDatagramBased *self,
1166 GOutputMessage *messages,
1167 guint num_messages,
1168 gint flags,
1169 gint64 timeout,
1170 GCancellable *cancellable,
1171 GError **error)
1173 if (!check_datagram_based (self, error))
1174 return FALSE;
1176 return g_socket_send_messages_with_timeout (G_SOCKET (self), messages,
1177 num_messages, flags, timeout,
1178 cancellable, error);
1181 static GSource *
1182 g_socket_datagram_based_create_source (GDatagramBased *self,
1183 GIOCondition condition,
1184 GCancellable *cancellable)
1186 if (!check_datagram_based (self, NULL))
1187 return NULL;
1189 return g_socket_create_source (G_SOCKET (self), condition, cancellable);
1192 static GIOCondition
1193 g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
1194 GIOCondition condition)
1196 if (!check_datagram_based (datagram_based, NULL))
1197 return G_IO_ERR;
1199 return g_socket_condition_check (G_SOCKET (datagram_based), condition);
1202 static gboolean
1203 g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
1204 GIOCondition condition,
1205 gint64 timeout,
1206 GCancellable *cancellable,
1207 GError **error)
1209 if (!check_datagram_based (datagram_based, error))
1210 return FALSE;
1212 return g_socket_condition_timed_wait (G_SOCKET (datagram_based), condition,
1213 timeout, cancellable, error);
1217 * g_socket_new:
1218 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1219 * @type: the socket type to use.
1220 * @protocol: the id of the protocol to use, or 0 for default.
1221 * @error: #GError for error reporting, or %NULL to ignore.
1223 * Creates a new #GSocket with the defined family, type and protocol.
1224 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1225 * for the family and type is used.
1227 * The @protocol is a family and type specific int that specifies what
1228 * kind of protocol to use. #GSocketProtocol lists several common ones.
1229 * Many families only support one protocol, and use 0 for this, others
1230 * support several and using 0 means to use the default protocol for
1231 * the family and type.
1233 * The protocol id is passed directly to the operating
1234 * system, so you can use protocols not listed in #GSocketProtocol if you
1235 * know the protocol number used for it.
1237 * Returns: a #GSocket or %NULL on error.
1238 * Free the returned object with g_object_unref().
1240 * Since: 2.22
1242 GSocket *
1243 g_socket_new (GSocketFamily family,
1244 GSocketType type,
1245 GSocketProtocol protocol,
1246 GError **error)
1248 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1249 NULL, error,
1250 "family", family,
1251 "type", type,
1252 "protocol", protocol,
1253 NULL));
1257 * g_socket_new_from_fd:
1258 * @fd: a native socket file descriptor.
1259 * @error: #GError for error reporting, or %NULL to ignore.
1261 * Creates a new #GSocket from a native file descriptor
1262 * or winsock SOCKET handle.
1264 * This reads all the settings from the file descriptor so that
1265 * all properties should work. Note that the file descriptor
1266 * will be set to non-blocking mode, independent on the blocking
1267 * mode of the #GSocket.
1269 * On success, the returned #GSocket takes ownership of @fd. On failure, the
1270 * caller must close @fd themselves.
1272 * Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
1273 * descriptor. Instead, a GError will be set with code %G_IO_ERROR_FAILED
1275 * Returns: a #GSocket or %NULL on error.
1276 * Free the returned object with g_object_unref().
1278 * Since: 2.22
1280 GSocket *
1281 g_socket_new_from_fd (gint fd,
1282 GError **error)
1284 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1285 NULL, error,
1286 "fd", fd,
1287 NULL));
1291 * g_socket_set_blocking:
1292 * @socket: a #GSocket.
1293 * @blocking: Whether to use blocking I/O or not.
1295 * Sets the blocking mode of the socket. In blocking mode
1296 * all operations (which don’t take an explicit blocking parameter) block until
1297 * they succeed or there is an error. In
1298 * non-blocking mode all functions return results immediately or
1299 * with a %G_IO_ERROR_WOULD_BLOCK error.
1301 * All sockets are created in blocking mode. However, note that the
1302 * platform level socket is always non-blocking, and blocking mode
1303 * is a GSocket level feature.
1305 * Since: 2.22
1307 void
1308 g_socket_set_blocking (GSocket *socket,
1309 gboolean blocking)
1311 g_return_if_fail (G_IS_SOCKET (socket));
1313 blocking = !!blocking;
1315 if (socket->priv->blocking == blocking)
1316 return;
1318 socket->priv->blocking = blocking;
1319 g_object_notify (G_OBJECT (socket), "blocking");
1323 * g_socket_get_blocking:
1324 * @socket: a #GSocket.
1326 * Gets the blocking mode of the socket. For details on blocking I/O,
1327 * see g_socket_set_blocking().
1329 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1331 * Since: 2.22
1333 gboolean
1334 g_socket_get_blocking (GSocket *socket)
1336 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1338 return socket->priv->blocking;
1342 * g_socket_set_keepalive:
1343 * @socket: a #GSocket.
1344 * @keepalive: Value for the keepalive flag
1346 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1347 * this flag is set on a socket, the system will attempt to verify that the
1348 * remote socket endpoint is still present if a sufficiently long period of
1349 * time passes with no data being exchanged. If the system is unable to
1350 * verify the presence of the remote endpoint, it will automatically close
1351 * the connection.
1353 * This option is only functional on certain kinds of sockets. (Notably,
1354 * %G_SOCKET_PROTOCOL_TCP sockets.)
1356 * The exact time between pings is system- and protocol-dependent, but will
1357 * normally be at least two hours. Most commonly, you would set this flag
1358 * on a server socket if you want to allow clients to remain idle for long
1359 * periods of time, but also want to ensure that connections are eventually
1360 * garbage-collected if clients crash or become unreachable.
1362 * Since: 2.22
1364 void
1365 g_socket_set_keepalive (GSocket *socket,
1366 gboolean keepalive)
1368 GError *error = NULL;
1370 g_return_if_fail (G_IS_SOCKET (socket));
1372 keepalive = !!keepalive;
1373 if (socket->priv->keepalive == keepalive)
1374 return;
1376 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1377 keepalive, &error))
1379 g_warning ("error setting keepalive: %s", error->message);
1380 g_error_free (error);
1381 return;
1384 socket->priv->keepalive = keepalive;
1385 g_object_notify (G_OBJECT (socket), "keepalive");
1389 * g_socket_get_keepalive:
1390 * @socket: a #GSocket.
1392 * Gets the keepalive mode of the socket. For details on this,
1393 * see g_socket_set_keepalive().
1395 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1397 * Since: 2.22
1399 gboolean
1400 g_socket_get_keepalive (GSocket *socket)
1402 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1404 return socket->priv->keepalive;
1408 * g_socket_get_listen_backlog:
1409 * @socket: a #GSocket.
1411 * Gets the listen backlog setting of the socket. For details on this,
1412 * see g_socket_set_listen_backlog().
1414 * Returns: the maximum number of pending connections.
1416 * Since: 2.22
1418 gint
1419 g_socket_get_listen_backlog (GSocket *socket)
1421 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1423 return socket->priv->listen_backlog;
1427 * g_socket_set_listen_backlog:
1428 * @socket: a #GSocket.
1429 * @backlog: the maximum number of pending connections.
1431 * Sets the maximum number of outstanding connections allowed
1432 * when listening on this socket. If more clients than this are
1433 * connecting to the socket and the application is not handling them
1434 * on time then the new connections will be refused.
1436 * Note that this must be called before g_socket_listen() and has no
1437 * effect if called after that.
1439 * Since: 2.22
1441 void
1442 g_socket_set_listen_backlog (GSocket *socket,
1443 gint backlog)
1445 g_return_if_fail (G_IS_SOCKET (socket));
1446 g_return_if_fail (!socket->priv->listening);
1448 if (backlog != socket->priv->listen_backlog)
1450 socket->priv->listen_backlog = backlog;
1451 g_object_notify (G_OBJECT (socket), "listen-backlog");
1456 * g_socket_get_timeout:
1457 * @socket: a #GSocket.
1459 * Gets the timeout setting of the socket. For details on this, see
1460 * g_socket_set_timeout().
1462 * Returns: the timeout in seconds
1464 * Since: 2.26
1466 guint
1467 g_socket_get_timeout (GSocket *socket)
1469 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1471 return socket->priv->timeout;
1475 * g_socket_set_timeout:
1476 * @socket: a #GSocket.
1477 * @timeout: the timeout for @socket, in seconds, or 0 for none
1479 * Sets the time in seconds after which I/O operations on @socket will
1480 * time out if they have not yet completed.
1482 * On a blocking socket, this means that any blocking #GSocket
1483 * operation will time out after @timeout seconds of inactivity,
1484 * returning %G_IO_ERROR_TIMED_OUT.
1486 * On a non-blocking socket, calls to g_socket_condition_wait() will
1487 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1488 * created with g_socket_create_source() will trigger after
1489 * @timeout seconds of inactivity, with the requested condition
1490 * set, at which point calling g_socket_receive(), g_socket_send(),
1491 * g_socket_check_connect_result(), etc, will fail with
1492 * %G_IO_ERROR_TIMED_OUT.
1494 * If @timeout is 0 (the default), operations will never time out
1495 * on their own.
1497 * Note that if an I/O operation is interrupted by a signal, this may
1498 * cause the timeout to be reset.
1500 * Since: 2.26
1502 void
1503 g_socket_set_timeout (GSocket *socket,
1504 guint timeout)
1506 g_return_if_fail (G_IS_SOCKET (socket));
1508 if (timeout != socket->priv->timeout)
1510 socket->priv->timeout = timeout;
1511 g_object_notify (G_OBJECT (socket), "timeout");
1516 * g_socket_get_ttl:
1517 * @socket: a #GSocket.
1519 * Gets the unicast time-to-live setting on @socket; see
1520 * g_socket_set_ttl() for more details.
1522 * Returns: the time-to-live setting on @socket
1524 * Since: 2.32
1526 guint
1527 g_socket_get_ttl (GSocket *socket)
1529 GError *error = NULL;
1530 gint value;
1532 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1534 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1536 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1537 &value, &error);
1539 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1541 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1542 &value, &error);
1544 else
1545 g_return_val_if_reached (0);
1547 if (error)
1549 g_warning ("error getting unicast ttl: %s", error->message);
1550 g_error_free (error);
1551 return 0;
1554 return value;
1558 * g_socket_set_ttl:
1559 * @socket: a #GSocket.
1560 * @ttl: the time-to-live value for all unicast packets on @socket
1562 * Sets the time-to-live for outgoing unicast packets on @socket.
1563 * By default the platform-specific default value is used.
1565 * Since: 2.32
1567 void
1568 g_socket_set_ttl (GSocket *socket,
1569 guint ttl)
1571 GError *error = NULL;
1573 g_return_if_fail (G_IS_SOCKET (socket));
1575 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1577 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1578 ttl, &error);
1580 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1582 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1583 ttl, NULL);
1584 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1585 ttl, &error);
1587 else
1588 g_return_if_reached ();
1590 if (error)
1592 g_warning ("error setting unicast ttl: %s", error->message);
1593 g_error_free (error);
1594 return;
1597 g_object_notify (G_OBJECT (socket), "ttl");
1601 * g_socket_get_broadcast:
1602 * @socket: a #GSocket.
1604 * Gets the broadcast setting on @socket; if %TRUE,
1605 * it is possible to send packets to broadcast
1606 * addresses.
1608 * Returns: the broadcast setting on @socket
1610 * Since: 2.32
1612 gboolean
1613 g_socket_get_broadcast (GSocket *socket)
1615 GError *error = NULL;
1616 gint value;
1618 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1620 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1621 &value, &error))
1623 g_warning ("error getting broadcast: %s", error->message);
1624 g_error_free (error);
1625 return FALSE;
1628 return !!value;
1632 * g_socket_set_broadcast:
1633 * @socket: a #GSocket.
1634 * @broadcast: whether @socket should allow sending to broadcast
1635 * addresses
1637 * Sets whether @socket should allow sending to broadcast addresses.
1638 * This is %FALSE by default.
1640 * Since: 2.32
1642 void
1643 g_socket_set_broadcast (GSocket *socket,
1644 gboolean broadcast)
1646 GError *error = NULL;
1648 g_return_if_fail (G_IS_SOCKET (socket));
1650 broadcast = !!broadcast;
1652 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1653 broadcast, &error))
1655 g_warning ("error setting broadcast: %s", error->message);
1656 g_error_free (error);
1657 return;
1660 g_object_notify (G_OBJECT (socket), "broadcast");
1664 * g_socket_get_multicast_loopback:
1665 * @socket: a #GSocket.
1667 * Gets the multicast loopback setting on @socket; if %TRUE (the
1668 * default), outgoing multicast packets will be looped back to
1669 * multicast listeners on the same host.
1671 * Returns: the multicast loopback setting on @socket
1673 * Since: 2.32
1675 gboolean
1676 g_socket_get_multicast_loopback (GSocket *socket)
1678 GError *error = NULL;
1679 gint value;
1681 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1683 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1685 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1686 &value, &error);
1688 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1690 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1691 &value, &error);
1693 else
1694 g_return_val_if_reached (FALSE);
1696 if (error)
1698 g_warning ("error getting multicast loopback: %s", error->message);
1699 g_error_free (error);
1700 return FALSE;
1703 return !!value;
1707 * g_socket_set_multicast_loopback:
1708 * @socket: a #GSocket.
1709 * @loopback: whether @socket should receive messages sent to its
1710 * multicast groups from the local host
1712 * Sets whether outgoing multicast packets will be received by sockets
1713 * listening on that multicast address on the same host. This is %TRUE
1714 * by default.
1716 * Since: 2.32
1718 void
1719 g_socket_set_multicast_loopback (GSocket *socket,
1720 gboolean loopback)
1722 GError *error = NULL;
1724 g_return_if_fail (G_IS_SOCKET (socket));
1726 loopback = !!loopback;
1728 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1730 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1731 loopback, &error);
1733 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1735 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1736 loopback, NULL);
1737 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1738 loopback, &error);
1740 else
1741 g_return_if_reached ();
1743 if (error)
1745 g_warning ("error setting multicast loopback: %s", error->message);
1746 g_error_free (error);
1747 return;
1750 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1754 * g_socket_get_multicast_ttl:
1755 * @socket: a #GSocket.
1757 * Gets the multicast time-to-live setting on @socket; see
1758 * g_socket_set_multicast_ttl() for more details.
1760 * Returns: the multicast time-to-live setting on @socket
1762 * Since: 2.32
1764 guint
1765 g_socket_get_multicast_ttl (GSocket *socket)
1767 GError *error = NULL;
1768 gint value;
1770 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1772 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1774 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1775 &value, &error);
1777 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1779 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1780 &value, &error);
1782 else
1783 g_return_val_if_reached (FALSE);
1785 if (error)
1787 g_warning ("error getting multicast ttl: %s", error->message);
1788 g_error_free (error);
1789 return FALSE;
1792 return value;
1796 * g_socket_set_multicast_ttl:
1797 * @socket: a #GSocket.
1798 * @ttl: the time-to-live value for all multicast datagrams on @socket
1800 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1801 * By default, this is 1, meaning that multicast packets will not leave
1802 * the local network.
1804 * Since: 2.32
1806 void
1807 g_socket_set_multicast_ttl (GSocket *socket,
1808 guint ttl)
1810 GError *error = NULL;
1812 g_return_if_fail (G_IS_SOCKET (socket));
1814 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1816 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1817 ttl, &error);
1819 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1821 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1822 ttl, NULL);
1823 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1824 ttl, &error);
1826 else
1827 g_return_if_reached ();
1829 if (error)
1831 g_warning ("error setting multicast ttl: %s", error->message);
1832 g_error_free (error);
1833 return;
1836 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1840 * g_socket_get_family:
1841 * @socket: a #GSocket.
1843 * Gets the socket family of the socket.
1845 * Returns: a #GSocketFamily
1847 * Since: 2.22
1849 GSocketFamily
1850 g_socket_get_family (GSocket *socket)
1852 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1854 return socket->priv->family;
1858 * g_socket_get_socket_type:
1859 * @socket: a #GSocket.
1861 * Gets the socket type of the socket.
1863 * Returns: a #GSocketType
1865 * Since: 2.22
1867 GSocketType
1868 g_socket_get_socket_type (GSocket *socket)
1870 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1872 return socket->priv->type;
1876 * g_socket_get_protocol:
1877 * @socket: a #GSocket.
1879 * Gets the socket protocol id the socket was created with.
1880 * In case the protocol is unknown, -1 is returned.
1882 * Returns: a protocol id, or -1 if unknown
1884 * Since: 2.22
1886 GSocketProtocol
1887 g_socket_get_protocol (GSocket *socket)
1889 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1891 return socket->priv->protocol;
1895 * g_socket_get_fd:
1896 * @socket: a #GSocket.
1898 * Returns the underlying OS socket object. On unix this
1899 * is a socket file descriptor, and on Windows this is
1900 * a Winsock2 SOCKET handle. This may be useful for
1901 * doing platform specific or otherwise unusual operations
1902 * on the socket.
1904 * Returns: the file descriptor of the socket.
1906 * Since: 2.22
1909 g_socket_get_fd (GSocket *socket)
1911 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1913 return socket->priv->fd;
1917 * g_socket_get_local_address:
1918 * @socket: a #GSocket.
1919 * @error: #GError for error reporting, or %NULL to ignore.
1921 * Try to get the local address of a bound socket. This is only
1922 * useful if the socket has been bound to a local address,
1923 * either explicitly or implicitly when connecting.
1925 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1926 * Free the returned object with g_object_unref().
1928 * Since: 2.22
1930 GSocketAddress *
1931 g_socket_get_local_address (GSocket *socket,
1932 GError **error)
1934 struct sockaddr_storage buffer;
1935 guint len = sizeof (buffer);
1937 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1939 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1941 int errsv = get_socket_errno ();
1942 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1943 _("could not get local address: %s"), socket_strerror (errsv));
1944 return NULL;
1947 return g_socket_address_new_from_native (&buffer, len);
1951 * g_socket_get_remote_address:
1952 * @socket: a #GSocket.
1953 * @error: #GError for error reporting, or %NULL to ignore.
1955 * Try to get the remove address of a connected socket. This is only
1956 * useful for connection oriented sockets that have been connected.
1958 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1959 * Free the returned object with g_object_unref().
1961 * Since: 2.22
1963 GSocketAddress *
1964 g_socket_get_remote_address (GSocket *socket,
1965 GError **error)
1967 struct sockaddr_storage buffer;
1968 guint len = sizeof (buffer);
1970 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1972 if (socket->priv->connect_pending)
1974 if (!g_socket_check_connect_result (socket, error))
1975 return NULL;
1976 else
1977 socket->priv->connect_pending = FALSE;
1980 if (!socket->priv->remote_address)
1982 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1984 int errsv = get_socket_errno ();
1985 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1986 _("could not get remote address: %s"), socket_strerror (errsv));
1987 return NULL;
1990 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1993 return g_object_ref (socket->priv->remote_address);
1997 * g_socket_is_connected:
1998 * @socket: a #GSocket.
2000 * Check whether the socket is connected. This is only useful for
2001 * connection-oriented sockets.
2003 * If using g_socket_shutdown(), this function will return %TRUE until the
2004 * socket has been shut down for reading and writing. If you do a non-blocking
2005 * connect, this function will not return %TRUE until after you call
2006 * g_socket_check_connect_result().
2008 * Returns: %TRUE if socket is connected, %FALSE otherwise.
2010 * Since: 2.22
2012 gboolean
2013 g_socket_is_connected (GSocket *socket)
2015 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2017 return (socket->priv->connected_read || socket->priv->connected_write);
2021 * g_socket_listen:
2022 * @socket: a #GSocket.
2023 * @error: #GError for error reporting, or %NULL to ignore.
2025 * Marks the socket as a server socket, i.e. a socket that is used
2026 * to accept incoming requests using g_socket_accept().
2028 * Before calling this the socket must be bound to a local address using
2029 * g_socket_bind().
2031 * To set the maximum amount of outstanding clients, use
2032 * g_socket_set_listen_backlog().
2034 * Returns: %TRUE on success, %FALSE on error.
2036 * Since: 2.22
2038 gboolean
2039 g_socket_listen (GSocket *socket,
2040 GError **error)
2042 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2044 if (!check_socket (socket, error))
2045 return FALSE;
2047 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
2049 int errsv = get_socket_errno ();
2051 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2052 _("could not listen: %s"), socket_strerror (errsv));
2053 return FALSE;
2056 socket->priv->listening = TRUE;
2058 return TRUE;
2062 * g_socket_bind:
2063 * @socket: a #GSocket.
2064 * @address: a #GSocketAddress specifying the local address.
2065 * @allow_reuse: whether to allow reusing this address
2066 * @error: #GError for error reporting, or %NULL to ignore.
2068 * When a socket is created it is attached to an address family, but it
2069 * doesn't have an address in this family. g_socket_bind() assigns the
2070 * address (sometimes called name) of the socket.
2072 * It is generally required to bind to a local address before you can
2073 * receive connections. (See g_socket_listen() and g_socket_accept() ).
2074 * In certain situations, you may also want to bind a socket that will be
2075 * used to initiate connections, though this is not normally required.
2077 * If @socket is a TCP socket, then @allow_reuse controls the setting
2078 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
2079 * server sockets (sockets that you will eventually call
2080 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
2081 * set this flag on a server socket may cause g_socket_bind() to return
2082 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
2083 * immediately restarted.)
2085 * If @socket is a UDP socket, then @allow_reuse determines whether or
2086 * not other UDP sockets can be bound to the same address at the same
2087 * time. In particular, you can have several UDP sockets bound to the
2088 * same address, and they will all receive all of the multicast and
2089 * broadcast packets sent to that address. (The behavior of unicast
2090 * UDP packets to an address with multiple listeners is not defined.)
2092 * Returns: %TRUE on success, %FALSE on error.
2094 * Since: 2.22
2096 gboolean
2097 g_socket_bind (GSocket *socket,
2098 GSocketAddress *address,
2099 gboolean reuse_address,
2100 GError **error)
2102 struct sockaddr_storage addr;
2103 gboolean so_reuseaddr;
2104 #ifdef SO_REUSEPORT
2105 gboolean so_reuseport;
2106 #endif
2108 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2110 if (!check_socket (socket, error))
2111 return FALSE;
2113 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2114 return FALSE;
2116 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
2117 * sockets, but has nasty side effects we don't want for TCP
2118 * sockets.
2120 * On other platforms, we set SO_REUSEPORT, if it exists, for
2121 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
2122 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
2123 * the desired semantics on UDP (as it does on Linux, although
2124 * Linux has SO_REUSEPORT too as of 3.9).
2127 #ifdef G_OS_WIN32
2128 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2129 #else
2130 so_reuseaddr = !!reuse_address;
2131 #endif
2133 #ifdef SO_REUSEPORT
2134 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2135 #endif
2137 /* Ignore errors here, the only likely error is "not supported", and
2138 * this is a "best effort" thing mainly.
2140 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
2141 #ifdef SO_REUSEPORT
2142 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
2143 #endif
2145 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
2146 g_socket_address_get_native_size (address)) < 0)
2148 int errsv = get_socket_errno ();
2149 g_set_error (error,
2150 G_IO_ERROR, socket_io_error_from_errno (errsv),
2151 _("Error binding to address: %s"), socket_strerror (errsv));
2152 return FALSE;
2155 return TRUE;
2158 #if !defined(HAVE_IF_NAMETOINDEX) && defined(G_OS_WIN32)
2159 static guint
2160 if_nametoindex (const gchar *iface)
2162 PIP_ADAPTER_ADDRESSES addresses = NULL, p;
2163 gulong addresses_len = 0;
2164 guint idx = 0;
2165 DWORD res;
2167 if (ws2funcs.pIfNameToIndex != NULL)
2168 return ws2funcs.pIfNameToIndex (iface);
2170 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, NULL, &addresses_len);
2171 if (res != NO_ERROR && res != ERROR_BUFFER_OVERFLOW)
2173 if (res == ERROR_NO_DATA)
2174 errno = ENXIO;
2175 else
2176 errno = EINVAL;
2177 return 0;
2180 addresses = g_malloc (addresses_len);
2181 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, addresses, &addresses_len);
2183 if (res != NO_ERROR)
2185 g_free (addresses);
2186 if (res == ERROR_NO_DATA)
2187 errno = ENXIO;
2188 else
2189 errno = EINVAL;
2190 return 0;
2193 p = addresses;
2194 while (p)
2196 if (strcmp (p->AdapterName, iface) == 0)
2198 idx = p->IfIndex;
2199 break;
2201 p = p->Next;
2204 if (p == NULL)
2205 errno = ENXIO;
2207 g_free (addresses);
2209 return idx;
2212 #define HAVE_IF_NAMETOINDEX 1
2213 #endif
2215 static gboolean
2216 g_socket_multicast_group_operation (GSocket *socket,
2217 GInetAddress *group,
2218 gboolean source_specific,
2219 const gchar *iface,
2220 gboolean join_group,
2221 GError **error)
2223 const guint8 *native_addr;
2224 gint optname, result;
2226 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2227 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2228 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2230 if (!check_socket (socket, error))
2231 return FALSE;
2233 native_addr = g_inet_address_to_bytes (group);
2234 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2236 #ifdef HAVE_IP_MREQN
2237 struct ip_mreqn mc_req;
2238 #else
2239 struct ip_mreq mc_req;
2240 #endif
2242 memset (&mc_req, 0, sizeof (mc_req));
2243 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2245 #ifdef HAVE_IP_MREQN
2246 if (iface)
2247 mc_req.imr_ifindex = if_nametoindex (iface);
2248 else
2249 mc_req.imr_ifindex = 0; /* Pick any. */
2250 #elif defined(G_OS_WIN32)
2251 if (iface)
2252 mc_req.imr_interface.s_addr = g_htonl (if_nametoindex (iface));
2253 else
2254 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2255 #else
2256 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2257 #endif
2259 if (source_specific)
2261 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2262 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2263 #else
2264 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2265 join_group ?
2266 _("Error joining multicast group: %s") :
2267 _("Error leaving multicast group: %s"),
2268 _("No support for source-specific multicast"));
2269 return FALSE;
2270 #endif
2272 else
2273 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2274 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2275 &mc_req, sizeof (mc_req));
2277 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2279 struct ipv6_mreq mc_req_ipv6;
2281 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2282 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2283 #ifdef HAVE_IF_NAMETOINDEX
2284 if (iface)
2285 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2286 else
2287 #endif
2288 mc_req_ipv6.ipv6mr_interface = 0;
2290 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2291 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2292 &mc_req_ipv6, sizeof (mc_req_ipv6));
2294 else
2295 g_return_val_if_reached (FALSE);
2297 if (result < 0)
2299 int errsv = get_socket_errno ();
2301 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2302 join_group ?
2303 _("Error joining multicast group: %s") :
2304 _("Error leaving multicast group: %s"),
2305 socket_strerror (errsv));
2306 return FALSE;
2309 return TRUE;
2313 * g_socket_join_multicast_group:
2314 * @socket: a #GSocket.
2315 * @group: a #GInetAddress specifying the group address to join.
2316 * @iface: (nullable): Name of the interface to use, or %NULL
2317 * @source_specific: %TRUE if source-specific multicast should be used
2318 * @error: #GError for error reporting, or %NULL to ignore.
2320 * Registers @socket to receive multicast messages sent to @group.
2321 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2322 * been bound to an appropriate interface and port with
2323 * g_socket_bind().
2325 * If @iface is %NULL, the system will automatically pick an interface
2326 * to bind to based on @group.
2328 * If @source_specific is %TRUE, source-specific multicast as defined
2329 * in RFC 4604 is used. Note that on older platforms this may fail
2330 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2332 * Returns: %TRUE on success, %FALSE on error.
2334 * Since: 2.32
2336 gboolean
2337 g_socket_join_multicast_group (GSocket *socket,
2338 GInetAddress *group,
2339 gboolean source_specific,
2340 const gchar *iface,
2341 GError **error)
2343 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2347 * g_socket_leave_multicast_group:
2348 * @socket: a #GSocket.
2349 * @group: a #GInetAddress specifying the group address to leave.
2350 * @iface: (nullable): Interface used
2351 * @source_specific: %TRUE if source-specific multicast was used
2352 * @error: #GError for error reporting, or %NULL to ignore.
2354 * Removes @socket from the multicast group defined by @group, @iface,
2355 * and @source_specific (which must all have the same values they had
2356 * when you joined the group).
2358 * @socket remains bound to its address and port, and can still receive
2359 * unicast messages after calling this.
2361 * Returns: %TRUE on success, %FALSE on error.
2363 * Since: 2.32
2365 gboolean
2366 g_socket_leave_multicast_group (GSocket *socket,
2367 GInetAddress *group,
2368 gboolean source_specific,
2369 const gchar *iface,
2370 GError **error)
2372 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2376 * g_socket_speaks_ipv4:
2377 * @socket: a #GSocket
2379 * Checks if a socket is capable of speaking IPv4.
2381 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2382 * and under some combinations of circumstances IPv6 sockets are also
2383 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2384 * information.
2386 * No other types of sockets are currently considered as being capable
2387 * of speaking IPv4.
2389 * Returns: %TRUE if this socket can be used with IPv4.
2391 * Since: 2.22
2393 gboolean
2394 g_socket_speaks_ipv4 (GSocket *socket)
2396 switch (socket->priv->family)
2398 case G_SOCKET_FAMILY_IPV4:
2399 return TRUE;
2401 case G_SOCKET_FAMILY_IPV6:
2402 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2404 gint v6_only;
2406 if (!g_socket_get_option (socket,
2407 IPPROTO_IPV6, IPV6_V6ONLY,
2408 &v6_only, NULL))
2409 return FALSE;
2411 return !v6_only;
2413 #else
2414 return FALSE;
2415 #endif
2417 default:
2418 return FALSE;
2423 * g_socket_accept:
2424 * @socket: a #GSocket.
2425 * @cancellable: (nullable): a %GCancellable or %NULL
2426 * @error: #GError for error reporting, or %NULL to ignore.
2428 * Accept incoming connections on a connection-based socket. This removes
2429 * the first outstanding connection request from the listening socket and
2430 * creates a #GSocket object for it.
2432 * The @socket must be bound to a local address with g_socket_bind() and
2433 * must be listening for incoming connections (g_socket_listen()).
2435 * If there are no outstanding connections then the operation will block
2436 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2437 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2439 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2440 * Free the returned object with g_object_unref().
2442 * Since: 2.22
2444 GSocket *
2445 g_socket_accept (GSocket *socket,
2446 GCancellable *cancellable,
2447 GError **error)
2449 GSocket *new_socket;
2450 gint ret;
2452 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2454 if (!check_socket (socket, error))
2455 return NULL;
2457 if (!check_timeout (socket, error))
2458 return NULL;
2460 while (TRUE)
2462 win32_unset_event_mask (socket, FD_ACCEPT);
2464 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2466 int errsv = get_socket_errno ();
2468 if (errsv == EINTR)
2469 continue;
2471 #ifdef WSAEWOULDBLOCK
2472 if (errsv == WSAEWOULDBLOCK)
2473 #else
2474 if (errsv == EWOULDBLOCK ||
2475 errsv == EAGAIN)
2476 #endif
2478 if (socket->priv->blocking)
2480 if (!g_socket_condition_wait (socket,
2481 G_IO_IN, cancellable, error))
2482 return NULL;
2484 continue;
2488 socket_set_error_lazy (error, errsv, _("Error accepting connection: %s"));
2489 return NULL;
2491 break;
2494 #ifdef G_OS_WIN32
2496 /* The socket inherits the accepting sockets event mask and even object,
2497 we need to remove that */
2498 WSAEventSelect (ret, NULL, 0);
2500 #else
2502 int flags;
2504 /* We always want to set close-on-exec to protect users. If you
2505 need to so some weird inheritance to exec you can re-enable this
2506 using lower level hacks with g_socket_get_fd(). */
2507 flags = fcntl (ret, F_GETFD, 0);
2508 if (flags != -1 &&
2509 (flags & FD_CLOEXEC) == 0)
2511 flags |= FD_CLOEXEC;
2512 fcntl (ret, F_SETFD, flags);
2515 #endif
2517 new_socket = g_socket_new_from_fd (ret, error);
2518 if (new_socket == NULL)
2520 #ifdef G_OS_WIN32
2521 closesocket (ret);
2522 #else
2523 close (ret);
2524 #endif
2526 else
2527 new_socket->priv->protocol = socket->priv->protocol;
2529 return new_socket;
2533 * g_socket_connect:
2534 * @socket: a #GSocket.
2535 * @address: a #GSocketAddress specifying the remote address.
2536 * @cancellable: (nullable): a %GCancellable or %NULL
2537 * @error: #GError for error reporting, or %NULL to ignore.
2539 * Connect the socket to the specified remote address.
2541 * For connection oriented socket this generally means we attempt to make
2542 * a connection to the @address. For a connection-less socket it sets
2543 * the default address for g_socket_send() and discards all incoming datagrams
2544 * from other sources.
2546 * Generally connection oriented sockets can only connect once, but
2547 * connection-less sockets can connect multiple times to change the
2548 * default address.
2550 * If the connect call needs to do network I/O it will block, unless
2551 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2552 * and the user can be notified of the connection finishing by waiting
2553 * for the G_IO_OUT condition. The result of the connection must then be
2554 * checked with g_socket_check_connect_result().
2556 * Returns: %TRUE if connected, %FALSE on error.
2558 * Since: 2.22
2560 gboolean
2561 g_socket_connect (GSocket *socket,
2562 GSocketAddress *address,
2563 GCancellable *cancellable,
2564 GError **error)
2566 struct sockaddr_storage buffer;
2568 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2570 if (!check_socket (socket, error))
2571 return FALSE;
2573 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2574 return FALSE;
2576 if (socket->priv->remote_address)
2577 g_object_unref (socket->priv->remote_address);
2578 socket->priv->remote_address = g_object_ref (address);
2580 while (1)
2582 win32_unset_event_mask (socket, FD_CONNECT);
2584 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2585 g_socket_address_get_native_size (address)) < 0)
2587 int errsv = get_socket_errno ();
2589 if (errsv == EINTR)
2590 continue;
2592 #ifndef G_OS_WIN32
2593 if (errsv == EINPROGRESS)
2594 #else
2595 if (errsv == WSAEWOULDBLOCK)
2596 #endif
2598 if (socket->priv->blocking)
2600 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2602 if (g_socket_check_connect_result (socket, error))
2603 break;
2606 else
2608 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2609 _("Connection in progress"));
2610 socket->priv->connect_pending = TRUE;
2613 else
2614 g_set_error_literal (error, G_IO_ERROR,
2615 socket_io_error_from_errno (errsv),
2616 socket_strerror (errsv));
2618 return FALSE;
2620 break;
2623 socket->priv->connected_read = TRUE;
2624 socket->priv->connected_write = TRUE;
2626 return TRUE;
2630 * g_socket_check_connect_result:
2631 * @socket: a #GSocket
2632 * @error: #GError for error reporting, or %NULL to ignore.
2634 * Checks and resets the pending connect error for the socket.
2635 * This is used to check for errors when g_socket_connect() is
2636 * used in non-blocking mode.
2638 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2640 * Since: 2.22
2642 gboolean
2643 g_socket_check_connect_result (GSocket *socket,
2644 GError **error)
2646 int value;
2648 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2650 if (!check_socket (socket, error))
2651 return FALSE;
2653 if (!check_timeout (socket, error))
2654 return FALSE;
2656 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
2658 g_prefix_error (error, _("Unable to get pending error: "));
2659 return FALSE;
2662 if (value != 0)
2664 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2665 socket_strerror (value));
2666 if (socket->priv->remote_address)
2668 g_object_unref (socket->priv->remote_address);
2669 socket->priv->remote_address = NULL;
2671 return FALSE;
2674 socket->priv->connected_read = TRUE;
2675 socket->priv->connected_write = TRUE;
2677 return TRUE;
2681 * g_socket_get_available_bytes:
2682 * @socket: a #GSocket
2684 * Get the amount of data pending in the OS input buffer, without blocking.
2686 * If @socket is a UDP or SCTP socket, this will return the size of
2687 * just the next packet, even if additional packets are buffered after
2688 * that one.
2690 * Note that on Windows, this function is rather inefficient in the
2691 * UDP case, and so if you know any plausible upper bound on the size
2692 * of the incoming packet, it is better to just do a
2693 * g_socket_receive() with a buffer of that size, rather than calling
2694 * g_socket_get_available_bytes() first and then doing a receive of
2695 * exactly the right size.
2697 * Returns: the number of bytes that can be read from the socket
2698 * without blocking or truncating, or -1 on error.
2700 * Since: 2.32
2702 gssize
2703 g_socket_get_available_bytes (GSocket *socket)
2705 #ifdef G_OS_WIN32
2706 const gint bufsize = 64 * 1024;
2707 static guchar *buf = NULL;
2708 u_long avail;
2709 #else
2710 gint avail;
2711 #endif
2713 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2715 #if defined (SO_NREAD)
2716 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
2717 return -1;
2718 #elif !defined (G_OS_WIN32)
2719 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2720 avail = -1;
2721 #else
2722 if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
2724 if (G_UNLIKELY (g_once_init_enter (&buf)))
2725 g_once_init_leave (&buf, g_malloc (bufsize));
2727 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
2728 if (avail == -1 && get_socket_errno () == WSAEWOULDBLOCK)
2729 avail = 0;
2731 else
2733 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
2734 avail = -1;
2736 #endif
2738 return avail;
2741 /* Block on a timed wait for @condition until (@start_time + @timeout).
2742 * Return %G_IO_ERROR_TIMED_OUT if the timeout is reached; otherwise %TRUE.
2744 static gboolean
2745 block_on_timeout (GSocket *socket,
2746 GIOCondition condition,
2747 gint64 timeout,
2748 gint64 start_time,
2749 GCancellable *cancellable,
2750 GError **error)
2752 gint64 wait_timeout = -1;
2754 g_return_val_if_fail (timeout != 0, TRUE);
2756 /* check if we've timed out or how much time to wait at most */
2757 if (timeout >= 0)
2759 gint64 elapsed = g_get_monotonic_time () - start_time;
2761 if (elapsed >= timeout)
2763 g_set_error_literal (error,
2764 G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2765 _("Socket I/O timed out"));
2766 return FALSE;
2769 wait_timeout = timeout - elapsed;
2772 return g_socket_condition_timed_wait (socket, condition, wait_timeout,
2773 cancellable, error);
2776 static gssize
2777 g_socket_receive_with_timeout (GSocket *socket,
2778 guint8 *buffer,
2779 gsize size,
2780 gint64 timeout,
2781 GCancellable *cancellable,
2782 GError **error)
2784 gssize ret;
2785 gint64 start_time;
2787 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2789 start_time = g_get_monotonic_time ();
2791 if (!check_socket (socket, error))
2792 return -1;
2794 if (!check_timeout (socket, error))
2795 return -1;
2797 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2798 return -1;
2800 while (1)
2802 win32_unset_event_mask (socket, FD_READ);
2804 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2806 int errsv = get_socket_errno ();
2808 if (errsv == EINTR)
2809 continue;
2811 #ifdef WSAEWOULDBLOCK
2812 if (errsv == WSAEWOULDBLOCK)
2813 #else
2814 if (errsv == EWOULDBLOCK ||
2815 errsv == EAGAIN)
2816 #endif
2818 if (timeout != 0)
2820 if (!block_on_timeout (socket, G_IO_IN, timeout, start_time,
2821 cancellable, error))
2822 return -1;
2824 continue;
2828 socket_set_error_lazy (error, errsv, _("Error receiving data: %s"));
2829 return -1;
2832 break;
2835 return ret;
2839 * g_socket_receive:
2840 * @socket: a #GSocket
2841 * @buffer: (array length=size) (element-type guint8): a buffer to
2842 * read data into (which should be at least @size bytes long).
2843 * @size: the number of bytes you want to read from the socket
2844 * @cancellable: (nullable): a %GCancellable or %NULL
2845 * @error: #GError for error reporting, or %NULL to ignore.
2847 * Receive data (up to @size bytes) from a socket. This is mainly used by
2848 * connection-oriented sockets; it is identical to g_socket_receive_from()
2849 * with @address set to %NULL.
2851 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2852 * g_socket_receive() will always read either 0 or 1 complete messages from
2853 * the socket. If the received message is too large to fit in @buffer, then
2854 * the data beyond @size bytes will be discarded, without any explicit
2855 * indication that this has occurred.
2857 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2858 * number of bytes, up to @size. If more than @size bytes have been
2859 * received, the additional data will be returned in future calls to
2860 * g_socket_receive().
2862 * If the socket is in blocking mode the call will block until there
2863 * is some data to receive, the connection is closed, or there is an
2864 * error. If there is no data available and the socket is in
2865 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2866 * returned. To be notified when data is available, wait for the
2867 * %G_IO_IN condition.
2869 * On error -1 is returned and @error is set accordingly.
2871 * Returns: Number of bytes read, or 0 if the connection was closed by
2872 * the peer, or -1 on error
2874 * Since: 2.22
2876 gssize
2877 g_socket_receive (GSocket *socket,
2878 gchar *buffer,
2879 gsize size,
2880 GCancellable *cancellable,
2881 GError **error)
2883 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
2884 socket->priv->blocking ? -1 : 0,
2885 cancellable, error);
2889 * g_socket_receive_with_blocking:
2890 * @socket: a #GSocket
2891 * @buffer: (array length=size) (element-type guint8): a buffer to
2892 * read data into (which should be at least @size bytes long).
2893 * @size: the number of bytes you want to read from the socket
2894 * @blocking: whether to do blocking or non-blocking I/O
2895 * @cancellable: (nullable): a %GCancellable or %NULL
2896 * @error: #GError for error reporting, or %NULL to ignore.
2898 * This behaves exactly the same as g_socket_receive(), except that
2899 * the choice of blocking or non-blocking behavior is determined by
2900 * the @blocking argument rather than by @socket's properties.
2902 * Returns: Number of bytes read, or 0 if the connection was closed by
2903 * the peer, or -1 on error
2905 * Since: 2.26
2907 gssize
2908 g_socket_receive_with_blocking (GSocket *socket,
2909 gchar *buffer,
2910 gsize size,
2911 gboolean blocking,
2912 GCancellable *cancellable,
2913 GError **error)
2915 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
2916 blocking ? -1 : 0, cancellable, error);
2920 * g_socket_receive_from:
2921 * @socket: a #GSocket
2922 * @address: (out) (optional): a pointer to a #GSocketAddress
2923 * pointer, or %NULL
2924 * @buffer: (array length=size) (element-type guint8): a buffer to
2925 * read data into (which should be at least @size bytes long).
2926 * @size: the number of bytes you want to read from the socket
2927 * @cancellable: (nullable): a %GCancellable or %NULL
2928 * @error: #GError for error reporting, or %NULL to ignore.
2930 * Receive data (up to @size bytes) from a socket.
2932 * If @address is non-%NULL then @address will be set equal to the
2933 * source address of the received packet.
2934 * @address is owned by the caller.
2936 * See g_socket_receive() for additional information.
2938 * Returns: Number of bytes read, or 0 if the connection was closed by
2939 * the peer, or -1 on error
2941 * Since: 2.22
2943 gssize
2944 g_socket_receive_from (GSocket *socket,
2945 GSocketAddress **address,
2946 gchar *buffer,
2947 gsize size,
2948 GCancellable *cancellable,
2949 GError **error)
2951 GInputVector v;
2953 v.buffer = buffer;
2954 v.size = size;
2956 return g_socket_receive_message (socket,
2957 address,
2958 &v, 1,
2959 NULL, 0, NULL,
2960 cancellable,
2961 error);
2964 /* See the comment about SIGPIPE above. */
2965 #ifdef MSG_NOSIGNAL
2966 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2967 #else
2968 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2969 #endif
2971 static gssize
2972 g_socket_send_with_timeout (GSocket *socket,
2973 const guint8 *buffer,
2974 gsize size,
2975 gint64 timeout,
2976 GCancellable *cancellable,
2977 GError **error)
2979 gssize ret;
2980 gint64 start_time;
2982 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2984 start_time = g_get_monotonic_time ();
2986 if (!check_socket (socket, error))
2987 return -1;
2989 if (!check_timeout (socket, error))
2990 return -1;
2992 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2993 return -1;
2995 while (1)
2997 win32_unset_event_mask (socket, FD_WRITE);
2999 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
3001 int errsv = get_socket_errno ();
3003 if (errsv == EINTR)
3004 continue;
3006 #ifdef WSAEWOULDBLOCK
3007 if (errsv == WSAEWOULDBLOCK)
3008 #else
3009 if (errsv == EWOULDBLOCK ||
3010 errsv == EAGAIN)
3011 #endif
3013 if (timeout != 0)
3015 if (!block_on_timeout (socket, G_IO_OUT, timeout, start_time,
3016 cancellable, error))
3017 return -1;
3019 continue;
3023 socket_set_error_lazy (error, errsv, _("Error sending data: %s"));
3024 return -1;
3026 break;
3029 return ret;
3033 * g_socket_send:
3034 * @socket: a #GSocket
3035 * @buffer: (array length=size) (element-type guint8): the buffer
3036 * containing the data to send.
3037 * @size: the number of bytes to send
3038 * @cancellable: (nullable): a %GCancellable or %NULL
3039 * @error: #GError for error reporting, or %NULL to ignore.
3041 * Tries to send @size bytes from @buffer on the socket. This is
3042 * mainly used by connection-oriented sockets; it is identical to
3043 * g_socket_send_to() with @address set to %NULL.
3045 * If the socket is in blocking mode the call will block until there is
3046 * space for the data in the socket queue. If there is no space available
3047 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3048 * will be returned. To be notified when space is available, wait for the
3049 * %G_IO_OUT condition. Note though that you may still receive
3050 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3051 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3052 * very common due to the way the underlying APIs work.)
3054 * On error -1 is returned and @error is set accordingly.
3056 * Returns: Number of bytes written (which may be less than @size), or -1
3057 * on error
3059 * Since: 2.22
3061 gssize
3062 g_socket_send (GSocket *socket,
3063 const gchar *buffer,
3064 gsize size,
3065 GCancellable *cancellable,
3066 GError **error)
3068 return g_socket_send_with_blocking (socket, buffer, size,
3069 socket->priv->blocking,
3070 cancellable, error);
3074 * g_socket_send_with_blocking:
3075 * @socket: a #GSocket
3076 * @buffer: (array length=size) (element-type guint8): the buffer
3077 * containing the data to send.
3078 * @size: the number of bytes to send
3079 * @blocking: whether to do blocking or non-blocking I/O
3080 * @cancellable: (nullable): a %GCancellable or %NULL
3081 * @error: #GError for error reporting, or %NULL to ignore.
3083 * This behaves exactly the same as g_socket_send(), except that
3084 * the choice of blocking or non-blocking behavior is determined by
3085 * the @blocking argument rather than by @socket's properties.
3087 * Returns: Number of bytes written (which may be less than @size), or -1
3088 * on error
3090 * Since: 2.26
3092 gssize
3093 g_socket_send_with_blocking (GSocket *socket,
3094 const gchar *buffer,
3095 gsize size,
3096 gboolean blocking,
3097 GCancellable *cancellable,
3098 GError **error)
3100 return g_socket_send_with_timeout (socket, (const guint8 *) buffer, size,
3101 blocking ? -1 : 0, cancellable, error);
3105 * g_socket_send_to:
3106 * @socket: a #GSocket
3107 * @address: (nullable): a #GSocketAddress, or %NULL
3108 * @buffer: (array length=size) (element-type guint8): the buffer
3109 * containing the data to send.
3110 * @size: the number of bytes to send
3111 * @cancellable: (nullable): a %GCancellable or %NULL
3112 * @error: #GError for error reporting, or %NULL to ignore.
3114 * Tries to send @size bytes from @buffer to @address. If @address is
3115 * %NULL then the message is sent to the default receiver (set by
3116 * g_socket_connect()).
3118 * See g_socket_send() for additional information.
3120 * Returns: Number of bytes written (which may be less than @size), or -1
3121 * on error
3123 * Since: 2.22
3125 gssize
3126 g_socket_send_to (GSocket *socket,
3127 GSocketAddress *address,
3128 const gchar *buffer,
3129 gsize size,
3130 GCancellable *cancellable,
3131 GError **error)
3133 GOutputVector v;
3135 v.buffer = buffer;
3136 v.size = size;
3138 return g_socket_send_message (socket,
3139 address,
3140 &v, 1,
3141 NULL, 0,
3143 cancellable,
3144 error);
3148 * g_socket_shutdown:
3149 * @socket: a #GSocket
3150 * @shutdown_read: whether to shut down the read side
3151 * @shutdown_write: whether to shut down the write side
3152 * @error: #GError for error reporting, or %NULL to ignore.
3154 * Shut down part or all of a full-duplex connection.
3156 * If @shutdown_read is %TRUE then the receiving side of the connection
3157 * is shut down, and further reading is disallowed.
3159 * If @shutdown_write is %TRUE then the sending side of the connection
3160 * is shut down, and further writing is disallowed.
3162 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
3164 * One example where it is useful to shut down only one side of a connection is
3165 * graceful disconnect for TCP connections where you close the sending side,
3166 * then wait for the other side to close the connection, thus ensuring that the
3167 * other side saw all sent data.
3169 * Returns: %TRUE on success, %FALSE on error
3171 * Since: 2.22
3173 gboolean
3174 g_socket_shutdown (GSocket *socket,
3175 gboolean shutdown_read,
3176 gboolean shutdown_write,
3177 GError **error)
3179 int how;
3181 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3183 if (!check_socket (socket, error))
3184 return FALSE;
3186 /* Do nothing? */
3187 if (!shutdown_read && !shutdown_write)
3188 return TRUE;
3190 #ifndef G_OS_WIN32
3191 if (shutdown_read && shutdown_write)
3192 how = SHUT_RDWR;
3193 else if (shutdown_read)
3194 how = SHUT_RD;
3195 else
3196 how = SHUT_WR;
3197 #else
3198 if (shutdown_read && shutdown_write)
3199 how = SD_BOTH;
3200 else if (shutdown_read)
3201 how = SD_RECEIVE;
3202 else
3203 how = SD_SEND;
3204 #endif
3206 if (shutdown (socket->priv->fd, how) != 0)
3208 int errsv = get_socket_errno ();
3209 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
3210 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
3211 return FALSE;
3214 if (shutdown_read)
3215 socket->priv->connected_read = FALSE;
3216 if (shutdown_write)
3217 socket->priv->connected_write = FALSE;
3219 return TRUE;
3223 * g_socket_close:
3224 * @socket: a #GSocket
3225 * @error: #GError for error reporting, or %NULL to ignore.
3227 * Closes the socket, shutting down any active connection.
3229 * Closing a socket does not wait for all outstanding I/O operations
3230 * to finish, so the caller should not rely on them to be guaranteed
3231 * to complete even if the close returns with no error.
3233 * Once the socket is closed, all other operations will return
3234 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
3235 * return an error.
3237 * Sockets will be automatically closed when the last reference
3238 * is dropped, but you might want to call this function to make sure
3239 * resources are released as early as possible.
3241 * Beware that due to the way that TCP works, it is possible for
3242 * recently-sent data to be lost if either you close a socket while the
3243 * %G_IO_IN condition is set, or else if the remote connection tries to
3244 * send something to you after you close the socket but before it has
3245 * finished reading all of the data you sent. There is no easy generic
3246 * way to avoid this problem; the easiest fix is to design the network
3247 * protocol such that the client will never send data "out of turn".
3248 * Another solution is for the server to half-close the connection by
3249 * calling g_socket_shutdown() with only the @shutdown_write flag set,
3250 * and then wait for the client to notice this and close its side of the
3251 * connection, after which the server can safely call g_socket_close().
3252 * (This is what #GTcpConnection does if you call
3253 * g_tcp_connection_set_graceful_disconnect(). But of course, this
3254 * only works if the client will close its connection after the server
3255 * does.)
3257 * Returns: %TRUE on success, %FALSE on error
3259 * Since: 2.22
3261 gboolean
3262 g_socket_close (GSocket *socket,
3263 GError **error)
3265 int res;
3267 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3269 if (socket->priv->closed)
3270 return TRUE; /* Multiple close not an error */
3272 if (!check_socket (socket, error))
3273 return FALSE;
3275 while (1)
3277 #ifdef G_OS_WIN32
3278 res = closesocket (socket->priv->fd);
3279 #else
3280 res = close (socket->priv->fd);
3281 #endif
3282 if (res == -1)
3284 int errsv = get_socket_errno ();
3286 if (errsv == EINTR)
3287 continue;
3289 g_set_error (error, G_IO_ERROR,
3290 socket_io_error_from_errno (errsv),
3291 _("Error closing socket: %s"),
3292 socket_strerror (errsv));
3293 return FALSE;
3295 break;
3298 socket->priv->fd = -1;
3299 socket->priv->connected_read = FALSE;
3300 socket->priv->connected_write = FALSE;
3301 socket->priv->closed = TRUE;
3302 if (socket->priv->remote_address)
3304 g_object_unref (socket->priv->remote_address);
3305 socket->priv->remote_address = NULL;
3308 return TRUE;
3312 * g_socket_is_closed:
3313 * @socket: a #GSocket
3315 * Checks whether a socket is closed.
3317 * Returns: %TRUE if socket is closed, %FALSE otherwise
3319 * Since: 2.22
3321 gboolean
3322 g_socket_is_closed (GSocket *socket)
3324 return socket->priv->closed;
3327 #ifdef G_OS_WIN32
3328 /* Broken source, used on errors */
3329 static gboolean
3330 broken_dispatch (GSource *source,
3331 GSourceFunc callback,
3332 gpointer user_data)
3334 return TRUE;
3337 static GSourceFuncs broken_funcs =
3339 NULL,
3340 NULL,
3341 broken_dispatch,
3342 NULL
3345 static gint
3346 network_events_for_condition (GIOCondition condition)
3348 int event_mask = 0;
3350 if (condition & G_IO_IN)
3351 event_mask |= (FD_READ | FD_ACCEPT);
3352 if (condition & G_IO_OUT)
3353 event_mask |= (FD_WRITE | FD_CONNECT);
3354 event_mask |= FD_CLOSE;
3356 return event_mask;
3359 static void
3360 ensure_event (GSocket *socket)
3362 if (socket->priv->event == WSA_INVALID_EVENT)
3363 socket->priv->event = WSACreateEvent();
3366 static void
3367 update_select_events (GSocket *socket)
3369 int event_mask;
3370 GIOCondition *ptr;
3371 GList *l;
3372 WSAEVENT event;
3374 ensure_event (socket);
3376 event_mask = 0;
3377 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3379 ptr = l->data;
3380 event_mask |= network_events_for_condition (*ptr);
3383 if (event_mask != socket->priv->selected_events)
3385 /* If no events selected, disable event so we can unset
3386 nonblocking mode */
3388 if (event_mask == 0)
3389 event = NULL;
3390 else
3391 event = socket->priv->event;
3393 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3394 socket->priv->selected_events = event_mask;
3398 static void
3399 add_condition_watch (GSocket *socket,
3400 GIOCondition *condition)
3402 g_mutex_lock (&socket->priv->win32_source_lock);
3403 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3405 socket->priv->requested_conditions =
3406 g_list_prepend (socket->priv->requested_conditions, condition);
3408 update_select_events (socket);
3409 g_mutex_unlock (&socket->priv->win32_source_lock);
3412 static void
3413 remove_condition_watch (GSocket *socket,
3414 GIOCondition *condition)
3416 g_mutex_lock (&socket->priv->win32_source_lock);
3417 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3419 socket->priv->requested_conditions =
3420 g_list_remove (socket->priv->requested_conditions, condition);
3422 update_select_events (socket);
3423 g_mutex_unlock (&socket->priv->win32_source_lock);
3426 static GIOCondition
3427 update_condition_unlocked (GSocket *socket)
3429 WSANETWORKEVENTS events;
3430 GIOCondition condition;
3432 if (WSAEnumNetworkEvents (socket->priv->fd,
3433 socket->priv->event,
3434 &events) == 0)
3436 socket->priv->current_events |= events.lNetworkEvents;
3437 if (events.lNetworkEvents & FD_WRITE &&
3438 events.iErrorCode[FD_WRITE_BIT] != 0)
3439 socket->priv->current_errors |= FD_WRITE;
3440 if (events.lNetworkEvents & FD_CONNECT &&
3441 events.iErrorCode[FD_CONNECT_BIT] != 0)
3442 socket->priv->current_errors |= FD_CONNECT;
3445 condition = 0;
3446 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3447 condition |= G_IO_IN;
3449 if (socket->priv->current_events & FD_CLOSE)
3451 int r, errsv, buffer;
3453 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3454 if (r < 0)
3455 errsv = get_socket_errno ();
3457 if (r > 0 ||
3458 (r < 0 && errsv == WSAENOTCONN))
3459 condition |= G_IO_IN;
3460 else if (r == 0 ||
3461 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3462 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3463 condition |= G_IO_HUP;
3464 else
3465 condition |= G_IO_ERR;
3468 if (socket->priv->closed)
3469 condition |= G_IO_HUP;
3471 /* Never report both G_IO_OUT and HUP, these are
3472 mutually exclusive (can't write to a closed socket) */
3473 if ((condition & G_IO_HUP) == 0 &&
3474 socket->priv->current_events & FD_WRITE)
3476 if (socket->priv->current_errors & FD_WRITE)
3477 condition |= G_IO_ERR;
3478 else
3479 condition |= G_IO_OUT;
3481 else
3483 if (socket->priv->current_events & FD_CONNECT)
3485 if (socket->priv->current_errors & FD_CONNECT)
3486 condition |= (G_IO_HUP | G_IO_ERR);
3487 else
3488 condition |= G_IO_OUT;
3492 return condition;
3495 static GIOCondition
3496 update_condition (GSocket *socket)
3498 GIOCondition res;
3499 g_mutex_lock (&socket->priv->win32_source_lock);
3500 res = update_condition_unlocked (socket);
3501 g_mutex_unlock (&socket->priv->win32_source_lock);
3502 return res;
3504 #endif
3506 typedef struct {
3507 GSource source;
3508 #ifdef G_OS_WIN32
3509 GPollFD pollfd;
3510 #else
3511 gpointer fd_tag;
3512 #endif
3513 GSocket *socket;
3514 GIOCondition condition;
3515 } GSocketSource;
3517 #ifdef G_OS_WIN32
3518 static gboolean
3519 socket_source_prepare_win32 (GSource *source,
3520 gint *timeout)
3522 GSocketSource *socket_source = (GSocketSource *)source;
3524 *timeout = -1;
3526 return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3529 static gboolean
3530 socket_source_check_win32 (GSource *source)
3532 int timeout;
3534 return socket_source_prepare_win32 (source, &timeout);
3536 #endif
3538 static gboolean
3539 socket_source_dispatch (GSource *source,
3540 GSourceFunc callback,
3541 gpointer user_data)
3543 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3544 GSocketSource *socket_source = (GSocketSource *)source;
3545 GSocket *socket = socket_source->socket;
3546 gint64 timeout;
3547 guint events;
3548 gboolean ret;
3550 #ifdef G_OS_WIN32
3551 events = update_condition (socket_source->socket);
3552 #else
3553 events = g_source_query_unix_fd (source, socket_source->fd_tag);
3554 #endif
3556 timeout = g_source_get_ready_time (source);
3557 if (timeout >= 0 && timeout < g_source_get_time (source))
3559 socket->priv->timed_out = TRUE;
3560 events |= (G_IO_IN | G_IO_OUT);
3563 ret = (*func) (socket, events & socket_source->condition, user_data);
3565 if (socket->priv->timeout)
3566 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3567 else
3568 g_source_set_ready_time (source, -1);
3570 return ret;
3573 static void
3574 socket_source_finalize (GSource *source)
3576 GSocketSource *socket_source = (GSocketSource *)source;
3577 GSocket *socket;
3579 socket = socket_source->socket;
3581 #ifdef G_OS_WIN32
3582 remove_condition_watch (socket, &socket_source->condition);
3583 #endif
3585 g_object_unref (socket);
3588 static gboolean
3589 socket_source_closure_callback (GSocket *socket,
3590 GIOCondition condition,
3591 gpointer data)
3593 GClosure *closure = data;
3595 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3596 GValue result_value = G_VALUE_INIT;
3597 gboolean result;
3599 g_value_init (&result_value, G_TYPE_BOOLEAN);
3601 g_value_init (&params[0], G_TYPE_SOCKET);
3602 g_value_set_object (&params[0], socket);
3603 g_value_init (&params[1], G_TYPE_IO_CONDITION);
3604 g_value_set_flags (&params[1], condition);
3606 g_closure_invoke (closure, &result_value, 2, params, NULL);
3608 result = g_value_get_boolean (&result_value);
3609 g_value_unset (&result_value);
3610 g_value_unset (&params[0]);
3611 g_value_unset (&params[1]);
3613 return result;
3616 static GSourceFuncs socket_source_funcs =
3618 #ifdef G_OS_WIN32
3619 socket_source_prepare_win32,
3620 socket_source_check_win32,
3621 #else
3622 NULL, NULL, /* check, prepare */
3623 #endif
3624 socket_source_dispatch,
3625 socket_source_finalize,
3626 (GSourceFunc)socket_source_closure_callback,
3629 static GSource *
3630 socket_source_new (GSocket *socket,
3631 GIOCondition condition,
3632 GCancellable *cancellable)
3634 GSource *source;
3635 GSocketSource *socket_source;
3637 #ifdef G_OS_WIN32
3638 ensure_event (socket);
3640 if (socket->priv->event == WSA_INVALID_EVENT)
3642 g_warning ("Failed to create WSAEvent");
3643 return g_source_new (&broken_funcs, sizeof (GSource));
3645 #endif
3647 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
3649 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3650 g_source_set_name (source, "GSocket");
3651 socket_source = (GSocketSource *)source;
3653 socket_source->socket = g_object_ref (socket);
3654 socket_source->condition = condition;
3656 if (cancellable)
3658 GSource *cancellable_source;
3660 cancellable_source = g_cancellable_source_new (cancellable);
3661 g_source_add_child_source (source, cancellable_source);
3662 g_source_set_dummy_callback (cancellable_source);
3663 g_source_unref (cancellable_source);
3666 #ifdef G_OS_WIN32
3667 add_condition_watch (socket, &socket_source->condition);
3668 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3669 socket_source->pollfd.events = condition;
3670 socket_source->pollfd.revents = 0;
3671 g_source_add_poll (source, &socket_source->pollfd);
3672 #else
3673 socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
3674 #endif
3676 if (socket->priv->timeout)
3677 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3678 else
3679 g_source_set_ready_time (source, -1);
3681 return source;
3685 * g_socket_create_source: (skip)
3686 * @socket: a #GSocket
3687 * @condition: a #GIOCondition mask to monitor
3688 * @cancellable: (nullable): a %GCancellable or %NULL
3690 * Creates a #GSource that can be attached to a %GMainContext to monitor
3691 * for the availability of the specified @condition on the socket. The #GSource
3692 * keeps a reference to the @socket.
3694 * The callback on the source is of the #GSocketSourceFunc type.
3696 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3697 * these conditions will always be reported output if they are true.
3699 * @cancellable if not %NULL can be used to cancel the source, which will
3700 * cause the source to trigger, reporting the current condition (which
3701 * is likely 0 unless cancellation happened at the same time as a
3702 * condition change). You can check for this in the callback using
3703 * g_cancellable_is_cancelled().
3705 * If @socket has a timeout set, and it is reached before @condition
3706 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3707 * %G_IO_OUT depending on @condition. However, @socket will have been
3708 * marked as having had a timeout, and so the next #GSocket I/O method
3709 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3711 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3713 * Since: 2.22
3715 GSource *
3716 g_socket_create_source (GSocket *socket,
3717 GIOCondition condition,
3718 GCancellable *cancellable)
3720 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3722 return socket_source_new (socket, condition, cancellable);
3726 * g_socket_condition_check:
3727 * @socket: a #GSocket
3728 * @condition: a #GIOCondition mask to check
3730 * Checks on the readiness of @socket to perform operations.
3731 * The operations specified in @condition are checked for and masked
3732 * against the currently-satisfied conditions on @socket. The result
3733 * is returned.
3735 * Note that on Windows, it is possible for an operation to return
3736 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3737 * g_socket_condition_check() has claimed that the socket is ready for
3738 * writing. Rather than calling g_socket_condition_check() and then
3739 * writing to the socket if it succeeds, it is generally better to
3740 * simply try writing to the socket right away, and try again later if
3741 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3743 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3744 * these conditions will always be set in the output if they are true.
3746 * This call never blocks.
3748 * Returns: the @GIOCondition mask of the current state
3750 * Since: 2.22
3752 GIOCondition
3753 g_socket_condition_check (GSocket *socket,
3754 GIOCondition condition)
3756 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3758 if (!check_socket (socket, NULL))
3759 return 0;
3761 #ifdef G_OS_WIN32
3763 GIOCondition current_condition;
3765 condition |= G_IO_ERR | G_IO_HUP;
3767 add_condition_watch (socket, &condition);
3768 current_condition = update_condition (socket);
3769 remove_condition_watch (socket, &condition);
3770 return condition & current_condition;
3772 #else
3774 GPollFD poll_fd;
3775 gint result;
3776 poll_fd.fd = socket->priv->fd;
3777 poll_fd.events = condition;
3778 poll_fd.revents = 0;
3781 result = g_poll (&poll_fd, 1, 0);
3782 while (result == -1 && get_socket_errno () == EINTR);
3784 return poll_fd.revents;
3786 #endif
3790 * g_socket_condition_wait:
3791 * @socket: a #GSocket
3792 * @condition: a #GIOCondition mask to wait for
3793 * @cancellable: (nullable): a #GCancellable, or %NULL
3794 * @error: a #GError pointer, or %NULL
3796 * Waits for @condition to become true on @socket. When the condition
3797 * is met, %TRUE is returned.
3799 * If @cancellable is cancelled before the condition is met, or if the
3800 * socket has a timeout set and it is reached before the condition is
3801 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3802 * the appropriate value (%G_IO_ERROR_CANCELLED or
3803 * %G_IO_ERROR_TIMED_OUT).
3805 * See also g_socket_condition_timed_wait().
3807 * Returns: %TRUE if the condition was met, %FALSE otherwise
3809 * Since: 2.22
3811 gboolean
3812 g_socket_condition_wait (GSocket *socket,
3813 GIOCondition condition,
3814 GCancellable *cancellable,
3815 GError **error)
3817 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3819 return g_socket_condition_timed_wait (socket, condition, -1,
3820 cancellable, error);
3824 * g_socket_condition_timed_wait:
3825 * @socket: a #GSocket
3826 * @condition: a #GIOCondition mask to wait for
3827 * @timeout: the maximum time (in microseconds) to wait, or -1
3828 * @cancellable: (nullable): a #GCancellable, or %NULL
3829 * @error: a #GError pointer, or %NULL
3831 * Waits for up to @timeout microseconds for @condition to become true
3832 * on @socket. If the condition is met, %TRUE is returned.
3834 * If @cancellable is cancelled before the condition is met, or if
3835 * @timeout (or the socket's #GSocket:timeout) is reached before the
3836 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3837 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3838 * %G_IO_ERROR_TIMED_OUT).
3840 * If you don't want a timeout, use g_socket_condition_wait().
3841 * (Alternatively, you can pass -1 for @timeout.)
3843 * Note that although @timeout is in microseconds for consistency with
3844 * other GLib APIs, this function actually only has millisecond
3845 * resolution, and the behavior is undefined if @timeout is not an
3846 * exact number of milliseconds.
3848 * Returns: %TRUE if the condition was met, %FALSE otherwise
3850 * Since: 2.32
3852 gboolean
3853 g_socket_condition_timed_wait (GSocket *socket,
3854 GIOCondition condition,
3855 gint64 timeout,
3856 GCancellable *cancellable,
3857 GError **error)
3859 gint64 start_time;
3861 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3863 if (!check_socket (socket, error))
3864 return FALSE;
3866 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3867 return FALSE;
3869 if (socket->priv->timeout &&
3870 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3871 timeout = (gint64) socket->priv->timeout * 1000;
3872 else if (timeout != -1)
3873 timeout = timeout / 1000;
3875 start_time = g_get_monotonic_time ();
3877 #ifdef G_OS_WIN32
3879 GIOCondition current_condition;
3880 WSAEVENT events[2];
3881 DWORD res;
3882 GPollFD cancel_fd;
3883 int num_events;
3885 /* Always check these */
3886 condition |= G_IO_ERR | G_IO_HUP;
3888 add_condition_watch (socket, &condition);
3890 num_events = 0;
3891 events[num_events++] = socket->priv->event;
3893 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3894 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3896 if (timeout == -1)
3897 timeout = WSA_INFINITE;
3899 g_mutex_lock (&socket->priv->win32_source_lock);
3900 current_condition = update_condition_unlocked (socket);
3901 while ((condition & current_condition) == 0)
3903 if (!socket->priv->waiting)
3905 socket->priv->waiting = TRUE;
3906 socket->priv->waiting_result = 0;
3907 g_mutex_unlock (&socket->priv->win32_source_lock);
3909 res = WSAWaitForMultipleEvents (num_events, events, FALSE, timeout, FALSE);
3911 g_mutex_lock (&socket->priv->win32_source_lock);
3912 socket->priv->waiting = FALSE;
3913 socket->priv->waiting_result = res;
3914 g_cond_broadcast (&socket->priv->win32_source_cond);
3916 else
3918 if (timeout != WSA_INFINITE)
3920 if (!g_cond_wait_until (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock, timeout))
3922 res = WSA_WAIT_TIMEOUT;
3923 break;
3925 else
3927 res = socket->priv->waiting_result;
3930 else
3932 g_cond_wait (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock);
3933 res = socket->priv->waiting_result;
3937 if (res == WSA_WAIT_FAILED)
3939 int errsv = get_socket_errno ();
3941 g_set_error (error, G_IO_ERROR,
3942 socket_io_error_from_errno (errsv),
3943 _("Waiting for socket condition: %s"),
3944 socket_strerror (errsv));
3945 break;
3947 else if (res == WSA_WAIT_TIMEOUT)
3949 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3950 _("Socket I/O timed out"));
3951 break;
3954 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3955 break;
3957 current_condition = update_condition_unlocked (socket);
3959 if (timeout != WSA_INFINITE)
3961 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3962 if (timeout < 0)
3963 timeout = 0;
3966 g_mutex_unlock (&socket->priv->win32_source_lock);
3967 remove_condition_watch (socket, &condition);
3968 if (num_events > 1)
3969 g_cancellable_release_fd (cancellable);
3971 return (condition & current_condition) != 0;
3973 #else
3975 GPollFD poll_fd[2];
3976 gint result;
3977 gint num;
3979 poll_fd[0].fd = socket->priv->fd;
3980 poll_fd[0].events = condition;
3981 num = 1;
3983 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3984 num++;
3986 while (TRUE)
3988 int errsv;
3989 result = g_poll (poll_fd, num, timeout);
3990 errsv = errno;
3991 if (result != -1 || errsv != EINTR)
3992 break;
3994 if (timeout != -1)
3996 timeout -= (g_get_monotonic_time () - start_time) / 1000;
3997 if (timeout < 0)
3998 timeout = 0;
4002 if (num > 1)
4003 g_cancellable_release_fd (cancellable);
4005 if (result == 0)
4007 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4008 _("Socket I/O timed out"));
4009 return FALSE;
4012 return !g_cancellable_set_error_if_cancelled (cancellable, error);
4014 #endif
4017 #ifndef G_OS_WIN32
4019 /* Unfortunately these have to be macros rather than inline functions due to
4020 * using alloca(). */
4021 #define output_message_to_msghdr(message, prev_message, msg, prev_msg, error) \
4022 G_STMT_START { \
4023 const GOutputMessage *_message = (message); \
4024 const GOutputMessage *_prev_message = (prev_message); \
4025 struct msghdr *_msg = (msg); \
4026 const struct msghdr *_prev_msg = (prev_msg); \
4027 GError **_error = (error); \
4029 _msg->msg_flags = 0; \
4031 /* name */ \
4032 if (_prev_message != NULL && _prev_message->address == _message->address) \
4034 _msg->msg_name = _prev_msg->msg_name; \
4035 _msg->msg_namelen = _prev_msg->msg_namelen; \
4037 else if (_message->address != NULL) \
4039 _msg->msg_namelen = g_socket_address_get_native_size (_message->address); \
4040 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4041 if (!g_socket_address_to_native (_message->address, _msg->msg_name, \
4042 _msg->msg_namelen, _error)) \
4043 break; \
4045 else \
4047 _msg->msg_name = NULL; \
4048 _msg->msg_namelen = 0; \
4051 /* iov */ \
4053 /* this entire expression will be evaluated at compile time */ \
4054 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4055 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4056 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4057 G_STRUCT_OFFSET (GOutputVector, buffer) && \
4058 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4059 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4060 G_STRUCT_OFFSET (GOutputVector, size)) \
4061 /* ABI is compatible */ \
4063 _msg->msg_iov = (struct iovec *) _message->vectors; \
4064 _msg->msg_iovlen = _message->num_vectors; \
4066 else \
4067 /* ABI is incompatible */ \
4069 gint i; \
4071 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4072 for (i = 0; i < _message->num_vectors; i++) \
4074 _msg->msg_iov[i].iov_base = (void *) _message->vectors[i].buffer; \
4075 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4077 _msg->msg_iovlen = _message->num_vectors; \
4081 /* control */ \
4083 struct cmsghdr *cmsg; \
4084 gint i; \
4086 _msg->msg_controllen = 0; \
4087 for (i = 0; i < _message->num_control_messages; i++) \
4088 _msg->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (_message->control_messages[i])); \
4090 if (_msg->msg_controllen == 0) \
4091 _msg->msg_control = NULL; \
4092 else \
4094 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4095 memset (_msg->msg_control, '\0', _msg->msg_controllen); \
4098 cmsg = CMSG_FIRSTHDR (_msg); \
4099 for (i = 0; i < _message->num_control_messages; i++) \
4101 cmsg->cmsg_level = g_socket_control_message_get_level (_message->control_messages[i]); \
4102 cmsg->cmsg_type = g_socket_control_message_get_msg_type (_message->control_messages[i]); \
4103 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (_message->control_messages[i])); \
4104 g_socket_control_message_serialize (_message->control_messages[i], \
4105 CMSG_DATA (cmsg)); \
4106 cmsg = CMSG_NXTHDR (_msg, cmsg); \
4108 g_assert (cmsg == NULL); \
4110 } G_STMT_END
4112 #define input_message_to_msghdr(message, msg) \
4113 G_STMT_START { \
4114 const GInputMessage *_message = (message); \
4115 struct msghdr *_msg = (msg); \
4117 /* name */ \
4118 if (_message->address) \
4120 _msg->msg_namelen = sizeof (struct sockaddr_storage); \
4121 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4123 else \
4125 _msg->msg_name = NULL; \
4126 _msg->msg_namelen = 0; \
4129 /* iov */ \
4130 /* this entire expression will be evaluated at compile time */ \
4131 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4132 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4133 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4134 G_STRUCT_OFFSET (GInputVector, buffer) && \
4135 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4136 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4137 G_STRUCT_OFFSET (GInputVector, size)) \
4138 /* ABI is compatible */ \
4140 _msg->msg_iov = (struct iovec *) _message->vectors; \
4141 _msg->msg_iovlen = _message->num_vectors; \
4143 else \
4144 /* ABI is incompatible */ \
4146 guint i; \
4148 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4149 for (i = 0; i < _message->num_vectors; i++) \
4151 _msg->msg_iov[i].iov_base = _message->vectors[i].buffer; \
4152 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4154 _msg->msg_iovlen = _message->num_vectors; \
4157 /* control */ \
4158 if (_message->control_messages == NULL) \
4160 _msg->msg_controllen = 0; \
4161 _msg->msg_control = NULL; \
4163 else \
4165 _msg->msg_controllen = 2048; \
4166 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4169 /* flags */ \
4170 _msg->msg_flags = _message->flags; \
4171 } G_STMT_END
4173 static void
4174 input_message_from_msghdr (const struct msghdr *msg,
4175 GInputMessage *message,
4176 GSocket *socket)
4178 /* decode address */
4179 if (message->address != NULL)
4181 *message->address = cache_recv_address (socket, msg->msg_name,
4182 msg->msg_namelen);
4185 /* decode control messages */
4187 GPtrArray *my_messages = NULL;
4188 struct cmsghdr *cmsg;
4190 if (msg->msg_controllen >= sizeof (struct cmsghdr))
4192 g_assert (message->control_messages != NULL);
4193 for (cmsg = CMSG_FIRSTHDR (msg);
4194 cmsg != NULL;
4195 cmsg = CMSG_NXTHDR ((struct msghdr *) msg, cmsg))
4197 GSocketControlMessage *control_message;
4199 control_message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4200 cmsg->cmsg_type,
4201 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4202 CMSG_DATA (cmsg));
4203 if (control_message == NULL)
4204 /* We've already spewed about the problem in the
4205 deserialization code, so just continue */
4206 continue;
4208 if (my_messages == NULL)
4209 my_messages = g_ptr_array_new ();
4210 g_ptr_array_add (my_messages, control_message);
4214 if (message->num_control_messages)
4215 *message->num_control_messages = my_messages != NULL ? my_messages->len : 0;
4217 if (message->control_messages)
4219 if (my_messages == NULL)
4221 *message->control_messages = NULL;
4223 else
4225 g_ptr_array_add (my_messages, NULL);
4226 *message->control_messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4229 else
4231 g_assert (my_messages == NULL);
4235 /* capture the flags */
4236 message->flags = msg->msg_flags;
4238 #endif
4241 * g_socket_send_message:
4242 * @socket: a #GSocket
4243 * @address: (nullable): a #GSocketAddress, or %NULL
4244 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4245 * @num_vectors: the number of elements in @vectors, or -1
4246 * @messages: (array length=num_messages) (nullable): a pointer to an
4247 * array of #GSocketControlMessages, or %NULL.
4248 * @num_messages: number of elements in @messages, or -1.
4249 * @flags: an int containing #GSocketMsgFlags flags
4250 * @cancellable: (nullable): a %GCancellable or %NULL
4251 * @error: #GError for error reporting, or %NULL to ignore.
4253 * Send data to @address on @socket. For sending multiple messages see
4254 * g_socket_send_messages(); for easier use, see
4255 * g_socket_send() and g_socket_send_to().
4257 * If @address is %NULL then the message is sent to the default receiver
4258 * (set by g_socket_connect()).
4260 * @vectors must point to an array of #GOutputVector structs and
4261 * @num_vectors must be the length of this array. (If @num_vectors is -1,
4262 * then @vectors is assumed to be terminated by a #GOutputVector with a
4263 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
4264 * that the sent data will be gathered from. Using multiple
4265 * #GOutputVectors is more memory-efficient than manually copying
4266 * data from multiple sources into a single buffer, and more
4267 * network-efficient than making multiple calls to g_socket_send().
4269 * @messages, if non-%NULL, is taken to point to an array of @num_messages
4270 * #GSocketControlMessage instances. These correspond to the control
4271 * messages to be sent on the socket.
4272 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
4273 * array.
4275 * @flags modify how the message is sent. The commonly available arguments
4276 * for this are available in the #GSocketMsgFlags enum, but the
4277 * values there are the same as the system values, and the flags
4278 * are passed in as-is, so you can pass in system-specific flags too.
4280 * If the socket is in blocking mode the call will block until there is
4281 * space for the data in the socket queue. If there is no space available
4282 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4283 * will be returned. To be notified when space is available, wait for the
4284 * %G_IO_OUT condition. Note though that you may still receive
4285 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4286 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4287 * very common due to the way the underlying APIs work.)
4289 * On error -1 is returned and @error is set accordingly.
4291 * Returns: Number of bytes written (which may be less than @size), or -1
4292 * on error
4294 * Since: 2.22
4296 gssize
4297 g_socket_send_message (GSocket *socket,
4298 GSocketAddress *address,
4299 GOutputVector *vectors,
4300 gint num_vectors,
4301 GSocketControlMessage **messages,
4302 gint num_messages,
4303 gint flags,
4304 GCancellable *cancellable,
4305 GError **error)
4307 return g_socket_send_message_with_timeout (socket, address,
4308 vectors, num_vectors,
4309 messages, num_messages, flags,
4310 socket->priv->blocking ? -1 : 0,
4311 cancellable, error);
4314 static gssize
4315 g_socket_send_message_with_timeout (GSocket *socket,
4316 GSocketAddress *address,
4317 GOutputVector *vectors,
4318 gint num_vectors,
4319 GSocketControlMessage **messages,
4320 gint num_messages,
4321 gint flags,
4322 gint64 timeout,
4323 GCancellable *cancellable,
4324 GError **error)
4326 GOutputVector one_vector;
4327 char zero;
4328 gint64 start_time;
4330 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4331 g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), -1);
4332 g_return_val_if_fail (num_vectors == 0 || vectors != NULL, -1);
4333 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
4334 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
4335 g_return_val_if_fail (error == NULL || *error == NULL, -1);
4337 start_time = g_get_monotonic_time ();
4339 if (!check_socket (socket, error))
4340 return -1;
4342 if (!check_timeout (socket, error))
4343 return -1;
4345 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4346 return -1;
4348 if (num_vectors == -1)
4350 for (num_vectors = 0;
4351 vectors[num_vectors].buffer != NULL;
4352 num_vectors++)
4356 if (num_messages == -1)
4358 for (num_messages = 0;
4359 messages != NULL && messages[num_messages] != NULL;
4360 num_messages++)
4364 if (num_vectors == 0)
4366 zero = '\0';
4368 one_vector.buffer = &zero;
4369 one_vector.size = 1;
4370 num_vectors = 1;
4371 vectors = &one_vector;
4374 #ifndef G_OS_WIN32
4376 GOutputMessage output_message;
4377 struct msghdr msg;
4378 gssize result;
4379 GError *child_error = NULL;
4381 output_message.address = address;
4382 output_message.vectors = vectors;
4383 output_message.num_vectors = num_vectors;
4384 output_message.bytes_sent = 0;
4385 output_message.control_messages = messages;
4386 output_message.num_control_messages = num_messages;
4388 output_message_to_msghdr (&output_message, NULL, &msg, NULL, &child_error);
4390 if (child_error != NULL)
4392 g_propagate_error (error, child_error);
4393 return -1;
4396 while (1)
4398 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4399 if (result < 0)
4401 int errsv = get_socket_errno ();
4403 if (errsv == EINTR)
4404 continue;
4406 if (timeout != 0 &&
4407 (errsv == EWOULDBLOCK ||
4408 errsv == EAGAIN))
4410 if (!block_on_timeout (socket, G_IO_OUT, timeout, start_time,
4411 cancellable, error))
4412 return -1;
4414 continue;
4417 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4418 return -1;
4420 break;
4423 return result;
4425 #else
4427 struct sockaddr_storage addr;
4428 guint addrlen;
4429 DWORD bytes_sent;
4430 int result;
4431 WSABUF *bufs;
4432 gint i;
4434 /* Win32 doesn't support control messages.
4435 Actually this is possible for raw and datagram sockets
4436 via WSASendMessage on Vista or later, but that doesn't
4437 seem very useful */
4438 if (num_messages != 0)
4440 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
4441 _("GSocketControlMessage not supported on Windows"));
4442 return -1;
4445 /* iov */
4446 bufs = g_newa (WSABUF, num_vectors);
4447 for (i = 0; i < num_vectors; i++)
4449 bufs[i].buf = (char *)vectors[i].buffer;
4450 bufs[i].len = (gulong)vectors[i].size;
4453 /* name */
4454 addrlen = 0; /* Avoid warning */
4455 if (address)
4457 addrlen = g_socket_address_get_native_size (address);
4458 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
4459 return -1;
4462 while (1)
4464 win32_unset_event_mask (socket, FD_WRITE);
4466 if (address)
4467 result = WSASendTo (socket->priv->fd,
4468 bufs, num_vectors,
4469 &bytes_sent, flags,
4470 (const struct sockaddr *)&addr, addrlen,
4471 NULL, NULL);
4472 else
4473 result = WSASend (socket->priv->fd,
4474 bufs, num_vectors,
4475 &bytes_sent, flags,
4476 NULL, NULL);
4478 if (result != 0)
4480 int errsv = get_socket_errno ();
4482 if (errsv == WSAEINTR)
4483 continue;
4485 if (errsv == WSAEWOULDBLOCK)
4487 if (timeout != 0)
4489 if (!block_on_timeout (socket, G_IO_OUT, timeout,
4490 start_time, cancellable, error))
4491 return -1;
4493 continue;
4497 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4498 return -1;
4500 break;
4503 return bytes_sent;
4505 #endif
4509 * g_socket_send_messages:
4510 * @socket: a #GSocket
4511 * @messages: (array length=num_messages): an array of #GOutputMessage structs
4512 * @num_messages: the number of elements in @messages
4513 * @flags: an int containing #GSocketMsgFlags flags
4514 * @cancellable: (nullable): a %GCancellable or %NULL
4515 * @error: #GError for error reporting, or %NULL to ignore.
4517 * Send multiple data messages from @socket in one go. This is the most
4518 * complicated and fully-featured version of this call. For easier use, see
4519 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
4521 * @messages must point to an array of #GOutputMessage structs and
4522 * @num_messages must be the length of this array. Each #GOutputMessage
4523 * contains an address to send the data to, and a pointer to an array of
4524 * #GOutputVector structs to describe the buffers that the data to be sent
4525 * for each message will be gathered from. Using multiple #GOutputVectors is
4526 * more memory-efficient than manually copying data from multiple sources
4527 * into a single buffer, and more network-efficient than making multiple
4528 * calls to g_socket_send(). Sending multiple messages in one go avoids the
4529 * overhead of making a lot of syscalls in scenarios where a lot of data
4530 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
4531 * or where the same data needs to be sent to multiple recipients.
4533 * @flags modify how the message is sent. The commonly available arguments
4534 * for this are available in the #GSocketMsgFlags enum, but the
4535 * values there are the same as the system values, and the flags
4536 * are passed in as-is, so you can pass in system-specific flags too.
4538 * If the socket is in blocking mode the call will block until there is
4539 * space for all the data in the socket queue. If there is no space available
4540 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4541 * will be returned if no data was written at all, otherwise the number of
4542 * messages sent will be returned. To be notified when space is available,
4543 * wait for the %G_IO_OUT condition. Note though that you may still receive
4544 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4545 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4546 * very common due to the way the underlying APIs work.)
4548 * On error -1 is returned and @error is set accordingly. An error will only
4549 * be returned if zero messages could be sent; otherwise the number of messages
4550 * successfully sent before the error will be returned.
4552 * Returns: number of messages sent, or -1 on error. Note that the number of
4553 * messages sent may be smaller than @num_messages if the socket is
4554 * non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
4555 * in which case the caller may re-try to send the remaining messages.
4557 * Since: 2.44
4559 gint
4560 g_socket_send_messages (GSocket *socket,
4561 GOutputMessage *messages,
4562 guint num_messages,
4563 gint flags,
4564 GCancellable *cancellable,
4565 GError **error)
4567 return g_socket_send_messages_with_timeout (socket, messages, num_messages,
4568 flags,
4569 socket->priv->blocking ? -1 : 0,
4570 cancellable, error);
4573 static gint
4574 g_socket_send_messages_with_timeout (GSocket *socket,
4575 GOutputMessage *messages,
4576 guint num_messages,
4577 gint flags,
4578 gint64 timeout,
4579 GCancellable *cancellable,
4580 GError **error)
4582 gint64 start_time;
4584 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4585 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
4586 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
4587 g_return_val_if_fail (error == NULL || *error == NULL, -1);
4589 start_time = g_get_monotonic_time ();
4591 if (!check_socket (socket, error))
4592 return -1;
4594 if (!check_timeout (socket, error))
4595 return -1;
4597 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4598 return -1;
4600 if (num_messages == 0)
4601 return 0;
4603 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
4605 struct mmsghdr *msgvec;
4606 gint i, num_sent;
4608 #ifdef UIO_MAXIOV
4609 #define MAX_NUM_MESSAGES UIO_MAXIOV
4610 #else
4611 #define MAX_NUM_MESSAGES 1024
4612 #endif
4614 if (num_messages > MAX_NUM_MESSAGES)
4615 num_messages = MAX_NUM_MESSAGES;
4617 msgvec = g_newa (struct mmsghdr, num_messages);
4619 for (i = 0; i < num_messages; ++i)
4621 GOutputMessage *msg = &messages[i];
4622 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
4623 GError *child_error = NULL;
4625 msgvec[i].msg_len = 0;
4627 output_message_to_msghdr (msg, (i > 0) ? &messages[i - 1] : NULL,
4628 msg_hdr, (i > 0) ? &msgvec[i - 1].msg_hdr : NULL,
4629 &child_error);
4631 if (child_error != NULL)
4633 g_propagate_error (error, child_error);
4634 return -1;
4638 for (num_sent = 0; num_sent < num_messages;)
4640 gint ret;
4642 ret = sendmmsg (socket->priv->fd, msgvec + num_sent, num_messages - num_sent,
4643 flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4645 if (ret < 0)
4647 int errsv = get_socket_errno ();
4649 if (errsv == EINTR)
4650 continue;
4652 if (timeout != 0 &&
4653 (errsv == EWOULDBLOCK ||
4654 errsv == EAGAIN))
4656 if (!block_on_timeout (socket, G_IO_OUT, timeout, start_time,
4657 cancellable, error))
4659 if (num_sent > 0)
4661 g_clear_error (error);
4662 break;
4665 return -1;
4668 continue;
4671 /* If any messages were successfully sent, do not error. */
4672 if (num_sent > 0)
4673 break;
4675 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4677 return -1;
4680 num_sent += ret;
4683 for (i = 0; i < num_sent; ++i)
4684 messages[i].bytes_sent = msgvec[i].msg_len;
4686 return num_sent;
4688 #else
4690 gssize result;
4691 gint i;
4692 gint64 wait_timeout;
4694 wait_timeout = timeout;
4696 for (i = 0; i < num_messages; ++i)
4698 GOutputMessage *msg = &messages[i];
4699 GError *msg_error = NULL;
4701 result = g_socket_send_message_with_timeout (socket, msg->address,
4702 msg->vectors,
4703 msg->num_vectors,
4704 msg->control_messages,
4705 msg->num_control_messages,
4706 flags, wait_timeout,
4707 cancellable, &msg_error);
4709 /* check if we've timed out or how much time to wait at most */
4710 if (timeout > 0)
4712 gint64 elapsed = g_get_monotonic_time () - start_time;
4713 wait_timeout = MAX (timeout - elapsed, 1);
4716 if (result < 0)
4718 /* if we couldn't send all messages, just return how many we did
4719 * manage to send, provided we managed to send at least one */
4720 if (i > 0)
4722 g_error_free (msg_error);
4723 return i;
4725 else
4727 g_propagate_error (error, msg_error);
4728 return -1;
4732 msg->bytes_sent = result;
4735 return i;
4737 #endif
4740 static GSocketAddress *
4741 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
4743 GSocketAddress *saddr;
4744 gint i;
4745 guint64 oldest_time = G_MAXUINT64;
4746 gint oldest_index = 0;
4748 if (native_len <= 0)
4749 return NULL;
4751 saddr = NULL;
4752 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
4754 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
4755 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
4756 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
4758 if (!tmp)
4759 continue;
4761 if (tmp_native_len != native_len)
4762 continue;
4764 if (memcmp (tmp_native, native, native_len) == 0)
4766 saddr = g_object_ref (tmp);
4767 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
4768 return saddr;
4771 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
4773 oldest_time = socket->priv->recv_addr_cache[i].last_used;
4774 oldest_index = i;
4778 saddr = g_socket_address_new_from_native (native, native_len);
4780 if (socket->priv->recv_addr_cache[oldest_index].addr)
4782 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
4783 g_free (socket->priv->recv_addr_cache[oldest_index].native);
4786 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
4787 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
4788 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
4789 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
4791 return saddr;
4794 static gssize
4795 g_socket_receive_message_with_timeout (GSocket *socket,
4796 GSocketAddress **address,
4797 GInputVector *vectors,
4798 gint num_vectors,
4799 GSocketControlMessage ***messages,
4800 gint *num_messages,
4801 gint *flags,
4802 gint64 timeout,
4803 GCancellable *cancellable,
4804 GError **error)
4806 GInputVector one_vector;
4807 char one_byte;
4808 gint64 start_time;
4810 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4812 start_time = g_get_monotonic_time ();
4814 if (!check_socket (socket, error))
4815 return -1;
4817 if (!check_timeout (socket, error))
4818 return -1;
4820 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4821 return -1;
4823 if (num_vectors == -1)
4825 for (num_vectors = 0;
4826 vectors[num_vectors].buffer != NULL;
4827 num_vectors++)
4831 if (num_vectors == 0)
4833 one_vector.buffer = &one_byte;
4834 one_vector.size = 1;
4835 num_vectors = 1;
4836 vectors = &one_vector;
4839 #ifndef G_OS_WIN32
4841 GInputMessage input_message;
4842 struct msghdr msg;
4843 gssize result;
4845 input_message.address = address;
4846 input_message.vectors = vectors;
4847 input_message.num_vectors = num_vectors;
4848 input_message.bytes_received = 0;
4849 input_message.flags = (flags != NULL) ? *flags : 0;
4850 input_message.control_messages = messages;
4851 input_message.num_control_messages = (guint *) num_messages;
4853 /* We always set the close-on-exec flag so we don't leak file
4854 * descriptors into child processes. Note that gunixfdmessage.c
4855 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4857 #ifdef MSG_CMSG_CLOEXEC
4858 input_message.flags |= MSG_CMSG_CLOEXEC;
4859 #endif
4861 input_message_to_msghdr (&input_message, &msg);
4863 /* do it */
4864 while (1)
4866 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4867 #ifdef MSG_CMSG_CLOEXEC
4868 if (result < 0 && get_socket_errno () == EINVAL)
4870 /* We must be running on an old kernel. Call without the flag. */
4871 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4872 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4874 #endif
4876 if (result < 0)
4878 int errsv = get_socket_errno ();
4880 if (errsv == EINTR)
4881 continue;
4883 if (timeout != 0 &&
4884 (errsv == EWOULDBLOCK ||
4885 errsv == EAGAIN))
4887 if (!block_on_timeout (socket, G_IO_IN, timeout, start_time,
4888 cancellable, error))
4889 return -1;
4891 continue;
4894 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
4895 return -1;
4897 break;
4900 input_message_from_msghdr (&msg, &input_message, socket);
4902 if (flags != NULL)
4903 *flags = input_message.flags;
4905 return result;
4907 #else
4909 struct sockaddr_storage addr;
4910 int addrlen;
4911 DWORD bytes_received;
4912 DWORD win_flags;
4913 int result;
4914 WSABUF *bufs;
4915 gint i;
4917 /* iov */
4918 bufs = g_newa (WSABUF, num_vectors);
4919 for (i = 0; i < num_vectors; i++)
4921 bufs[i].buf = (char *)vectors[i].buffer;
4922 bufs[i].len = (gulong)vectors[i].size;
4925 /* flags */
4926 if (flags != NULL)
4927 win_flags = *flags;
4928 else
4929 win_flags = 0;
4931 /* do it */
4932 while (1)
4934 win32_unset_event_mask (socket, FD_READ);
4936 addrlen = sizeof addr;
4937 if (address)
4938 result = WSARecvFrom (socket->priv->fd,
4939 bufs, num_vectors,
4940 &bytes_received, &win_flags,
4941 (struct sockaddr *)&addr, &addrlen,
4942 NULL, NULL);
4943 else
4944 result = WSARecv (socket->priv->fd,
4945 bufs, num_vectors,
4946 &bytes_received, &win_flags,
4947 NULL, NULL);
4948 if (result != 0)
4950 int errsv = get_socket_errno ();
4952 if (errsv == WSAEINTR)
4953 continue;
4955 if (errsv == WSAEWOULDBLOCK)
4957 if (timeout != 0)
4959 if (!block_on_timeout (socket, G_IO_IN, timeout,
4960 start_time, cancellable, error))
4961 return -1;
4963 continue;
4967 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
4968 return -1;
4970 break;
4973 /* decode address */
4974 if (address != NULL)
4976 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
4979 /* capture the flags */
4980 if (flags != NULL)
4981 *flags = win_flags;
4983 if (messages != NULL)
4984 *messages = NULL;
4985 if (num_messages != NULL)
4986 *num_messages = 0;
4988 return bytes_received;
4990 #endif
4994 * g_socket_receive_messages:
4995 * @socket: a #GSocket
4996 * @messages: (array length=num_messages): an array of #GInputMessage structs
4997 * @num_messages: the number of elements in @messages
4998 * @flags: an int containing #GSocketMsgFlags flags for the overall operation
4999 * @cancellable: (nullable): a %GCancellable or %NULL
5000 * @error: #GError for error reporting, or %NULL to ignore
5002 * Receive multiple data messages from @socket in one go. This is the most
5003 * complicated and fully-featured version of this call. For easier use, see
5004 * g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
5006 * @messages must point to an array of #GInputMessage structs and
5007 * @num_messages must be the length of this array. Each #GInputMessage
5008 * contains a pointer to an array of #GInputVector structs describing the
5009 * buffers that the data received in each message will be written to. Using
5010 * multiple #GInputVectors is more memory-efficient than manually copying data
5011 * out of a single buffer to multiple sources, and more system-call-efficient
5012 * than making multiple calls to g_socket_receive(), such as in scenarios where
5013 * a lot of data packets need to be received (e.g. high-bandwidth video
5014 * streaming over RTP/UDP).
5016 * @flags modify how all messages are received. The commonly available
5017 * arguments for this are available in the #GSocketMsgFlags enum, but the
5018 * values there are the same as the system values, and the flags
5019 * are passed in as-is, so you can pass in system-specific flags too. These
5020 * flags affect the overall receive operation. Flags affecting individual
5021 * messages are returned in #GInputMessage.flags.
5023 * The other members of #GInputMessage are treated as described in its
5024 * documentation.
5026 * If #GSocket:blocking is %TRUE the call will block until @num_messages have
5027 * been received, or the end of the stream is reached.
5029 * If #GSocket:blocking is %FALSE the call will return up to @num_messages
5030 * without blocking, or %G_IO_ERROR_WOULD_BLOCK if no messages are queued in the
5031 * operating system to be received.
5033 * In blocking mode, if #GSocket:timeout is positive and is reached before any
5034 * messages are received, %G_IO_ERROR_TIMED_OUT is returned, otherwise up to
5035 * @num_messages are returned. (Note: This is effectively the
5036 * behaviour of `MSG_WAITFORONE` with recvmmsg().)
5038 * To be notified when messages are available, wait for the
5039 * %G_IO_IN condition. Note though that you may still receive
5040 * %G_IO_ERROR_WOULD_BLOCK from g_socket_receive_messages() even if you were
5041 * previously notified of a %G_IO_IN condition.
5043 * If the remote peer closes the connection, any messages queued in the
5044 * operating system will be returned, and subsequent calls to
5045 * g_socket_receive_messages() will return 0 (with no error set).
5047 * On error -1 is returned and @error is set accordingly. An error will only
5048 * be returned if zero messages could be received; otherwise the number of
5049 * messages successfully received before the error will be returned.
5051 * Returns: number of messages received, or -1 on error. Note that the number
5052 * of messages received may be smaller than @num_messages if in non-blocking
5053 * mode, if the peer closed the connection, or if @num_messages
5054 * was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
5055 * to receive the remaining messages.
5057 * Since: 2.48
5059 gint
5060 g_socket_receive_messages (GSocket *socket,
5061 GInputMessage *messages,
5062 guint num_messages,
5063 gint flags,
5064 GCancellable *cancellable,
5065 GError **error)
5067 if (!check_socket (socket, error) ||
5068 !check_timeout (socket, error))
5069 return -1;
5071 return g_socket_receive_messages_with_timeout (socket, messages, num_messages,
5072 flags,
5073 socket->priv->blocking ? -1 : 0,
5074 cancellable, error);
5077 static gint
5078 g_socket_receive_messages_with_timeout (GSocket *socket,
5079 GInputMessage *messages,
5080 guint num_messages,
5081 gint flags,
5082 gint64 timeout,
5083 GCancellable *cancellable,
5084 GError **error)
5086 gint64 start_time;
5088 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5089 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5090 g_return_val_if_fail (cancellable == NULL ||
5091 G_IS_CANCELLABLE (cancellable), -1);
5092 g_return_val_if_fail (error == NULL || *error == NULL, -1);
5094 start_time = g_get_monotonic_time ();
5096 if (!check_socket (socket, error))
5097 return -1;
5099 if (!check_timeout (socket, error))
5100 return -1;
5102 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5103 return -1;
5105 if (num_messages == 0)
5106 return 0;
5108 #if !defined (G_OS_WIN32) && defined (HAVE_RECVMMSG)
5110 struct mmsghdr *msgvec;
5111 guint i, num_received;
5113 #ifdef UIO_MAXIOV
5114 #define MAX_NUM_MESSAGES UIO_MAXIOV
5115 #else
5116 #define MAX_NUM_MESSAGES 1024
5117 #endif
5119 if (num_messages > MAX_NUM_MESSAGES)
5120 num_messages = MAX_NUM_MESSAGES;
5122 msgvec = g_newa (struct mmsghdr, num_messages);
5124 for (i = 0; i < num_messages; ++i)
5126 GInputMessage *msg = &messages[i];
5127 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5129 input_message_to_msghdr (msg, msg_hdr);
5130 msgvec[i].msg_len = 0;
5133 /* We always set the close-on-exec flag so we don't leak file
5134 * descriptors into child processes. Note that gunixfdmessage.c
5135 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5137 #ifdef MSG_CMSG_CLOEXEC
5138 flags |= MSG_CMSG_CLOEXEC;
5139 #endif
5141 for (num_received = 0; num_received < num_messages;)
5143 gint ret;
5145 /* We operate in non-blocking mode and handle the timeout ourselves. */
5146 ret = recvmmsg (socket->priv->fd,
5147 msgvec + num_received,
5148 num_messages - num_received,
5149 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5150 #ifdef MSG_CMSG_CLOEXEC
5151 if (ret < 0 && get_socket_errno () == EINVAL)
5153 /* We must be running on an old kernel. Call without the flag. */
5154 flags &= ~(MSG_CMSG_CLOEXEC);
5155 ret = recvmmsg (socket->priv->fd,
5156 msgvec + num_received,
5157 num_messages - num_received,
5158 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5160 #endif
5162 if (ret < 0)
5164 int errsv = get_socket_errno ();
5166 if (errsv == EINTR)
5167 continue;
5169 if (timeout != 0 &&
5170 (errsv == EWOULDBLOCK ||
5171 errsv == EAGAIN))
5173 if (!block_on_timeout (socket, G_IO_IN, timeout, start_time,
5174 cancellable, error))
5176 if (num_received > 0)
5178 g_clear_error (error);
5179 break;
5182 return -1;
5185 continue;
5188 /* If any messages were successfully received, do not error. */
5189 if (num_received > 0)
5190 break;
5192 socket_set_error_lazy (error, errsv,
5193 _("Error receiving message: %s"));
5195 return -1;
5197 else if (ret == 0)
5199 /* EOS. */
5200 break;
5203 num_received += ret;
5206 for (i = 0; i < num_received; ++i)
5208 input_message_from_msghdr (&msgvec[i].msg_hdr, &messages[i], socket);
5209 messages[i].bytes_received = msgvec[i].msg_len;
5212 return num_received;
5214 #else
5216 guint i;
5217 gint64 wait_timeout;
5219 wait_timeout = timeout;
5221 for (i = 0; i < num_messages; i++)
5223 GInputMessage *msg = &messages[i];
5224 gssize len;
5225 GError *msg_error = NULL;
5227 msg->flags = flags; /* in-out parameter */
5229 len = g_socket_receive_message_with_timeout (socket,
5230 msg->address,
5231 msg->vectors,
5232 msg->num_vectors,
5233 msg->control_messages,
5234 (gint *) msg->num_control_messages,
5235 &msg->flags,
5236 wait_timeout,
5237 cancellable,
5238 &msg_error);
5240 /* check if we've timed out or how much time to wait at most */
5241 if (timeout > 0)
5243 gint64 elapsed = g_get_monotonic_time () - start_time;
5244 wait_timeout = MAX (timeout - elapsed, 1);
5247 if (len >= 0)
5248 msg->bytes_received = len;
5250 if (i != 0 &&
5251 (g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK) ||
5252 g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)))
5254 g_clear_error (&msg_error);
5255 break;
5258 if (msg_error != NULL)
5260 g_propagate_error (error, msg_error);
5261 return -1;
5264 if (len == 0)
5265 break;
5268 return i;
5270 #endif
5274 * g_socket_receive_message:
5275 * @socket: a #GSocket
5276 * @address: (out) (optional): a pointer to a #GSocketAddress
5277 * pointer, or %NULL
5278 * @vectors: (array length=num_vectors): an array of #GInputVector structs
5279 * @num_vectors: the number of elements in @vectors, or -1
5280 * @messages: (array length=num_messages) (out) (optional) (nullable): a pointer
5281 * which may be filled with an array of #GSocketControlMessages, or %NULL
5282 * @num_messages: (out): a pointer which will be filled with the number of
5283 * elements in @messages, or %NULL
5284 * @flags: (inout): a pointer to an int containing #GSocketMsgFlags flags
5285 * @cancellable: a %GCancellable or %NULL
5286 * @error: a #GError pointer, or %NULL
5288 * Receive data from a socket. For receiving multiple messages, see
5289 * g_socket_receive_messages(); for easier use, see
5290 * g_socket_receive() and g_socket_receive_from().
5292 * If @address is non-%NULL then @address will be set equal to the
5293 * source address of the received packet.
5294 * @address is owned by the caller.
5296 * @vector must point to an array of #GInputVector structs and
5297 * @num_vectors must be the length of this array. These structs
5298 * describe the buffers that received data will be scattered into.
5299 * If @num_vectors is -1, then @vectors is assumed to be terminated
5300 * by a #GInputVector with a %NULL buffer pointer.
5302 * As a special case, if @num_vectors is 0 (in which case, @vectors
5303 * may of course be %NULL), then a single byte is received and
5304 * discarded. This is to facilitate the common practice of sending a
5305 * single '\0' byte for the purposes of transferring ancillary data.
5307 * @messages, if non-%NULL, will be set to point to a newly-allocated
5308 * array of #GSocketControlMessage instances or %NULL if no such
5309 * messages was received. These correspond to the control messages
5310 * received from the kernel, one #GSocketControlMessage per message
5311 * from the kernel. This array is %NULL-terminated and must be freed
5312 * by the caller using g_free() after calling g_object_unref() on each
5313 * element. If @messages is %NULL, any control messages received will
5314 * be discarded.
5316 * @num_messages, if non-%NULL, will be set to the number of control
5317 * messages received.
5319 * If both @messages and @num_messages are non-%NULL, then
5320 * @num_messages gives the number of #GSocketControlMessage instances
5321 * in @messages (ie: not including the %NULL terminator).
5323 * @flags is an in/out parameter. The commonly available arguments
5324 * for this are available in the #GSocketMsgFlags enum, but the
5325 * values there are the same as the system values, and the flags
5326 * are passed in as-is, so you can pass in system-specific flags too
5327 * (and g_socket_receive_message() may pass system-specific flags out).
5328 * Flags passed in to the parameter affect the receive operation; flags returned
5329 * out of it are relevant to the specific returned message.
5331 * As with g_socket_receive(), data may be discarded if @socket is
5332 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
5333 * provide enough buffer space to read a complete message. You can pass
5334 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
5335 * removing it from the receive queue, but there is no portable way to find
5336 * out the length of the message other than by reading it into a
5337 * sufficiently-large buffer.
5339 * If the socket is in blocking mode the call will block until there
5340 * is some data to receive, the connection is closed, or there is an
5341 * error. If there is no data available and the socket is in
5342 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
5343 * returned. To be notified when data is available, wait for the
5344 * %G_IO_IN condition.
5346 * On error -1 is returned and @error is set accordingly.
5348 * Returns: Number of bytes read, or 0 if the connection was closed by
5349 * the peer, or -1 on error
5351 * Since: 2.22
5353 gssize
5354 g_socket_receive_message (GSocket *socket,
5355 GSocketAddress **address,
5356 GInputVector *vectors,
5357 gint num_vectors,
5358 GSocketControlMessage ***messages,
5359 gint *num_messages,
5360 gint *flags,
5361 GCancellable *cancellable,
5362 GError **error)
5364 return g_socket_receive_message_with_timeout (socket, address, vectors,
5365 num_vectors, messages,
5366 num_messages, flags,
5367 socket->priv->blocking ? -1 : 0,
5368 cancellable, error);
5372 * g_socket_get_credentials:
5373 * @socket: a #GSocket.
5374 * @error: #GError for error reporting, or %NULL to ignore.
5376 * Returns the credentials of the foreign process connected to this
5377 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
5378 * sockets).
5380 * If this operation isn't supported on the OS, the method fails with
5381 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
5382 * by reading the %SO_PEERCRED option on the underlying socket.
5384 * Other ways to obtain credentials from a foreign peer includes the
5385 * #GUnixCredentialsMessage type and
5386 * g_unix_connection_send_credentials() /
5387 * g_unix_connection_receive_credentials() functions.
5389 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
5390 * that must be freed with g_object_unref().
5392 * Since: 2.26
5394 GCredentials *
5395 g_socket_get_credentials (GSocket *socket,
5396 GError **error)
5398 GCredentials *ret;
5400 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
5401 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5403 ret = NULL;
5405 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
5407 #ifdef SO_PEERCRED
5409 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
5410 socklen_t optlen = sizeof (native_creds_buf);
5412 if (getsockopt (socket->priv->fd,
5413 SOL_SOCKET,
5414 SO_PEERCRED,
5415 native_creds_buf,
5416 &optlen) == 0)
5418 ret = g_credentials_new ();
5419 g_credentials_set_native (ret,
5420 G_CREDENTIALS_NATIVE_TYPE,
5421 native_creds_buf);
5424 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
5426 struct unpcbid cred;
5427 socklen_t optlen = sizeof (cred);
5429 if (getsockopt (socket->priv->fd,
5431 LOCAL_PEEREID,
5432 &cred,
5433 &optlen) == 0)
5435 ret = g_credentials_new ();
5436 g_credentials_set_native (ret,
5437 G_CREDENTIALS_NATIVE_TYPE,
5438 &cred);
5441 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
5443 ucred_t *ucred = NULL;
5445 if (getpeerucred (socket->priv->fd, &ucred) == 0)
5447 ret = g_credentials_new ();
5448 g_credentials_set_native (ret,
5449 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
5450 ucred);
5451 ucred_free (ucred);
5454 #else
5455 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
5456 #endif
5458 if (!ret)
5460 int errsv = get_socket_errno ();
5462 g_set_error (error,
5463 G_IO_ERROR,
5464 socket_io_error_from_errno (errsv),
5465 _("Unable to read socket credentials: %s"),
5466 socket_strerror (errsv));
5469 #else
5471 g_set_error_literal (error,
5472 G_IO_ERROR,
5473 G_IO_ERROR_NOT_SUPPORTED,
5474 _("g_socket_get_credentials not implemented for this OS"));
5475 #endif
5477 return ret;
5481 * g_socket_get_option:
5482 * @socket: a #GSocket
5483 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5484 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5485 * @value: (out): return location for the option value
5486 * @error: #GError for error reporting, or %NULL to ignore.
5488 * Gets the value of an integer-valued option on @socket, as with
5489 * getsockopt(). (If you need to fetch a non-integer-valued option,
5490 * you will need to call getsockopt() directly.)
5492 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5493 * header pulls in system headers that will define most of the
5494 * standard/portable socket options. For unusual socket protocols or
5495 * platform-dependent options, you may need to include additional
5496 * headers.
5498 * Note that even for socket options that are a single byte in size,
5499 * @value is still a pointer to a #gint variable, not a #guchar;
5500 * g_socket_get_option() will handle the conversion internally.
5502 * Returns: success or failure. On failure, @error will be set, and
5503 * the system error value (`errno` or WSAGetLastError()) will still
5504 * be set to the result of the getsockopt() call.
5506 * Since: 2.36
5508 gboolean
5509 g_socket_get_option (GSocket *socket,
5510 gint level,
5511 gint optname,
5512 gint *value,
5513 GError **error)
5515 guint size;
5517 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
5519 *value = 0;
5520 size = sizeof (gint);
5521 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
5523 int errsv = get_socket_errno ();
5525 g_set_error_literal (error,
5526 G_IO_ERROR,
5527 socket_io_error_from_errno (errsv),
5528 socket_strerror (errsv));
5529 #ifndef G_OS_WIN32
5530 /* Reset errno in case the caller wants to look at it */
5531 errno = errsv;
5532 #endif
5533 return FALSE;
5536 #if G_BYTE_ORDER == G_BIG_ENDIAN
5537 /* If the returned value is smaller than an int then we need to
5538 * slide it over into the low-order bytes of *value.
5540 if (size != sizeof (gint))
5541 *value = *value >> (8 * (sizeof (gint) - size));
5542 #endif
5544 return TRUE;
5548 * g_socket_set_option:
5549 * @socket: a #GSocket
5550 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5551 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5552 * @value: the value to set the option to
5553 * @error: #GError for error reporting, or %NULL to ignore.
5555 * Sets the value of an integer-valued option on @socket, as with
5556 * setsockopt(). (If you need to set a non-integer-valued option,
5557 * you will need to call setsockopt() directly.)
5559 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5560 * header pulls in system headers that will define most of the
5561 * standard/portable socket options. For unusual socket protocols or
5562 * platform-dependent options, you may need to include additional
5563 * headers.
5565 * Returns: success or failure. On failure, @error will be set, and
5566 * the system error value (`errno` or WSAGetLastError()) will still
5567 * be set to the result of the setsockopt() call.
5569 * Since: 2.36
5571 gboolean
5572 g_socket_set_option (GSocket *socket,
5573 gint level,
5574 gint optname,
5575 gint value,
5576 GError **error)
5578 gint errsv;
5580 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
5582 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
5583 return TRUE;
5585 #if !defined (__linux__) && !defined (G_OS_WIN32)
5586 /* Linux and Windows let you set a single-byte value from an int,
5587 * but most other platforms don't.
5589 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
5591 #if G_BYTE_ORDER == G_BIG_ENDIAN
5592 value = value << (8 * (sizeof (gint) - 1));
5593 #endif
5594 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
5595 return TRUE;
5597 #endif
5599 errsv = get_socket_errno ();
5601 g_set_error_literal (error,
5602 G_IO_ERROR,
5603 socket_io_error_from_errno (errsv),
5604 socket_strerror (errsv));
5605 #ifndef G_OS_WIN32
5606 errno = errsv;
5607 #endif
5608 return FALSE;