Add some more cases to the app-id unit tests
[glib.git] / gio / gsocket.c
blobc7555ba4725b9f7948da45d9fe56f317ff6a42ac
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 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 #include "gcancellable.h"
56 #include "gdatagrambased.h"
57 #include "gioenumtypes.h"
58 #include "ginetaddress.h"
59 #include "ginitable.h"
60 #include "gioerror.h"
61 #include "gioenums.h"
62 #include "gioerror.h"
63 #include "gnetworkingprivate.h"
64 #include "gsocketaddress.h"
65 #include "gsocketcontrolmessage.h"
66 #include "gcredentials.h"
67 #include "gcredentialsprivate.h"
68 #include "glibintl.h"
70 #ifdef G_OS_WIN32
71 /* For Windows XP runtime compatibility, but use the system's if_nametoindex() if available */
72 #include "gwin32networking.h"
73 #endif
75 /**
76 * SECTION:gsocket
77 * @short_description: Low-level socket object
78 * @include: gio/gio.h
79 * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
81 * A #GSocket is a low-level networking primitive. It is a more or less
82 * direct mapping of the BSD socket API in a portable GObject based API.
83 * It supports both the UNIX socket implementations and winsock2 on Windows.
85 * #GSocket is the platform independent base upon which the higher level
86 * network primitives are based. Applications are not typically meant to
87 * use it directly, but rather through classes like #GSocketClient,
88 * #GSocketService and #GSocketConnection. However there may be cases where
89 * direct use of #GSocket is useful.
91 * #GSocket implements the #GInitable interface, so if it is manually constructed
92 * by e.g. g_object_new() you must call g_initable_init() and check the
93 * results before using the object. This is done automatically in
94 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
95 * %NULL.
97 * Sockets operate in two general modes, blocking or non-blocking. When
98 * in blocking mode all operations (which don’t take an explicit blocking
99 * parameter) block until the requested operation
100 * is finished or there is an error. In non-blocking mode all calls that
101 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
102 * To know when a call would successfully run you can call g_socket_condition_check(),
103 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
104 * attach it to a #GMainContext to get callbacks when I/O is possible.
105 * Note that all sockets are always set to non blocking mode in the system, and
106 * blocking mode is emulated in GSocket.
108 * When working in non-blocking mode applications should always be able to
109 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
110 * function said that I/O was possible. This can easily happen in case
111 * of a race condition in the application, but it can also happen for other
112 * reasons. For instance, on Windows a socket is always seen as writable
113 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
115 * #GSockets can be either connection oriented or datagram based.
116 * For connection oriented types you must first establish a connection by
117 * either connecting to an address or accepting a connection from another
118 * address. For connectionless socket types the target/source address is
119 * specified or received in each I/O operation.
121 * All socket file descriptors are set to be close-on-exec.
123 * Note that creating a #GSocket causes the signal %SIGPIPE to be
124 * ignored for the remainder of the program. If you are writing a
125 * command-line utility that uses #GSocket, you may need to take into
126 * account the fact that your program will not automatically be killed
127 * if it tries to write to %stdout after it has been closed.
129 * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
130 * a #GSocket concurrently from multiple threads, you must implement your own
131 * locking.
133 * Since: 2.22
136 static void g_socket_initable_iface_init (GInitableIface *iface);
137 static gboolean g_socket_initable_init (GInitable *initable,
138 GCancellable *cancellable,
139 GError **error);
141 static void g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface);
142 static gint g_socket_datagram_based_receive_messages (GDatagramBased *self,
143 GInputMessage *messages,
144 guint num_messages,
145 gint flags,
146 gint64 timeout,
147 GCancellable *cancellable,
148 GError **error);
149 static gint g_socket_datagram_based_send_messages (GDatagramBased *self,
150 GOutputMessage *messages,
151 guint num_messages,
152 gint flags,
153 gint64 timeout,
154 GCancellable *cancellable,
155 GError **error);
156 static GSource *g_socket_datagram_based_create_source (GDatagramBased *self,
157 GIOCondition condition,
158 GCancellable *cancellable);
159 static GIOCondition g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
160 GIOCondition condition);
161 static gboolean g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
162 GIOCondition condition,
163 gint64 timeout,
164 GCancellable *cancellable,
165 GError **error);
167 static GSocketAddress *
168 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len);
170 static gssize
171 g_socket_receive_message_with_timeout (GSocket *socket,
172 GSocketAddress **address,
173 GInputVector *vectors,
174 gint num_vectors,
175 GSocketControlMessage ***messages,
176 gint *num_messages,
177 gint *flags,
178 gint64 timeout,
179 GCancellable *cancellable,
180 GError **error);
181 static gint
182 g_socket_receive_messages_with_timeout (GSocket *socket,
183 GInputMessage *messages,
184 guint num_messages,
185 gint flags,
186 gint64 timeout,
187 GCancellable *cancellable,
188 GError **error);
189 static gssize
190 g_socket_send_message_with_timeout (GSocket *socket,
191 GSocketAddress *address,
192 GOutputVector *vectors,
193 gint num_vectors,
194 GSocketControlMessage **messages,
195 gint num_messages,
196 gint flags,
197 gint64 timeout,
198 GCancellable *cancellable,
199 GError **error);
200 static gint
201 g_socket_send_messages_with_timeout (GSocket *socket,
202 GOutputMessage *messages,
203 guint num_messages,
204 gint flags,
205 gint64 timeout,
206 GCancellable *cancellable,
207 GError **error);
209 enum
211 PROP_0,
212 PROP_FAMILY,
213 PROP_TYPE,
214 PROP_PROTOCOL,
215 PROP_FD,
216 PROP_BLOCKING,
217 PROP_LISTEN_BACKLOG,
218 PROP_KEEPALIVE,
219 PROP_LOCAL_ADDRESS,
220 PROP_REMOTE_ADDRESS,
221 PROP_TIMEOUT,
222 PROP_TTL,
223 PROP_BROADCAST,
224 PROP_MULTICAST_LOOPBACK,
225 PROP_MULTICAST_TTL
228 /* Size of the receiver cache for g_socket_receive_from() */
229 #define RECV_ADDR_CACHE_SIZE 8
231 struct _GSocketPrivate
233 GSocketFamily family;
234 GSocketType type;
235 GSocketProtocol protocol;
236 gint fd;
237 gint listen_backlog;
238 guint timeout;
239 GError *construct_error;
240 GSocketAddress *remote_address;
241 guint inited : 1;
242 guint blocking : 1;
243 guint keepalive : 1;
244 guint closed : 1;
245 guint connected_read : 1;
246 guint connected_write : 1;
247 guint listening : 1;
248 guint timed_out : 1;
249 guint connect_pending : 1;
250 #ifdef G_OS_WIN32
251 WSAEVENT event;
252 gboolean waiting;
253 DWORD waiting_result;
254 int current_events;
255 int current_errors;
256 int selected_events;
257 GList *requested_conditions; /* list of requested GIOCondition * */
258 GMutex win32_source_lock;
259 GCond win32_source_cond;
260 #endif
262 struct {
263 GSocketAddress *addr;
264 struct sockaddr *native;
265 gint native_len;
266 guint64 last_used;
267 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
270 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
271 G_ADD_PRIVATE (GSocket)
272 g_networking_init ();
273 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
274 g_socket_initable_iface_init);
275 G_IMPLEMENT_INTERFACE (G_TYPE_DATAGRAM_BASED,
276 g_socket_datagram_based_iface_init));
278 static int
279 get_socket_errno (void)
281 #ifndef G_OS_WIN32
282 return errno;
283 #else
284 return WSAGetLastError ();
285 #endif
288 static GIOErrorEnum
289 socket_io_error_from_errno (int err)
291 #ifdef G_OS_WIN32
292 return g_io_error_from_win32_error (err);
293 #else
294 return g_io_error_from_errno (err);
295 #endif
298 static const char *
299 socket_strerror (int err)
301 #ifndef G_OS_WIN32
302 return g_strerror (err);
303 #else
304 const char *msg_ret;
305 char *msg;
307 msg = g_win32_error_message (err);
309 msg_ret = g_intern_string (msg);
310 g_free (msg);
312 return msg_ret;
313 #endif
316 /* Wrapper around g_set_error() to avoid doing excess work */
317 #define socket_set_error_lazy(err, errsv, fmt) \
318 G_STMT_START { \
319 GError **__err = (err); \
320 int __errsv = (errsv); \
322 if (__err) \
324 int __code = socket_io_error_from_errno (__errsv); \
325 const char *__strerr = socket_strerror (__errsv); \
327 if (__code == G_IO_ERROR_WOULD_BLOCK) \
328 g_set_error_literal (__err, G_IO_ERROR, __code, __strerr); \
329 else \
330 g_set_error (__err, G_IO_ERROR, __code, fmt, __strerr); \
332 } G_STMT_END
334 #ifdef G_OS_WIN32
335 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
336 static void
337 _win32_unset_event_mask (GSocket *socket, int mask)
339 g_mutex_lock (&socket->priv->win32_source_lock);
340 socket->priv->current_events &= ~mask;
341 socket->priv->current_errors &= ~mask;
342 g_mutex_unlock (&socket->priv->win32_source_lock);
344 #else
345 #define win32_unset_event_mask(_socket, _mask)
346 #endif
348 /* Windows has broken prototypes... */
349 #ifdef G_OS_WIN32
350 #define getsockopt(sockfd, level, optname, optval, optlen) \
351 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
352 #define setsockopt(sockfd, level, optname, optval, optlen) \
353 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
354 #define getsockname(sockfd, addr, addrlen) \
355 getsockname (sockfd, addr, (int *)addrlen)
356 #define getpeername(sockfd, addr, addrlen) \
357 getpeername (sockfd, addr, (int *)addrlen)
358 #define recv(sockfd, buf, len, flags) \
359 recv (sockfd, (gpointer)buf, len, flags)
360 #endif
362 static gboolean
363 check_socket (GSocket *socket,
364 GError **error)
366 if (!socket->priv->inited)
368 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
369 _("Invalid socket, not initialized"));
370 return FALSE;
373 if (socket->priv->construct_error)
375 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
376 _("Invalid socket, initialization failed due to: %s"),
377 socket->priv->construct_error->message);
378 return FALSE;
381 if (socket->priv->closed)
383 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
384 _("Socket is already closed"));
385 return FALSE;
388 return TRUE;
391 static gboolean
392 check_timeout (GSocket *socket,
393 GError **error)
395 if (socket->priv->timed_out)
397 socket->priv->timed_out = FALSE;
398 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
399 _("Socket I/O timed out"));
400 return FALSE;
403 return TRUE;
406 static void
407 g_socket_details_from_fd (GSocket *socket)
409 struct sockaddr_storage address;
410 gint fd;
411 guint addrlen;
412 int value, family;
413 int errsv;
415 fd = socket->priv->fd;
416 if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
418 errsv = get_socket_errno ();
419 goto err;
422 switch (value)
424 case SOCK_STREAM:
425 socket->priv->type = G_SOCKET_TYPE_STREAM;
426 break;
428 case SOCK_DGRAM:
429 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
430 break;
432 case SOCK_SEQPACKET:
433 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
434 break;
436 default:
437 socket->priv->type = G_SOCKET_TYPE_INVALID;
438 break;
441 addrlen = sizeof address;
442 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
444 errsv = get_socket_errno ();
445 goto err;
448 if (addrlen > 0)
450 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
451 sizeof address.ss_family <= addrlen);
452 family = address.ss_family;
454 else
456 /* On Solaris, this happens if the socket is not yet connected.
457 * But we can use SO_DOMAIN as a workaround there.
459 #ifdef SO_DOMAIN
460 if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
462 errsv = get_socket_errno ();
463 goto err;
465 #else
466 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
467 errsv = -1;
468 goto err;
469 #endif
472 switch (family)
474 case G_SOCKET_FAMILY_IPV4:
475 case G_SOCKET_FAMILY_IPV6:
476 socket->priv->family = address.ss_family;
477 switch (socket->priv->type)
479 case G_SOCKET_TYPE_STREAM:
480 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
481 break;
483 case G_SOCKET_TYPE_DATAGRAM:
484 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
485 break;
487 case G_SOCKET_TYPE_SEQPACKET:
488 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
489 break;
491 default:
492 break;
494 break;
496 case G_SOCKET_FAMILY_UNIX:
497 socket->priv->family = G_SOCKET_FAMILY_UNIX;
498 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
499 break;
501 default:
502 socket->priv->family = G_SOCKET_FAMILY_INVALID;
503 break;
506 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
508 addrlen = sizeof address;
509 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
511 socket->priv->connected_read = TRUE;
512 socket->priv->connected_write = TRUE;
516 if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
518 socket->priv->keepalive = !!value;
520 else
522 /* Can't read, maybe not supported, assume FALSE */
523 socket->priv->keepalive = FALSE;
526 return;
528 err:
529 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
530 socket_io_error_from_errno (errsv),
531 _("creating GSocket from fd: %s"),
532 socket_strerror (errsv));
535 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
536 gint
537 g_socket (gint domain,
538 gint type,
539 gint protocol,
540 GError **error)
542 int fd;
544 #ifdef SOCK_CLOEXEC
545 fd = socket (domain, type | SOCK_CLOEXEC, protocol);
546 if (fd != -1)
547 return fd;
549 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
550 if (fd < 0 && (errno == EINVAL || errno == EPROTOTYPE))
551 #endif
552 fd = socket (domain, type, protocol);
554 if (fd < 0)
556 int errsv = get_socket_errno ();
558 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
559 _("Unable to create socket: %s"), socket_strerror (errsv));
560 errno = errsv;
561 return -1;
564 #ifndef G_OS_WIN32
566 int flags;
568 /* We always want to set close-on-exec to protect users. If you
569 need to so some weird inheritance to exec you can re-enable this
570 using lower level hacks with g_socket_get_fd(). */
571 flags = fcntl (fd, F_GETFD, 0);
572 if (flags != -1 &&
573 (flags & FD_CLOEXEC) == 0)
575 flags |= FD_CLOEXEC;
576 fcntl (fd, F_SETFD, flags);
579 #endif
581 return fd;
584 static gint
585 g_socket_create_socket (GSocketFamily family,
586 GSocketType type,
587 int protocol,
588 GError **error)
590 gint native_type;
592 switch (type)
594 case G_SOCKET_TYPE_STREAM:
595 native_type = SOCK_STREAM;
596 break;
598 case G_SOCKET_TYPE_DATAGRAM:
599 native_type = SOCK_DGRAM;
600 break;
602 case G_SOCKET_TYPE_SEQPACKET:
603 native_type = SOCK_SEQPACKET;
604 break;
606 default:
607 g_assert_not_reached ();
610 if (family <= 0)
612 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
613 _("Unable to create socket: %s"), _("Unknown family was specified"));
614 return -1;
617 if (protocol == -1)
619 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
620 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
621 return -1;
624 return g_socket (family, native_type, protocol, error);
627 static void
628 g_socket_constructed (GObject *object)
630 GSocket *socket = G_SOCKET (object);
632 if (socket->priv->fd >= 0)
633 /* create socket->priv info from the fd */
634 g_socket_details_from_fd (socket);
636 else
637 /* create the fd from socket->priv info */
638 socket->priv->fd = g_socket_create_socket (socket->priv->family,
639 socket->priv->type,
640 socket->priv->protocol,
641 &socket->priv->construct_error);
643 if (socket->priv->fd != -1)
645 #ifndef G_OS_WIN32
646 GError *error = NULL;
647 #else
648 gulong arg;
649 #endif
651 /* Always use native nonblocking sockets, as Windows sets sockets to
652 * nonblocking automatically in certain operations. This way we make
653 * things work the same on all platforms.
655 #ifndef G_OS_WIN32
656 if (!g_unix_set_fd_nonblocking (socket->priv->fd, TRUE, &error))
658 g_warning ("Error setting socket nonblocking: %s", error->message);
659 g_clear_error (&error);
661 #else
662 arg = TRUE;
664 if (ioctlsocket (socket->priv->fd, FIONBIO, &arg) == SOCKET_ERROR)
666 int errsv = get_socket_errno ();
667 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
669 #endif
671 #ifdef SO_NOSIGPIPE
672 /* See note about SIGPIPE below. */
673 g_socket_set_option (socket, SOL_SOCKET, SO_NOSIGPIPE, TRUE, NULL);
674 #endif
678 static void
679 g_socket_get_property (GObject *object,
680 guint prop_id,
681 GValue *value,
682 GParamSpec *pspec)
684 GSocket *socket = G_SOCKET (object);
685 GSocketAddress *address;
687 switch (prop_id)
689 case PROP_FAMILY:
690 g_value_set_enum (value, socket->priv->family);
691 break;
693 case PROP_TYPE:
694 g_value_set_enum (value, socket->priv->type);
695 break;
697 case PROP_PROTOCOL:
698 g_value_set_enum (value, socket->priv->protocol);
699 break;
701 case PROP_FD:
702 g_value_set_int (value, socket->priv->fd);
703 break;
705 case PROP_BLOCKING:
706 g_value_set_boolean (value, socket->priv->blocking);
707 break;
709 case PROP_LISTEN_BACKLOG:
710 g_value_set_int (value, socket->priv->listen_backlog);
711 break;
713 case PROP_KEEPALIVE:
714 g_value_set_boolean (value, socket->priv->keepalive);
715 break;
717 case PROP_LOCAL_ADDRESS:
718 address = g_socket_get_local_address (socket, NULL);
719 g_value_take_object (value, address);
720 break;
722 case PROP_REMOTE_ADDRESS:
723 address = g_socket_get_remote_address (socket, NULL);
724 g_value_take_object (value, address);
725 break;
727 case PROP_TIMEOUT:
728 g_value_set_uint (value, socket->priv->timeout);
729 break;
731 case PROP_TTL:
732 g_value_set_uint (value, g_socket_get_ttl (socket));
733 break;
735 case PROP_BROADCAST:
736 g_value_set_boolean (value, g_socket_get_broadcast (socket));
737 break;
739 case PROP_MULTICAST_LOOPBACK:
740 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
741 break;
743 case PROP_MULTICAST_TTL:
744 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
745 break;
747 default:
748 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
752 static void
753 g_socket_set_property (GObject *object,
754 guint prop_id,
755 const GValue *value,
756 GParamSpec *pspec)
758 GSocket *socket = G_SOCKET (object);
760 switch (prop_id)
762 case PROP_FAMILY:
763 socket->priv->family = g_value_get_enum (value);
764 break;
766 case PROP_TYPE:
767 socket->priv->type = g_value_get_enum (value);
768 break;
770 case PROP_PROTOCOL:
771 socket->priv->protocol = g_value_get_enum (value);
772 break;
774 case PROP_FD:
775 socket->priv->fd = g_value_get_int (value);
776 break;
778 case PROP_BLOCKING:
779 g_socket_set_blocking (socket, g_value_get_boolean (value));
780 break;
782 case PROP_LISTEN_BACKLOG:
783 g_socket_set_listen_backlog (socket, g_value_get_int (value));
784 break;
786 case PROP_KEEPALIVE:
787 g_socket_set_keepalive (socket, g_value_get_boolean (value));
788 break;
790 case PROP_TIMEOUT:
791 g_socket_set_timeout (socket, g_value_get_uint (value));
792 break;
794 case PROP_TTL:
795 g_socket_set_ttl (socket, g_value_get_uint (value));
796 break;
798 case PROP_BROADCAST:
799 g_socket_set_broadcast (socket, g_value_get_boolean (value));
800 break;
802 case PROP_MULTICAST_LOOPBACK:
803 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
804 break;
806 case PROP_MULTICAST_TTL:
807 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
808 break;
810 default:
811 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
815 static void
816 g_socket_finalize (GObject *object)
818 GSocket *socket = G_SOCKET (object);
819 gint i;
821 g_clear_error (&socket->priv->construct_error);
823 if (socket->priv->fd != -1 &&
824 !socket->priv->closed)
825 g_socket_close (socket, NULL);
827 if (socket->priv->remote_address)
828 g_object_unref (socket->priv->remote_address);
830 #ifdef G_OS_WIN32
831 if (socket->priv->event != WSA_INVALID_EVENT)
833 WSACloseEvent (socket->priv->event);
834 socket->priv->event = WSA_INVALID_EVENT;
837 g_assert (socket->priv->requested_conditions == NULL);
838 g_mutex_clear (&socket->priv->win32_source_lock);
839 g_cond_clear (&socket->priv->win32_source_cond);
840 #endif
842 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
844 if (socket->priv->recv_addr_cache[i].addr)
846 g_object_unref (socket->priv->recv_addr_cache[i].addr);
847 g_free (socket->priv->recv_addr_cache[i].native);
851 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
852 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
855 static void
856 g_socket_class_init (GSocketClass *klass)
858 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
860 #ifdef SIGPIPE
861 /* There is no portable, thread-safe way to avoid having the process
862 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
863 * forced to simply ignore the signal process-wide.
865 * Even if we ignore it though, gdb will still stop if the app
866 * receives a SIGPIPE, which can be confusing and annoying. So when
867 * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
868 * prevent the signal from occurring at all.
870 signal (SIGPIPE, SIG_IGN);
871 #endif
873 gobject_class->finalize = g_socket_finalize;
874 gobject_class->constructed = g_socket_constructed;
875 gobject_class->set_property = g_socket_set_property;
876 gobject_class->get_property = g_socket_get_property;
878 g_object_class_install_property (gobject_class, PROP_FAMILY,
879 g_param_spec_enum ("family",
880 P_("Socket family"),
881 P_("The sockets address family"),
882 G_TYPE_SOCKET_FAMILY,
883 G_SOCKET_FAMILY_INVALID,
884 G_PARAM_CONSTRUCT_ONLY |
885 G_PARAM_READWRITE |
886 G_PARAM_STATIC_STRINGS));
888 g_object_class_install_property (gobject_class, PROP_TYPE,
889 g_param_spec_enum ("type",
890 P_("Socket type"),
891 P_("The sockets type"),
892 G_TYPE_SOCKET_TYPE,
893 G_SOCKET_TYPE_STREAM,
894 G_PARAM_CONSTRUCT_ONLY |
895 G_PARAM_READWRITE |
896 G_PARAM_STATIC_STRINGS));
898 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
899 g_param_spec_enum ("protocol",
900 P_("Socket protocol"),
901 P_("The id of the protocol to use, or -1 for unknown"),
902 G_TYPE_SOCKET_PROTOCOL,
903 G_SOCKET_PROTOCOL_UNKNOWN,
904 G_PARAM_CONSTRUCT_ONLY |
905 G_PARAM_READWRITE |
906 G_PARAM_STATIC_STRINGS));
908 g_object_class_install_property (gobject_class, PROP_FD,
909 g_param_spec_int ("fd",
910 P_("File descriptor"),
911 P_("The sockets file descriptor"),
912 G_MININT,
913 G_MAXINT,
915 G_PARAM_CONSTRUCT_ONLY |
916 G_PARAM_READWRITE |
917 G_PARAM_STATIC_STRINGS));
919 g_object_class_install_property (gobject_class, PROP_BLOCKING,
920 g_param_spec_boolean ("blocking",
921 P_("blocking"),
922 P_("Whether or not I/O on this socket is blocking"),
923 TRUE,
924 G_PARAM_READWRITE |
925 G_PARAM_STATIC_STRINGS));
927 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
928 g_param_spec_int ("listen-backlog",
929 P_("Listen backlog"),
930 P_("Outstanding connections in the listen queue"),
932 SOMAXCONN,
934 G_PARAM_READWRITE |
935 G_PARAM_STATIC_STRINGS));
937 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
938 g_param_spec_boolean ("keepalive",
939 P_("Keep connection alive"),
940 P_("Keep connection alive by sending periodic pings"),
941 FALSE,
942 G_PARAM_READWRITE |
943 G_PARAM_STATIC_STRINGS));
945 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
946 g_param_spec_object ("local-address",
947 P_("Local address"),
948 P_("The local address the socket is bound to"),
949 G_TYPE_SOCKET_ADDRESS,
950 G_PARAM_READABLE |
951 G_PARAM_STATIC_STRINGS));
953 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
954 g_param_spec_object ("remote-address",
955 P_("Remote address"),
956 P_("The remote address the socket is connected to"),
957 G_TYPE_SOCKET_ADDRESS,
958 G_PARAM_READABLE |
959 G_PARAM_STATIC_STRINGS));
962 * GSocket:timeout:
964 * The timeout in seconds on socket I/O
966 * Since: 2.26
968 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
969 g_param_spec_uint ("timeout",
970 P_("Timeout"),
971 P_("The timeout in seconds on socket I/O"),
973 G_MAXUINT,
975 G_PARAM_READWRITE |
976 G_PARAM_STATIC_STRINGS));
979 * GSocket:broadcast:
981 * Whether the socket should allow sending to broadcast addresses.
983 * Since: 2.32
985 g_object_class_install_property (gobject_class, PROP_BROADCAST,
986 g_param_spec_boolean ("broadcast",
987 P_("Broadcast"),
988 P_("Whether to allow sending to broadcast addresses"),
989 FALSE,
990 G_PARAM_READWRITE |
991 G_PARAM_STATIC_STRINGS));
994 * GSocket:ttl:
996 * Time-to-live for outgoing unicast packets
998 * Since: 2.32
1000 g_object_class_install_property (gobject_class, PROP_TTL,
1001 g_param_spec_uint ("ttl",
1002 P_("TTL"),
1003 P_("Time-to-live of outgoing unicast packets"),
1004 0, G_MAXUINT, 0,
1005 G_PARAM_READWRITE |
1006 G_PARAM_STATIC_STRINGS));
1009 * GSocket:multicast-loopback:
1011 * Whether outgoing multicast packets loop back to the local host.
1013 * Since: 2.32
1015 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
1016 g_param_spec_boolean ("multicast-loopback",
1017 P_("Multicast loopback"),
1018 P_("Whether outgoing multicast packets loop back to the local host"),
1019 TRUE,
1020 G_PARAM_READWRITE |
1021 G_PARAM_STATIC_STRINGS));
1024 * GSocket:multicast-ttl:
1026 * Time-to-live out outgoing multicast packets
1028 * Since: 2.32
1030 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
1031 g_param_spec_uint ("multicast-ttl",
1032 P_("Multicast TTL"),
1033 P_("Time-to-live of outgoing multicast packets"),
1034 0, G_MAXUINT, 1,
1035 G_PARAM_READWRITE |
1036 G_PARAM_STATIC_STRINGS));
1039 static void
1040 g_socket_initable_iface_init (GInitableIface *iface)
1042 iface->init = g_socket_initable_init;
1045 static void
1046 g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface)
1048 iface->receive_messages = g_socket_datagram_based_receive_messages;
1049 iface->send_messages = g_socket_datagram_based_send_messages;
1050 iface->create_source = g_socket_datagram_based_create_source;
1051 iface->condition_check = g_socket_datagram_based_condition_check;
1052 iface->condition_wait = g_socket_datagram_based_condition_wait;
1055 static void
1056 g_socket_init (GSocket *socket)
1058 socket->priv = g_socket_get_instance_private (socket);
1060 socket->priv->fd = -1;
1061 socket->priv->blocking = TRUE;
1062 socket->priv->listen_backlog = 10;
1063 socket->priv->construct_error = NULL;
1064 #ifdef G_OS_WIN32
1065 socket->priv->event = WSA_INVALID_EVENT;
1066 g_mutex_init (&socket->priv->win32_source_lock);
1067 g_cond_init (&socket->priv->win32_source_cond);
1068 #endif
1071 static gboolean
1072 g_socket_initable_init (GInitable *initable,
1073 GCancellable *cancellable,
1074 GError **error)
1076 GSocket *socket;
1078 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
1080 socket = G_SOCKET (initable);
1082 if (cancellable != NULL)
1084 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1085 _("Cancellable initialization not supported"));
1086 return FALSE;
1089 socket->priv->inited = TRUE;
1091 if (socket->priv->construct_error)
1093 if (error)
1094 *error = g_error_copy (socket->priv->construct_error);
1095 return FALSE;
1099 return TRUE;
1102 static gboolean
1103 check_datagram_based (GDatagramBased *self,
1104 GError **error)
1106 switch (g_socket_get_socket_type (G_SOCKET (self)))
1108 case G_SOCKET_TYPE_INVALID:
1109 case G_SOCKET_TYPE_STREAM:
1110 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1111 _("Cannot use datagram operations on a non-datagram "
1112 "socket."));
1113 return FALSE;
1114 case G_SOCKET_TYPE_DATAGRAM:
1115 case G_SOCKET_TYPE_SEQPACKET:
1116 /* Fall through. */
1117 break;
1120 /* Due to us sharing #GSocketSource with the #GSocket implementation, it is
1121 * pretty tricky to split out #GSocket:timeout so that it does not affect
1122 * #GDatagramBased operations (but still affects #GSocket operations). It is
1123 * not worth that effort — just disallow it and require the user to specify
1124 * timeouts on a per-operation basis. */
1125 if (g_socket_get_timeout (G_SOCKET (self)) != 0)
1127 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1128 _("Cannot use datagram operations on a socket with a "
1129 "timeout set."));
1130 return FALSE;
1133 return TRUE;
1136 static gint
1137 g_socket_datagram_based_receive_messages (GDatagramBased *self,
1138 GInputMessage *messages,
1139 guint num_messages,
1140 gint flags,
1141 gint64 timeout,
1142 GCancellable *cancellable,
1143 GError **error)
1145 if (!check_datagram_based (self, error))
1146 return FALSE;
1148 return g_socket_receive_messages_with_timeout (G_SOCKET (self), messages,
1149 num_messages, flags, timeout,
1150 cancellable, error);
1153 static gint
1154 g_socket_datagram_based_send_messages (GDatagramBased *self,
1155 GOutputMessage *messages,
1156 guint num_messages,
1157 gint flags,
1158 gint64 timeout,
1159 GCancellable *cancellable,
1160 GError **error)
1162 if (!check_datagram_based (self, error))
1163 return FALSE;
1165 return g_socket_send_messages_with_timeout (G_SOCKET (self), messages,
1166 num_messages, flags, timeout,
1167 cancellable, error);
1170 static GSource *
1171 g_socket_datagram_based_create_source (GDatagramBased *self,
1172 GIOCondition condition,
1173 GCancellable *cancellable)
1175 if (!check_datagram_based (self, NULL))
1176 return NULL;
1178 return g_socket_create_source (G_SOCKET (self), condition, cancellable);
1181 static GIOCondition
1182 g_socket_datagram_based_condition_check (GDatagramBased *datagram_based,
1183 GIOCondition condition)
1185 if (!check_datagram_based (datagram_based, NULL))
1186 return G_IO_ERR;
1188 return g_socket_condition_check (G_SOCKET (datagram_based), condition);
1191 static gboolean
1192 g_socket_datagram_based_condition_wait (GDatagramBased *datagram_based,
1193 GIOCondition condition,
1194 gint64 timeout,
1195 GCancellable *cancellable,
1196 GError **error)
1198 if (!check_datagram_based (datagram_based, error))
1199 return FALSE;
1201 return g_socket_condition_timed_wait (G_SOCKET (datagram_based), condition,
1202 timeout, cancellable, error);
1206 * g_socket_new:
1207 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1208 * @type: the socket type to use.
1209 * @protocol: the id of the protocol to use, or 0 for default.
1210 * @error: #GError for error reporting, or %NULL to ignore.
1212 * Creates a new #GSocket with the defined family, type and protocol.
1213 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1214 * for the family and type is used.
1216 * The @protocol is a family and type specific int that specifies what
1217 * kind of protocol to use. #GSocketProtocol lists several common ones.
1218 * Many families only support one protocol, and use 0 for this, others
1219 * support several and using 0 means to use the default protocol for
1220 * the family and type.
1222 * The protocol id is passed directly to the operating
1223 * system, so you can use protocols not listed in #GSocketProtocol if you
1224 * know the protocol number used for it.
1226 * Returns: a #GSocket or %NULL on error.
1227 * Free the returned object with g_object_unref().
1229 * Since: 2.22
1231 GSocket *
1232 g_socket_new (GSocketFamily family,
1233 GSocketType type,
1234 GSocketProtocol protocol,
1235 GError **error)
1237 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1238 NULL, error,
1239 "family", family,
1240 "type", type,
1241 "protocol", protocol,
1242 NULL));
1246 * g_socket_new_from_fd:
1247 * @fd: a native socket file descriptor.
1248 * @error: #GError for error reporting, or %NULL to ignore.
1250 * Creates a new #GSocket from a native file descriptor
1251 * or winsock SOCKET handle.
1253 * This reads all the settings from the file descriptor so that
1254 * all properties should work. Note that the file descriptor
1255 * will be set to non-blocking mode, independent on the blocking
1256 * mode of the #GSocket.
1258 * On success, the returned #GSocket takes ownership of @fd. On failure, the
1259 * caller must close @fd themselves.
1261 * Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
1262 * descriptor. Instead, a GError will be set with code %G_IO_ERROR_FAILED
1264 * Returns: a #GSocket or %NULL on error.
1265 * Free the returned object with g_object_unref().
1267 * Since: 2.22
1269 GSocket *
1270 g_socket_new_from_fd (gint fd,
1271 GError **error)
1273 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1274 NULL, error,
1275 "fd", fd,
1276 NULL));
1280 * g_socket_set_blocking:
1281 * @socket: a #GSocket.
1282 * @blocking: Whether to use blocking I/O or not.
1284 * Sets the blocking mode of the socket. In blocking mode
1285 * all operations (which don’t take an explicit blocking parameter) block until
1286 * they succeed or there is an error. In
1287 * non-blocking mode all functions return results immediately or
1288 * with a %G_IO_ERROR_WOULD_BLOCK error.
1290 * All sockets are created in blocking mode. However, note that the
1291 * platform level socket is always non-blocking, and blocking mode
1292 * is a GSocket level feature.
1294 * Since: 2.22
1296 void
1297 g_socket_set_blocking (GSocket *socket,
1298 gboolean blocking)
1300 g_return_if_fail (G_IS_SOCKET (socket));
1302 blocking = !!blocking;
1304 if (socket->priv->blocking == blocking)
1305 return;
1307 socket->priv->blocking = blocking;
1308 g_object_notify (G_OBJECT (socket), "blocking");
1312 * g_socket_get_blocking:
1313 * @socket: a #GSocket.
1315 * Gets the blocking mode of the socket. For details on blocking I/O,
1316 * see g_socket_set_blocking().
1318 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1320 * Since: 2.22
1322 gboolean
1323 g_socket_get_blocking (GSocket *socket)
1325 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1327 return socket->priv->blocking;
1331 * g_socket_set_keepalive:
1332 * @socket: a #GSocket.
1333 * @keepalive: Value for the keepalive flag
1335 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1336 * this flag is set on a socket, the system will attempt to verify that the
1337 * remote socket endpoint is still present if a sufficiently long period of
1338 * time passes with no data being exchanged. If the system is unable to
1339 * verify the presence of the remote endpoint, it will automatically close
1340 * the connection.
1342 * This option is only functional on certain kinds of sockets. (Notably,
1343 * %G_SOCKET_PROTOCOL_TCP sockets.)
1345 * The exact time between pings is system- and protocol-dependent, but will
1346 * normally be at least two hours. Most commonly, you would set this flag
1347 * on a server socket if you want to allow clients to remain idle for long
1348 * periods of time, but also want to ensure that connections are eventually
1349 * garbage-collected if clients crash or become unreachable.
1351 * Since: 2.22
1353 void
1354 g_socket_set_keepalive (GSocket *socket,
1355 gboolean keepalive)
1357 GError *error = NULL;
1359 g_return_if_fail (G_IS_SOCKET (socket));
1361 keepalive = !!keepalive;
1362 if (socket->priv->keepalive == keepalive)
1363 return;
1365 if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1366 keepalive, &error))
1368 g_warning ("error setting keepalive: %s", error->message);
1369 g_error_free (error);
1370 return;
1373 socket->priv->keepalive = keepalive;
1374 g_object_notify (G_OBJECT (socket), "keepalive");
1378 * g_socket_get_keepalive:
1379 * @socket: a #GSocket.
1381 * Gets the keepalive mode of the socket. For details on this,
1382 * see g_socket_set_keepalive().
1384 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1386 * Since: 2.22
1388 gboolean
1389 g_socket_get_keepalive (GSocket *socket)
1391 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1393 return socket->priv->keepalive;
1397 * g_socket_get_listen_backlog:
1398 * @socket: a #GSocket.
1400 * Gets the listen backlog setting of the socket. For details on this,
1401 * see g_socket_set_listen_backlog().
1403 * Returns: the maximum number of pending connections.
1405 * Since: 2.22
1407 gint
1408 g_socket_get_listen_backlog (GSocket *socket)
1410 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1412 return socket->priv->listen_backlog;
1416 * g_socket_set_listen_backlog:
1417 * @socket: a #GSocket.
1418 * @backlog: the maximum number of pending connections.
1420 * Sets the maximum number of outstanding connections allowed
1421 * when listening on this socket. If more clients than this are
1422 * connecting to the socket and the application is not handling them
1423 * on time then the new connections will be refused.
1425 * Note that this must be called before g_socket_listen() and has no
1426 * effect if called after that.
1428 * Since: 2.22
1430 void
1431 g_socket_set_listen_backlog (GSocket *socket,
1432 gint backlog)
1434 g_return_if_fail (G_IS_SOCKET (socket));
1435 g_return_if_fail (!socket->priv->listening);
1437 if (backlog != socket->priv->listen_backlog)
1439 socket->priv->listen_backlog = backlog;
1440 g_object_notify (G_OBJECT (socket), "listen-backlog");
1445 * g_socket_get_timeout:
1446 * @socket: a #GSocket.
1448 * Gets the timeout setting of the socket. For details on this, see
1449 * g_socket_set_timeout().
1451 * Returns: the timeout in seconds
1453 * Since: 2.26
1455 guint
1456 g_socket_get_timeout (GSocket *socket)
1458 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1460 return socket->priv->timeout;
1464 * g_socket_set_timeout:
1465 * @socket: a #GSocket.
1466 * @timeout: the timeout for @socket, in seconds, or 0 for none
1468 * Sets the time in seconds after which I/O operations on @socket will
1469 * time out if they have not yet completed.
1471 * On a blocking socket, this means that any blocking #GSocket
1472 * operation will time out after @timeout seconds of inactivity,
1473 * returning %G_IO_ERROR_TIMED_OUT.
1475 * On a non-blocking socket, calls to g_socket_condition_wait() will
1476 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1477 * created with g_socket_create_source() will trigger after
1478 * @timeout seconds of inactivity, with the requested condition
1479 * set, at which point calling g_socket_receive(), g_socket_send(),
1480 * g_socket_check_connect_result(), etc, will fail with
1481 * %G_IO_ERROR_TIMED_OUT.
1483 * If @timeout is 0 (the default), operations will never time out
1484 * on their own.
1486 * Note that if an I/O operation is interrupted by a signal, this may
1487 * cause the timeout to be reset.
1489 * Since: 2.26
1491 void
1492 g_socket_set_timeout (GSocket *socket,
1493 guint timeout)
1495 g_return_if_fail (G_IS_SOCKET (socket));
1497 if (timeout != socket->priv->timeout)
1499 socket->priv->timeout = timeout;
1500 g_object_notify (G_OBJECT (socket), "timeout");
1505 * g_socket_get_ttl:
1506 * @socket: a #GSocket.
1508 * Gets the unicast time-to-live setting on @socket; see
1509 * g_socket_set_ttl() for more details.
1511 * Returns: the time-to-live setting on @socket
1513 * Since: 2.32
1515 guint
1516 g_socket_get_ttl (GSocket *socket)
1518 GError *error = NULL;
1519 gint value;
1521 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1523 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1525 g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1526 &value, &error);
1528 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1530 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1531 &value, &error);
1533 else
1534 g_return_val_if_reached (0);
1536 if (error)
1538 g_warning ("error getting unicast ttl: %s", error->message);
1539 g_error_free (error);
1540 return 0;
1543 return value;
1547 * g_socket_set_ttl:
1548 * @socket: a #GSocket.
1549 * @ttl: the time-to-live value for all unicast packets on @socket
1551 * Sets the time-to-live for outgoing unicast packets on @socket.
1552 * By default the platform-specific default value is used.
1554 * Since: 2.32
1556 void
1557 g_socket_set_ttl (GSocket *socket,
1558 guint ttl)
1560 GError *error = NULL;
1562 g_return_if_fail (G_IS_SOCKET (socket));
1564 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1566 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1567 ttl, &error);
1569 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1571 g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1572 ttl, NULL);
1573 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1574 ttl, &error);
1576 else
1577 g_return_if_reached ();
1579 if (error)
1581 g_warning ("error setting unicast ttl: %s", error->message);
1582 g_error_free (error);
1583 return;
1586 g_object_notify (G_OBJECT (socket), "ttl");
1590 * g_socket_get_broadcast:
1591 * @socket: a #GSocket.
1593 * Gets the broadcast setting on @socket; if %TRUE,
1594 * it is possible to send packets to broadcast
1595 * addresses.
1597 * Returns: the broadcast setting on @socket
1599 * Since: 2.32
1601 gboolean
1602 g_socket_get_broadcast (GSocket *socket)
1604 GError *error = NULL;
1605 gint value;
1607 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1609 if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1610 &value, &error))
1612 g_warning ("error getting broadcast: %s", error->message);
1613 g_error_free (error);
1614 return FALSE;
1617 return !!value;
1621 * g_socket_set_broadcast:
1622 * @socket: a #GSocket.
1623 * @broadcast: whether @socket should allow sending to broadcast
1624 * addresses
1626 * Sets whether @socket should allow sending to broadcast addresses.
1627 * This is %FALSE by default.
1629 * Since: 2.32
1631 void
1632 g_socket_set_broadcast (GSocket *socket,
1633 gboolean broadcast)
1635 GError *error = NULL;
1637 g_return_if_fail (G_IS_SOCKET (socket));
1639 broadcast = !!broadcast;
1641 if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1642 broadcast, &error))
1644 g_warning ("error setting broadcast: %s", error->message);
1645 g_error_free (error);
1646 return;
1649 g_object_notify (G_OBJECT (socket), "broadcast");
1653 * g_socket_get_multicast_loopback:
1654 * @socket: a #GSocket.
1656 * Gets the multicast loopback setting on @socket; if %TRUE (the
1657 * default), outgoing multicast packets will be looped back to
1658 * multicast listeners on the same host.
1660 * Returns: the multicast loopback setting on @socket
1662 * Since: 2.32
1664 gboolean
1665 g_socket_get_multicast_loopback (GSocket *socket)
1667 GError *error = NULL;
1668 gint value;
1670 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1672 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1674 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1675 &value, &error);
1677 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1679 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1680 &value, &error);
1682 else
1683 g_return_val_if_reached (FALSE);
1685 if (error)
1687 g_warning ("error getting multicast loopback: %s", error->message);
1688 g_error_free (error);
1689 return FALSE;
1692 return !!value;
1696 * g_socket_set_multicast_loopback:
1697 * @socket: a #GSocket.
1698 * @loopback: whether @socket should receive messages sent to its
1699 * multicast groups from the local host
1701 * Sets whether outgoing multicast packets will be received by sockets
1702 * listening on that multicast address on the same host. This is %TRUE
1703 * by default.
1705 * Since: 2.32
1707 void
1708 g_socket_set_multicast_loopback (GSocket *socket,
1709 gboolean loopback)
1711 GError *error = NULL;
1713 g_return_if_fail (G_IS_SOCKET (socket));
1715 loopback = !!loopback;
1717 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1719 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1720 loopback, &error);
1722 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1724 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1725 loopback, NULL);
1726 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1727 loopback, &error);
1729 else
1730 g_return_if_reached ();
1732 if (error)
1734 g_warning ("error setting multicast loopback: %s", error->message);
1735 g_error_free (error);
1736 return;
1739 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1743 * g_socket_get_multicast_ttl:
1744 * @socket: a #GSocket.
1746 * Gets the multicast time-to-live setting on @socket; see
1747 * g_socket_set_multicast_ttl() for more details.
1749 * Returns: the multicast time-to-live setting on @socket
1751 * Since: 2.32
1753 guint
1754 g_socket_get_multicast_ttl (GSocket *socket)
1756 GError *error = NULL;
1757 gint value;
1759 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1761 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1763 g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1764 &value, &error);
1766 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1768 g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1769 &value, &error);
1771 else
1772 g_return_val_if_reached (FALSE);
1774 if (error)
1776 g_warning ("error getting multicast ttl: %s", error->message);
1777 g_error_free (error);
1778 return FALSE;
1781 return value;
1785 * g_socket_set_multicast_ttl:
1786 * @socket: a #GSocket.
1787 * @ttl: the time-to-live value for all multicast datagrams on @socket
1789 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1790 * By default, this is 1, meaning that multicast packets will not leave
1791 * the local network.
1793 * Since: 2.32
1795 void
1796 g_socket_set_multicast_ttl (GSocket *socket,
1797 guint ttl)
1799 GError *error = NULL;
1801 g_return_if_fail (G_IS_SOCKET (socket));
1803 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1805 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1806 ttl, &error);
1808 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1810 g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1811 ttl, NULL);
1812 g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1813 ttl, &error);
1815 else
1816 g_return_if_reached ();
1818 if (error)
1820 g_warning ("error setting multicast ttl: %s", error->message);
1821 g_error_free (error);
1822 return;
1825 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1829 * g_socket_get_family:
1830 * @socket: a #GSocket.
1832 * Gets the socket family of the socket.
1834 * Returns: a #GSocketFamily
1836 * Since: 2.22
1838 GSocketFamily
1839 g_socket_get_family (GSocket *socket)
1841 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1843 return socket->priv->family;
1847 * g_socket_get_socket_type:
1848 * @socket: a #GSocket.
1850 * Gets the socket type of the socket.
1852 * Returns: a #GSocketType
1854 * Since: 2.22
1856 GSocketType
1857 g_socket_get_socket_type (GSocket *socket)
1859 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1861 return socket->priv->type;
1865 * g_socket_get_protocol:
1866 * @socket: a #GSocket.
1868 * Gets the socket protocol id the socket was created with.
1869 * In case the protocol is unknown, -1 is returned.
1871 * Returns: a protocol id, or -1 if unknown
1873 * Since: 2.22
1875 GSocketProtocol
1876 g_socket_get_protocol (GSocket *socket)
1878 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1880 return socket->priv->protocol;
1884 * g_socket_get_fd:
1885 * @socket: a #GSocket.
1887 * Returns the underlying OS socket object. On unix this
1888 * is a socket file descriptor, and on Windows this is
1889 * a Winsock2 SOCKET handle. This may be useful for
1890 * doing platform specific or otherwise unusual operations
1891 * on the socket.
1893 * Returns: the file descriptor of the socket.
1895 * Since: 2.22
1898 g_socket_get_fd (GSocket *socket)
1900 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1902 return socket->priv->fd;
1906 * g_socket_get_local_address:
1907 * @socket: a #GSocket.
1908 * @error: #GError for error reporting, or %NULL to ignore.
1910 * Try to get the local address of a bound socket. This is only
1911 * useful if the socket has been bound to a local address,
1912 * either explicitly or implicitly when connecting.
1914 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1915 * Free the returned object with g_object_unref().
1917 * Since: 2.22
1919 GSocketAddress *
1920 g_socket_get_local_address (GSocket *socket,
1921 GError **error)
1923 struct sockaddr_storage buffer;
1924 guint len = sizeof (buffer);
1926 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1928 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1930 int errsv = get_socket_errno ();
1931 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1932 _("could not get local address: %s"), socket_strerror (errsv));
1933 return NULL;
1936 return g_socket_address_new_from_native (&buffer, len);
1940 * g_socket_get_remote_address:
1941 * @socket: a #GSocket.
1942 * @error: #GError for error reporting, or %NULL to ignore.
1944 * Try to get the remove address of a connected socket. This is only
1945 * useful for connection oriented sockets that have been connected.
1947 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1948 * Free the returned object with g_object_unref().
1950 * Since: 2.22
1952 GSocketAddress *
1953 g_socket_get_remote_address (GSocket *socket,
1954 GError **error)
1956 struct sockaddr_storage buffer;
1957 guint len = sizeof (buffer);
1959 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1961 if (socket->priv->connect_pending)
1963 if (!g_socket_check_connect_result (socket, error))
1964 return NULL;
1965 else
1966 socket->priv->connect_pending = FALSE;
1969 if (!socket->priv->remote_address)
1971 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1973 int errsv = get_socket_errno ();
1974 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1975 _("could not get remote address: %s"), socket_strerror (errsv));
1976 return NULL;
1979 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1982 return g_object_ref (socket->priv->remote_address);
1986 * g_socket_is_connected:
1987 * @socket: a #GSocket.
1989 * Check whether the socket is connected. This is only useful for
1990 * connection-oriented sockets.
1992 * If using g_socket_shutdown(), this function will return %TRUE until the
1993 * socket has been shut down for reading and writing. If you do a non-blocking
1994 * connect, this function will not return %TRUE until after you call
1995 * g_socket_check_connect_result().
1997 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1999 * Since: 2.22
2001 gboolean
2002 g_socket_is_connected (GSocket *socket)
2004 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2006 return (socket->priv->connected_read || socket->priv->connected_write);
2010 * g_socket_listen:
2011 * @socket: a #GSocket.
2012 * @error: #GError for error reporting, or %NULL to ignore.
2014 * Marks the socket as a server socket, i.e. a socket that is used
2015 * to accept incoming requests using g_socket_accept().
2017 * Before calling this the socket must be bound to a local address using
2018 * g_socket_bind().
2020 * To set the maximum amount of outstanding clients, use
2021 * g_socket_set_listen_backlog().
2023 * Returns: %TRUE on success, %FALSE on error.
2025 * Since: 2.22
2027 gboolean
2028 g_socket_listen (GSocket *socket,
2029 GError **error)
2031 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2033 if (!check_socket (socket, error))
2034 return FALSE;
2036 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
2038 int errsv = get_socket_errno ();
2040 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2041 _("could not listen: %s"), socket_strerror (errsv));
2042 return FALSE;
2045 socket->priv->listening = TRUE;
2047 return TRUE;
2051 * g_socket_bind:
2052 * @socket: a #GSocket.
2053 * @address: a #GSocketAddress specifying the local address.
2054 * @allow_reuse: whether to allow reusing this address
2055 * @error: #GError for error reporting, or %NULL to ignore.
2057 * When a socket is created it is attached to an address family, but it
2058 * doesn't have an address in this family. g_socket_bind() assigns the
2059 * address (sometimes called name) of the socket.
2061 * It is generally required to bind to a local address before you can
2062 * receive connections. (See g_socket_listen() and g_socket_accept() ).
2063 * In certain situations, you may also want to bind a socket that will be
2064 * used to initiate connections, though this is not normally required.
2066 * If @socket is a TCP socket, then @allow_reuse controls the setting
2067 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
2068 * server sockets (sockets that you will eventually call
2069 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
2070 * set this flag on a server socket may cause g_socket_bind() to return
2071 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
2072 * immediately restarted.)
2074 * If @socket is a UDP socket, then @allow_reuse determines whether or
2075 * not other UDP sockets can be bound to the same address at the same
2076 * time. In particular, you can have several UDP sockets bound to the
2077 * same address, and they will all receive all of the multicast and
2078 * broadcast packets sent to that address. (The behavior of unicast
2079 * UDP packets to an address with multiple listeners is not defined.)
2081 * Returns: %TRUE on success, %FALSE on error.
2083 * Since: 2.22
2085 gboolean
2086 g_socket_bind (GSocket *socket,
2087 GSocketAddress *address,
2088 gboolean reuse_address,
2089 GError **error)
2091 struct sockaddr_storage addr;
2092 gboolean so_reuseaddr;
2093 #ifdef SO_REUSEPORT
2094 gboolean so_reuseport;
2095 #endif
2097 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2099 if (!check_socket (socket, error))
2100 return FALSE;
2102 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2103 return FALSE;
2105 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
2106 * sockets, but has nasty side effects we don't want for TCP
2107 * sockets.
2109 * On other platforms, we set SO_REUSEPORT, if it exists, for
2110 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
2111 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
2112 * the desired semantics on UDP (as it does on Linux, although
2113 * Linux has SO_REUSEPORT too as of 3.9).
2116 #ifdef G_OS_WIN32
2117 so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2118 #else
2119 so_reuseaddr = !!reuse_address;
2120 #endif
2122 #ifdef SO_REUSEPORT
2123 so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2124 #endif
2126 /* Ignore errors here, the only likely error is "not supported", and
2127 * this is a "best effort" thing mainly.
2129 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
2130 #ifdef SO_REUSEPORT
2131 g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
2132 #endif
2134 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
2135 g_socket_address_get_native_size (address)) < 0)
2137 int errsv = get_socket_errno ();
2138 g_set_error (error,
2139 G_IO_ERROR, socket_io_error_from_errno (errsv),
2140 _("Error binding to address: %s"), socket_strerror (errsv));
2141 return FALSE;
2144 return TRUE;
2147 #if !defined(HAVE_IF_NAMETOINDEX) && defined(G_OS_WIN32)
2148 static guint
2149 if_nametoindex (const gchar *iface)
2151 PIP_ADAPTER_ADDRESSES addresses = NULL, p;
2152 gulong addresses_len = 0;
2153 guint idx = 0;
2154 DWORD res;
2156 if (ws2funcs.pIfNameToIndex != NULL)
2157 return ws2funcs.pIfNameToIndex (iface);
2159 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, NULL, &addresses_len);
2160 if (res != NO_ERROR && res != ERROR_BUFFER_OVERFLOW)
2162 if (res == ERROR_NO_DATA)
2163 errno = ENXIO;
2164 else
2165 errno = EINVAL;
2166 return 0;
2169 addresses = g_malloc (addresses_len);
2170 res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, addresses, &addresses_len);
2172 if (res != NO_ERROR)
2174 g_free (addresses);
2175 if (res == ERROR_NO_DATA)
2176 errno = ENXIO;
2177 else
2178 errno = EINVAL;
2179 return 0;
2182 p = addresses;
2183 while (p)
2185 if (strcmp (p->AdapterName, iface) == 0)
2187 idx = p->IfIndex;
2188 break;
2190 p = p->Next;
2193 if (p == NULL)
2194 errno = ENXIO;
2196 g_free (addresses);
2198 return idx;
2201 #define HAVE_IF_NAMETOINDEX 1
2202 #endif
2204 static gboolean
2205 g_socket_multicast_group_operation (GSocket *socket,
2206 GInetAddress *group,
2207 gboolean source_specific,
2208 const gchar *iface,
2209 gboolean join_group,
2210 GError **error)
2212 const guint8 *native_addr;
2213 gint optname, result;
2215 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2216 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2217 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2219 if (!check_socket (socket, error))
2220 return FALSE;
2222 native_addr = g_inet_address_to_bytes (group);
2223 if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2225 #ifdef HAVE_IP_MREQN
2226 struct ip_mreqn mc_req;
2227 #else
2228 struct ip_mreq mc_req;
2229 #endif
2231 memset (&mc_req, 0, sizeof (mc_req));
2232 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2234 #ifdef HAVE_IP_MREQN
2235 if (iface)
2236 mc_req.imr_ifindex = if_nametoindex (iface);
2237 else
2238 mc_req.imr_ifindex = 0; /* Pick any. */
2239 #elif defined(G_OS_WIN32)
2240 if (iface)
2241 mc_req.imr_interface.s_addr = g_htonl (if_nametoindex (iface));
2242 else
2243 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2244 #else
2245 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2246 #endif
2248 if (source_specific)
2250 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2251 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2252 #else
2253 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2254 join_group ?
2255 _("Error joining multicast group: %s") :
2256 _("Error leaving multicast group: %s"),
2257 _("No support for source-specific multicast"));
2258 return FALSE;
2259 #endif
2261 else
2262 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2263 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2264 &mc_req, sizeof (mc_req));
2266 else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2268 struct ipv6_mreq mc_req_ipv6;
2270 memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2271 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2272 #ifdef HAVE_IF_NAMETOINDEX
2273 if (iface)
2274 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2275 else
2276 #endif
2277 mc_req_ipv6.ipv6mr_interface = 0;
2279 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2280 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2281 &mc_req_ipv6, sizeof (mc_req_ipv6));
2283 else
2284 g_return_val_if_reached (FALSE);
2286 if (result < 0)
2288 int errsv = get_socket_errno ();
2290 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2291 join_group ?
2292 _("Error joining multicast group: %s") :
2293 _("Error leaving multicast group: %s"),
2294 socket_strerror (errsv));
2295 return FALSE;
2298 return TRUE;
2302 * g_socket_join_multicast_group:
2303 * @socket: a #GSocket.
2304 * @group: a #GInetAddress specifying the group address to join.
2305 * @iface: (nullable): Name of the interface to use, or %NULL
2306 * @source_specific: %TRUE if source-specific multicast should be used
2307 * @error: #GError for error reporting, or %NULL to ignore.
2309 * Registers @socket to receive multicast messages sent to @group.
2310 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2311 * been bound to an appropriate interface and port with
2312 * g_socket_bind().
2314 * If @iface is %NULL, the system will automatically pick an interface
2315 * to bind to based on @group.
2317 * If @source_specific is %TRUE, source-specific multicast as defined
2318 * in RFC 4604 is used. Note that on older platforms this may fail
2319 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2321 * Returns: %TRUE on success, %FALSE on error.
2323 * Since: 2.32
2325 gboolean
2326 g_socket_join_multicast_group (GSocket *socket,
2327 GInetAddress *group,
2328 gboolean source_specific,
2329 const gchar *iface,
2330 GError **error)
2332 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2336 * g_socket_leave_multicast_group:
2337 * @socket: a #GSocket.
2338 * @group: a #GInetAddress specifying the group address to leave.
2339 * @iface: (nullable): Interface used
2340 * @source_specific: %TRUE if source-specific multicast was used
2341 * @error: #GError for error reporting, or %NULL to ignore.
2343 * Removes @socket from the multicast group defined by @group, @iface,
2344 * and @source_specific (which must all have the same values they had
2345 * when you joined the group).
2347 * @socket remains bound to its address and port, and can still receive
2348 * unicast messages after calling this.
2350 * Returns: %TRUE on success, %FALSE on error.
2352 * Since: 2.32
2354 gboolean
2355 g_socket_leave_multicast_group (GSocket *socket,
2356 GInetAddress *group,
2357 gboolean source_specific,
2358 const gchar *iface,
2359 GError **error)
2361 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2365 * g_socket_speaks_ipv4:
2366 * @socket: a #GSocket
2368 * Checks if a socket is capable of speaking IPv4.
2370 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2371 * and under some combinations of circumstances IPv6 sockets are also
2372 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2373 * information.
2375 * No other types of sockets are currently considered as being capable
2376 * of speaking IPv4.
2378 * Returns: %TRUE if this socket can be used with IPv4.
2380 * Since: 2.22
2382 gboolean
2383 g_socket_speaks_ipv4 (GSocket *socket)
2385 switch (socket->priv->family)
2387 case G_SOCKET_FAMILY_IPV4:
2388 return TRUE;
2390 case G_SOCKET_FAMILY_IPV6:
2391 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2393 gint v6_only;
2395 if (!g_socket_get_option (socket,
2396 IPPROTO_IPV6, IPV6_V6ONLY,
2397 &v6_only, NULL))
2398 return FALSE;
2400 return !v6_only;
2402 #else
2403 return FALSE;
2404 #endif
2406 default:
2407 return FALSE;
2412 * g_socket_accept:
2413 * @socket: a #GSocket.
2414 * @cancellable: (nullable): a %GCancellable or %NULL
2415 * @error: #GError for error reporting, or %NULL to ignore.
2417 * Accept incoming connections on a connection-based socket. This removes
2418 * the first outstanding connection request from the listening socket and
2419 * creates a #GSocket object for it.
2421 * The @socket must be bound to a local address with g_socket_bind() and
2422 * must be listening for incoming connections (g_socket_listen()).
2424 * If there are no outstanding connections then the operation will block
2425 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2426 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2428 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2429 * Free the returned object with g_object_unref().
2431 * Since: 2.22
2433 GSocket *
2434 g_socket_accept (GSocket *socket,
2435 GCancellable *cancellable,
2436 GError **error)
2438 GSocket *new_socket;
2439 gint ret;
2441 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2443 if (!check_socket (socket, error))
2444 return NULL;
2446 if (!check_timeout (socket, error))
2447 return NULL;
2449 while (TRUE)
2451 win32_unset_event_mask (socket, FD_ACCEPT);
2453 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2455 int errsv = get_socket_errno ();
2457 if (errsv == EINTR)
2458 continue;
2460 #ifdef WSAEWOULDBLOCK
2461 if (errsv == WSAEWOULDBLOCK)
2462 #else
2463 if (errsv == EWOULDBLOCK ||
2464 errsv == EAGAIN)
2465 #endif
2467 if (socket->priv->blocking)
2469 if (!g_socket_condition_wait (socket,
2470 G_IO_IN, cancellable, error))
2471 return NULL;
2473 continue;
2477 socket_set_error_lazy (error, errsv, _("Error accepting connection: %s"));
2478 return NULL;
2480 break;
2483 #ifdef G_OS_WIN32
2485 /* The socket inherits the accepting sockets event mask and even object,
2486 we need to remove that */
2487 WSAEventSelect (ret, NULL, 0);
2489 #else
2491 int flags;
2493 /* We always want to set close-on-exec to protect users. If you
2494 need to so some weird inheritance to exec you can re-enable this
2495 using lower level hacks with g_socket_get_fd(). */
2496 flags = fcntl (ret, F_GETFD, 0);
2497 if (flags != -1 &&
2498 (flags & FD_CLOEXEC) == 0)
2500 flags |= FD_CLOEXEC;
2501 fcntl (ret, F_SETFD, flags);
2504 #endif
2506 new_socket = g_socket_new_from_fd (ret, error);
2507 if (new_socket == NULL)
2509 #ifdef G_OS_WIN32
2510 closesocket (ret);
2511 #else
2512 close (ret);
2513 #endif
2515 else
2516 new_socket->priv->protocol = socket->priv->protocol;
2518 return new_socket;
2522 * g_socket_connect:
2523 * @socket: a #GSocket.
2524 * @address: a #GSocketAddress specifying the remote address.
2525 * @cancellable: (nullable): a %GCancellable or %NULL
2526 * @error: #GError for error reporting, or %NULL to ignore.
2528 * Connect the socket to the specified remote address.
2530 * For connection oriented socket this generally means we attempt to make
2531 * a connection to the @address. For a connection-less socket it sets
2532 * the default address for g_socket_send() and discards all incoming datagrams
2533 * from other sources.
2535 * Generally connection oriented sockets can only connect once, but
2536 * connection-less sockets can connect multiple times to change the
2537 * default address.
2539 * If the connect call needs to do network I/O it will block, unless
2540 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2541 * and the user can be notified of the connection finishing by waiting
2542 * for the G_IO_OUT condition. The result of the connection must then be
2543 * checked with g_socket_check_connect_result().
2545 * Returns: %TRUE if connected, %FALSE on error.
2547 * Since: 2.22
2549 gboolean
2550 g_socket_connect (GSocket *socket,
2551 GSocketAddress *address,
2552 GCancellable *cancellable,
2553 GError **error)
2555 struct sockaddr_storage buffer;
2557 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2559 if (!check_socket (socket, error))
2560 return FALSE;
2562 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2563 return FALSE;
2565 if (socket->priv->remote_address)
2566 g_object_unref (socket->priv->remote_address);
2567 socket->priv->remote_address = g_object_ref (address);
2569 while (1)
2571 win32_unset_event_mask (socket, FD_CONNECT);
2573 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2574 g_socket_address_get_native_size (address)) < 0)
2576 int errsv = get_socket_errno ();
2578 if (errsv == EINTR)
2579 continue;
2581 #ifndef G_OS_WIN32
2582 if (errsv == EINPROGRESS)
2583 #else
2584 if (errsv == WSAEWOULDBLOCK)
2585 #endif
2587 if (socket->priv->blocking)
2589 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2591 if (g_socket_check_connect_result (socket, error))
2592 break;
2595 else
2597 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2598 _("Connection in progress"));
2599 socket->priv->connect_pending = TRUE;
2602 else
2603 g_set_error_literal (error, G_IO_ERROR,
2604 socket_io_error_from_errno (errsv),
2605 socket_strerror (errsv));
2607 return FALSE;
2609 break;
2612 socket->priv->connected_read = TRUE;
2613 socket->priv->connected_write = TRUE;
2615 return TRUE;
2619 * g_socket_check_connect_result:
2620 * @socket: a #GSocket
2621 * @error: #GError for error reporting, or %NULL to ignore.
2623 * Checks and resets the pending connect error for the socket.
2624 * This is used to check for errors when g_socket_connect() is
2625 * used in non-blocking mode.
2627 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2629 * Since: 2.22
2631 gboolean
2632 g_socket_check_connect_result (GSocket *socket,
2633 GError **error)
2635 int value;
2637 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2639 if (!check_socket (socket, error))
2640 return FALSE;
2642 if (!check_timeout (socket, error))
2643 return FALSE;
2645 if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
2647 g_prefix_error (error, _("Unable to get pending error: "));
2648 return FALSE;
2651 if (value != 0)
2653 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2654 socket_strerror (value));
2655 if (socket->priv->remote_address)
2657 g_object_unref (socket->priv->remote_address);
2658 socket->priv->remote_address = NULL;
2660 return FALSE;
2663 socket->priv->connected_read = TRUE;
2664 socket->priv->connected_write = TRUE;
2666 return TRUE;
2670 * g_socket_get_available_bytes:
2671 * @socket: a #GSocket
2673 * Get the amount of data pending in the OS input buffer, without blocking.
2675 * If @socket is a UDP or SCTP socket, this will return the size of
2676 * just the next packet, even if additional packets are buffered after
2677 * that one.
2679 * Note that on Windows, this function is rather inefficient in the
2680 * UDP case, and so if you know any plausible upper bound on the size
2681 * of the incoming packet, it is better to just do a
2682 * g_socket_receive() with a buffer of that size, rather than calling
2683 * g_socket_get_available_bytes() first and then doing a receive of
2684 * exactly the right size.
2686 * Returns: the number of bytes that can be read from the socket
2687 * without blocking or truncating, or -1 on error.
2689 * Since: 2.32
2691 gssize
2692 g_socket_get_available_bytes (GSocket *socket)
2694 #ifdef G_OS_WIN32
2695 const gint bufsize = 64 * 1024;
2696 static guchar *buf = NULL;
2697 u_long avail;
2698 #else
2699 gint avail;
2700 #endif
2702 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2704 #if defined (SO_NREAD)
2705 if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
2706 return -1;
2707 #elif !defined (G_OS_WIN32)
2708 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2709 avail = -1;
2710 #else
2711 if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
2713 if (G_UNLIKELY (g_once_init_enter (&buf)))
2714 g_once_init_leave (&buf, g_malloc (bufsize));
2716 avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
2717 if (avail == -1 && get_socket_errno () == WSAEWOULDBLOCK)
2718 avail = 0;
2720 else
2722 if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
2723 avail = -1;
2725 #endif
2727 return avail;
2730 /* Block on a timed wait for @condition until (@start_time + @timeout).
2731 * Return %G_IO_ERROR_TIMED_OUT if the timeout is reached; otherwise %TRUE.
2733 static gboolean
2734 block_on_timeout (GSocket *socket,
2735 GIOCondition condition,
2736 gint64 timeout,
2737 gint64 start_time,
2738 GCancellable *cancellable,
2739 GError **error)
2741 gint64 wait_timeout = -1;
2743 g_return_val_if_fail (timeout != 0, TRUE);
2745 /* check if we've timed out or how much time to wait at most */
2746 if (timeout >= 0)
2748 gint64 elapsed = g_get_monotonic_time () - start_time;
2750 if (elapsed >= timeout)
2752 g_set_error_literal (error,
2753 G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2754 _("Socket I/O timed out"));
2755 return FALSE;
2758 wait_timeout = timeout - elapsed;
2761 return g_socket_condition_timed_wait (socket, condition, wait_timeout,
2762 cancellable, error);
2765 static gssize
2766 g_socket_receive_with_timeout (GSocket *socket,
2767 guint8 *buffer,
2768 gsize size,
2769 gint64 timeout,
2770 GCancellable *cancellable,
2771 GError **error)
2773 gssize ret;
2774 gint64 start_time;
2776 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2778 start_time = g_get_monotonic_time ();
2780 if (!check_socket (socket, error))
2781 return -1;
2783 if (!check_timeout (socket, error))
2784 return -1;
2786 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2787 return -1;
2789 while (1)
2791 win32_unset_event_mask (socket, FD_READ);
2793 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2795 int errsv = get_socket_errno ();
2797 if (errsv == EINTR)
2798 continue;
2800 #ifdef WSAEWOULDBLOCK
2801 if (errsv == WSAEWOULDBLOCK)
2802 #else
2803 if (errsv == EWOULDBLOCK ||
2804 errsv == EAGAIN)
2805 #endif
2807 if (timeout != 0)
2809 if (!block_on_timeout (socket, G_IO_IN, timeout, start_time,
2810 cancellable, error))
2811 return -1;
2813 continue;
2817 socket_set_error_lazy (error, errsv, _("Error receiving data: %s"));
2818 return -1;
2821 break;
2824 return ret;
2828 * g_socket_receive:
2829 * @socket: a #GSocket
2830 * @buffer: (array length=size) (element-type guint8): a buffer to
2831 * read data into (which should be at least @size bytes long).
2832 * @size: the number of bytes you want to read from the socket
2833 * @cancellable: (nullable): a %GCancellable or %NULL
2834 * @error: #GError for error reporting, or %NULL to ignore.
2836 * Receive data (up to @size bytes) from a socket. This is mainly used by
2837 * connection-oriented sockets; it is identical to g_socket_receive_from()
2838 * with @address set to %NULL.
2840 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2841 * g_socket_receive() will always read either 0 or 1 complete messages from
2842 * the socket. If the received message is too large to fit in @buffer, then
2843 * the data beyond @size bytes will be discarded, without any explicit
2844 * indication that this has occurred.
2846 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2847 * number of bytes, up to @size. If more than @size bytes have been
2848 * received, the additional data will be returned in future calls to
2849 * g_socket_receive().
2851 * If the socket is in blocking mode the call will block until there
2852 * is some data to receive, the connection is closed, or there is an
2853 * error. If there is no data available and the socket is in
2854 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2855 * returned. To be notified when data is available, wait for the
2856 * %G_IO_IN condition.
2858 * On error -1 is returned and @error is set accordingly.
2860 * Returns: Number of bytes read, or 0 if the connection was closed by
2861 * the peer, or -1 on error
2863 * Since: 2.22
2865 gssize
2866 g_socket_receive (GSocket *socket,
2867 gchar *buffer,
2868 gsize size,
2869 GCancellable *cancellable,
2870 GError **error)
2872 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
2873 socket->priv->blocking ? -1 : 0,
2874 cancellable, error);
2878 * g_socket_receive_with_blocking:
2879 * @socket: a #GSocket
2880 * @buffer: (array length=size) (element-type guint8): a buffer to
2881 * read data into (which should be at least @size bytes long).
2882 * @size: the number of bytes you want to read from the socket
2883 * @blocking: whether to do blocking or non-blocking I/O
2884 * @cancellable: (nullable): a %GCancellable or %NULL
2885 * @error: #GError for error reporting, or %NULL to ignore.
2887 * This behaves exactly the same as g_socket_receive(), except that
2888 * the choice of blocking or non-blocking behavior is determined by
2889 * the @blocking argument rather than by @socket's properties.
2891 * Returns: Number of bytes read, or 0 if the connection was closed by
2892 * the peer, or -1 on error
2894 * Since: 2.26
2896 gssize
2897 g_socket_receive_with_blocking (GSocket *socket,
2898 gchar *buffer,
2899 gsize size,
2900 gboolean blocking,
2901 GCancellable *cancellable,
2902 GError **error)
2904 return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
2905 blocking ? -1 : 0, cancellable, error);
2909 * g_socket_receive_from:
2910 * @socket: a #GSocket
2911 * @address: (out) (optional): a pointer to a #GSocketAddress
2912 * pointer, or %NULL
2913 * @buffer: (array length=size) (element-type guint8): a buffer to
2914 * read data into (which should be at least @size bytes long).
2915 * @size: the number of bytes you want to read from the socket
2916 * @cancellable: (nullable): a %GCancellable or %NULL
2917 * @error: #GError for error reporting, or %NULL to ignore.
2919 * Receive data (up to @size bytes) from a socket.
2921 * If @address is non-%NULL then @address will be set equal to the
2922 * source address of the received packet.
2923 * @address is owned by the caller.
2925 * See g_socket_receive() for additional information.
2927 * Returns: Number of bytes read, or 0 if the connection was closed by
2928 * the peer, or -1 on error
2930 * Since: 2.22
2932 gssize
2933 g_socket_receive_from (GSocket *socket,
2934 GSocketAddress **address,
2935 gchar *buffer,
2936 gsize size,
2937 GCancellable *cancellable,
2938 GError **error)
2940 GInputVector v;
2942 v.buffer = buffer;
2943 v.size = size;
2945 return g_socket_receive_message (socket,
2946 address,
2947 &v, 1,
2948 NULL, 0, NULL,
2949 cancellable,
2950 error);
2953 /* See the comment about SIGPIPE above. */
2954 #ifdef MSG_NOSIGNAL
2955 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2956 #else
2957 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2958 #endif
2960 static gssize
2961 g_socket_send_with_timeout (GSocket *socket,
2962 const guint8 *buffer,
2963 gsize size,
2964 gint64 timeout,
2965 GCancellable *cancellable,
2966 GError **error)
2968 gssize ret;
2969 gint64 start_time;
2971 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2973 start_time = g_get_monotonic_time ();
2975 if (!check_socket (socket, error))
2976 return -1;
2978 if (!check_timeout (socket, error))
2979 return -1;
2981 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2982 return -1;
2984 while (1)
2986 win32_unset_event_mask (socket, FD_WRITE);
2988 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2990 int errsv = get_socket_errno ();
2992 if (errsv == EINTR)
2993 continue;
2995 #ifdef WSAEWOULDBLOCK
2996 if (errsv == WSAEWOULDBLOCK)
2997 #else
2998 if (errsv == EWOULDBLOCK ||
2999 errsv == EAGAIN)
3000 #endif
3002 if (timeout != 0)
3004 if (!block_on_timeout (socket, G_IO_OUT, timeout, start_time,
3005 cancellable, error))
3006 return -1;
3008 continue;
3012 socket_set_error_lazy (error, errsv, _("Error sending data: %s"));
3013 return -1;
3015 break;
3018 return ret;
3022 * g_socket_send:
3023 * @socket: a #GSocket
3024 * @buffer: (array length=size) (element-type guint8): the buffer
3025 * containing the data to send.
3026 * @size: the number of bytes to send
3027 * @cancellable: (nullable): a %GCancellable or %NULL
3028 * @error: #GError for error reporting, or %NULL to ignore.
3030 * Tries to send @size bytes from @buffer on the socket. This is
3031 * mainly used by connection-oriented sockets; it is identical to
3032 * g_socket_send_to() with @address set to %NULL.
3034 * If the socket is in blocking mode the call will block until there is
3035 * space for the data in the socket queue. If there is no space available
3036 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3037 * will be returned. To be notified when space is available, wait for the
3038 * %G_IO_OUT condition. Note though that you may still receive
3039 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3040 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3041 * very common due to the way the underlying APIs work.)
3043 * On error -1 is returned and @error is set accordingly.
3045 * Returns: Number of bytes written (which may be less than @size), or -1
3046 * on error
3048 * Since: 2.22
3050 gssize
3051 g_socket_send (GSocket *socket,
3052 const gchar *buffer,
3053 gsize size,
3054 GCancellable *cancellable,
3055 GError **error)
3057 return g_socket_send_with_blocking (socket, buffer, size,
3058 socket->priv->blocking,
3059 cancellable, error);
3063 * g_socket_send_with_blocking:
3064 * @socket: a #GSocket
3065 * @buffer: (array length=size) (element-type guint8): the buffer
3066 * containing the data to send.
3067 * @size: the number of bytes to send
3068 * @blocking: whether to do blocking or non-blocking I/O
3069 * @cancellable: (nullable): a %GCancellable or %NULL
3070 * @error: #GError for error reporting, or %NULL to ignore.
3072 * This behaves exactly the same as g_socket_send(), except that
3073 * the choice of blocking or non-blocking behavior is determined by
3074 * the @blocking argument rather than by @socket's properties.
3076 * Returns: Number of bytes written (which may be less than @size), or -1
3077 * on error
3079 * Since: 2.26
3081 gssize
3082 g_socket_send_with_blocking (GSocket *socket,
3083 const gchar *buffer,
3084 gsize size,
3085 gboolean blocking,
3086 GCancellable *cancellable,
3087 GError **error)
3089 return g_socket_send_with_timeout (socket, (const guint8 *) buffer, size,
3090 blocking ? -1 : 0, cancellable, error);
3094 * g_socket_send_to:
3095 * @socket: a #GSocket
3096 * @address: (nullable): a #GSocketAddress, or %NULL
3097 * @buffer: (array length=size) (element-type guint8): the buffer
3098 * containing the data to send.
3099 * @size: the number of bytes to send
3100 * @cancellable: (nullable): a %GCancellable or %NULL
3101 * @error: #GError for error reporting, or %NULL to ignore.
3103 * Tries to send @size bytes from @buffer to @address. If @address is
3104 * %NULL then the message is sent to the default receiver (set by
3105 * g_socket_connect()).
3107 * See g_socket_send() for additional information.
3109 * Returns: Number of bytes written (which may be less than @size), or -1
3110 * on error
3112 * Since: 2.22
3114 gssize
3115 g_socket_send_to (GSocket *socket,
3116 GSocketAddress *address,
3117 const gchar *buffer,
3118 gsize size,
3119 GCancellable *cancellable,
3120 GError **error)
3122 GOutputVector v;
3124 v.buffer = buffer;
3125 v.size = size;
3127 return g_socket_send_message (socket,
3128 address,
3129 &v, 1,
3130 NULL, 0,
3132 cancellable,
3133 error);
3137 * g_socket_shutdown:
3138 * @socket: a #GSocket
3139 * @shutdown_read: whether to shut down the read side
3140 * @shutdown_write: whether to shut down the write side
3141 * @error: #GError for error reporting, or %NULL to ignore.
3143 * Shut down part or all of a full-duplex connection.
3145 * If @shutdown_read is %TRUE then the receiving side of the connection
3146 * is shut down, and further reading is disallowed.
3148 * If @shutdown_write is %TRUE then the sending side of the connection
3149 * is shut down, and further writing is disallowed.
3151 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
3153 * One example where it is useful to shut down only one side of a connection is
3154 * graceful disconnect for TCP connections where you close the sending side,
3155 * then wait for the other side to close the connection, thus ensuring that the
3156 * other side saw all sent data.
3158 * Returns: %TRUE on success, %FALSE on error
3160 * Since: 2.22
3162 gboolean
3163 g_socket_shutdown (GSocket *socket,
3164 gboolean shutdown_read,
3165 gboolean shutdown_write,
3166 GError **error)
3168 int how;
3170 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3172 if (!check_socket (socket, error))
3173 return FALSE;
3175 /* Do nothing? */
3176 if (!shutdown_read && !shutdown_write)
3177 return TRUE;
3179 #ifndef G_OS_WIN32
3180 if (shutdown_read && shutdown_write)
3181 how = SHUT_RDWR;
3182 else if (shutdown_read)
3183 how = SHUT_RD;
3184 else
3185 how = SHUT_WR;
3186 #else
3187 if (shutdown_read && shutdown_write)
3188 how = SD_BOTH;
3189 else if (shutdown_read)
3190 how = SD_RECEIVE;
3191 else
3192 how = SD_SEND;
3193 #endif
3195 if (shutdown (socket->priv->fd, how) != 0)
3197 int errsv = get_socket_errno ();
3198 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
3199 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
3200 return FALSE;
3203 if (shutdown_read)
3204 socket->priv->connected_read = FALSE;
3205 if (shutdown_write)
3206 socket->priv->connected_write = FALSE;
3208 return TRUE;
3212 * g_socket_close:
3213 * @socket: a #GSocket
3214 * @error: #GError for error reporting, or %NULL to ignore.
3216 * Closes the socket, shutting down any active connection.
3218 * Closing a socket does not wait for all outstanding I/O operations
3219 * to finish, so the caller should not rely on them to be guaranteed
3220 * to complete even if the close returns with no error.
3222 * Once the socket is closed, all other operations will return
3223 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
3224 * return an error.
3226 * Sockets will be automatically closed when the last reference
3227 * is dropped, but you might want to call this function to make sure
3228 * resources are released as early as possible.
3230 * Beware that due to the way that TCP works, it is possible for
3231 * recently-sent data to be lost if either you close a socket while the
3232 * %G_IO_IN condition is set, or else if the remote connection tries to
3233 * send something to you after you close the socket but before it has
3234 * finished reading all of the data you sent. There is no easy generic
3235 * way to avoid this problem; the easiest fix is to design the network
3236 * protocol such that the client will never send data "out of turn".
3237 * Another solution is for the server to half-close the connection by
3238 * calling g_socket_shutdown() with only the @shutdown_write flag set,
3239 * and then wait for the client to notice this and close its side of the
3240 * connection, after which the server can safely call g_socket_close().
3241 * (This is what #GTcpConnection does if you call
3242 * g_tcp_connection_set_graceful_disconnect(). But of course, this
3243 * only works if the client will close its connection after the server
3244 * does.)
3246 * Returns: %TRUE on success, %FALSE on error
3248 * Since: 2.22
3250 gboolean
3251 g_socket_close (GSocket *socket,
3252 GError **error)
3254 int res;
3256 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3258 if (socket->priv->closed)
3259 return TRUE; /* Multiple close not an error */
3261 if (!check_socket (socket, error))
3262 return FALSE;
3264 while (1)
3266 #ifdef G_OS_WIN32
3267 res = closesocket (socket->priv->fd);
3268 #else
3269 res = close (socket->priv->fd);
3270 #endif
3271 if (res == -1)
3273 int errsv = get_socket_errno ();
3275 if (errsv == EINTR)
3276 continue;
3278 g_set_error (error, G_IO_ERROR,
3279 socket_io_error_from_errno (errsv),
3280 _("Error closing socket: %s"),
3281 socket_strerror (errsv));
3282 return FALSE;
3284 break;
3287 socket->priv->fd = -1;
3288 socket->priv->connected_read = FALSE;
3289 socket->priv->connected_write = FALSE;
3290 socket->priv->closed = TRUE;
3291 if (socket->priv->remote_address)
3293 g_object_unref (socket->priv->remote_address);
3294 socket->priv->remote_address = NULL;
3297 return TRUE;
3301 * g_socket_is_closed:
3302 * @socket: a #GSocket
3304 * Checks whether a socket is closed.
3306 * Returns: %TRUE if socket is closed, %FALSE otherwise
3308 * Since: 2.22
3310 gboolean
3311 g_socket_is_closed (GSocket *socket)
3313 return socket->priv->closed;
3316 #ifdef G_OS_WIN32
3317 /* Broken source, used on errors */
3318 static gboolean
3319 broken_dispatch (GSource *source,
3320 GSourceFunc callback,
3321 gpointer user_data)
3323 return TRUE;
3326 static GSourceFuncs broken_funcs =
3328 NULL,
3329 NULL,
3330 broken_dispatch,
3331 NULL
3334 static gint
3335 network_events_for_condition (GIOCondition condition)
3337 int event_mask = 0;
3339 if (condition & G_IO_IN)
3340 event_mask |= (FD_READ | FD_ACCEPT);
3341 if (condition & G_IO_OUT)
3342 event_mask |= (FD_WRITE | FD_CONNECT);
3343 event_mask |= FD_CLOSE;
3345 return event_mask;
3348 static void
3349 ensure_event (GSocket *socket)
3351 if (socket->priv->event == WSA_INVALID_EVENT)
3352 socket->priv->event = WSACreateEvent();
3355 static void
3356 update_select_events (GSocket *socket)
3358 int event_mask;
3359 GIOCondition *ptr;
3360 GList *l;
3361 WSAEVENT event;
3363 ensure_event (socket);
3365 event_mask = 0;
3366 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3368 ptr = l->data;
3369 event_mask |= network_events_for_condition (*ptr);
3372 if (event_mask != socket->priv->selected_events)
3374 /* If no events selected, disable event so we can unset
3375 nonblocking mode */
3377 if (event_mask == 0)
3378 event = NULL;
3379 else
3380 event = socket->priv->event;
3382 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3383 socket->priv->selected_events = event_mask;
3387 static void
3388 add_condition_watch (GSocket *socket,
3389 GIOCondition *condition)
3391 g_mutex_lock (&socket->priv->win32_source_lock);
3392 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3394 socket->priv->requested_conditions =
3395 g_list_prepend (socket->priv->requested_conditions, condition);
3397 update_select_events (socket);
3398 g_mutex_unlock (&socket->priv->win32_source_lock);
3401 static void
3402 remove_condition_watch (GSocket *socket,
3403 GIOCondition *condition)
3405 g_mutex_lock (&socket->priv->win32_source_lock);
3406 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3408 socket->priv->requested_conditions =
3409 g_list_remove (socket->priv->requested_conditions, condition);
3411 update_select_events (socket);
3412 g_mutex_unlock (&socket->priv->win32_source_lock);
3415 static GIOCondition
3416 update_condition_unlocked (GSocket *socket)
3418 WSANETWORKEVENTS events;
3419 GIOCondition condition;
3421 if (WSAEnumNetworkEvents (socket->priv->fd,
3422 socket->priv->event,
3423 &events) == 0)
3425 socket->priv->current_events |= events.lNetworkEvents;
3426 if (events.lNetworkEvents & FD_WRITE &&
3427 events.iErrorCode[FD_WRITE_BIT] != 0)
3428 socket->priv->current_errors |= FD_WRITE;
3429 if (events.lNetworkEvents & FD_CONNECT &&
3430 events.iErrorCode[FD_CONNECT_BIT] != 0)
3431 socket->priv->current_errors |= FD_CONNECT;
3434 condition = 0;
3435 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3436 condition |= G_IO_IN;
3438 if (socket->priv->current_events & FD_CLOSE)
3440 int r, errsv, buffer;
3442 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3443 if (r < 0)
3444 errsv = get_socket_errno ();
3446 if (r > 0 ||
3447 (r < 0 && errsv == WSAENOTCONN))
3448 condition |= G_IO_IN;
3449 else if (r == 0 ||
3450 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3451 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3452 condition |= G_IO_HUP;
3453 else
3454 condition |= G_IO_ERR;
3457 if (socket->priv->closed)
3458 condition |= G_IO_HUP;
3460 /* Never report both G_IO_OUT and HUP, these are
3461 mutually exclusive (can't write to a closed socket) */
3462 if ((condition & G_IO_HUP) == 0 &&
3463 socket->priv->current_events & FD_WRITE)
3465 if (socket->priv->current_errors & FD_WRITE)
3466 condition |= G_IO_ERR;
3467 else
3468 condition |= G_IO_OUT;
3470 else
3472 if (socket->priv->current_events & FD_CONNECT)
3474 if (socket->priv->current_errors & FD_CONNECT)
3475 condition |= (G_IO_HUP | G_IO_ERR);
3476 else
3477 condition |= G_IO_OUT;
3481 return condition;
3484 static GIOCondition
3485 update_condition (GSocket *socket)
3487 GIOCondition res;
3488 g_mutex_lock (&socket->priv->win32_source_lock);
3489 res = update_condition_unlocked (socket);
3490 g_mutex_unlock (&socket->priv->win32_source_lock);
3491 return res;
3493 #endif
3495 typedef struct {
3496 GSource source;
3497 #ifdef G_OS_WIN32
3498 GPollFD pollfd;
3499 #else
3500 gpointer fd_tag;
3501 #endif
3502 GSocket *socket;
3503 GIOCondition condition;
3504 } GSocketSource;
3506 #ifdef G_OS_WIN32
3507 static gboolean
3508 socket_source_prepare_win32 (GSource *source,
3509 gint *timeout)
3511 GSocketSource *socket_source = (GSocketSource *)source;
3513 *timeout = -1;
3515 return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3518 static gboolean
3519 socket_source_check_win32 (GSource *source)
3521 int timeout;
3523 return socket_source_prepare_win32 (source, &timeout);
3525 #endif
3527 static gboolean
3528 socket_source_dispatch (GSource *source,
3529 GSourceFunc callback,
3530 gpointer user_data)
3532 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3533 GSocketSource *socket_source = (GSocketSource *)source;
3534 GSocket *socket = socket_source->socket;
3535 gint64 timeout;
3536 guint events;
3537 gboolean ret;
3539 #ifdef G_OS_WIN32
3540 events = update_condition (socket_source->socket);
3541 #else
3542 events = g_source_query_unix_fd (source, socket_source->fd_tag);
3543 #endif
3545 timeout = g_source_get_ready_time (source);
3546 if (timeout >= 0 && timeout < g_source_get_time (source))
3548 socket->priv->timed_out = TRUE;
3549 events |= (G_IO_IN | G_IO_OUT);
3552 ret = (*func) (socket, events & socket_source->condition, user_data);
3554 if (socket->priv->timeout)
3555 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3556 else
3557 g_source_set_ready_time (source, -1);
3559 return ret;
3562 static void
3563 socket_source_finalize (GSource *source)
3565 GSocketSource *socket_source = (GSocketSource *)source;
3566 GSocket *socket;
3568 socket = socket_source->socket;
3570 #ifdef G_OS_WIN32
3571 remove_condition_watch (socket, &socket_source->condition);
3572 #endif
3574 g_object_unref (socket);
3577 static gboolean
3578 socket_source_closure_callback (GSocket *socket,
3579 GIOCondition condition,
3580 gpointer data)
3582 GClosure *closure = data;
3584 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3585 GValue result_value = G_VALUE_INIT;
3586 gboolean result;
3588 g_value_init (&result_value, G_TYPE_BOOLEAN);
3590 g_value_init (&params[0], G_TYPE_SOCKET);
3591 g_value_set_object (&params[0], socket);
3592 g_value_init (&params[1], G_TYPE_IO_CONDITION);
3593 g_value_set_flags (&params[1], condition);
3595 g_closure_invoke (closure, &result_value, 2, params, NULL);
3597 result = g_value_get_boolean (&result_value);
3598 g_value_unset (&result_value);
3599 g_value_unset (&params[0]);
3600 g_value_unset (&params[1]);
3602 return result;
3605 static GSourceFuncs socket_source_funcs =
3607 #ifdef G_OS_WIN32
3608 socket_source_prepare_win32,
3609 socket_source_check_win32,
3610 #else
3611 NULL, NULL, /* check, prepare */
3612 #endif
3613 socket_source_dispatch,
3614 socket_source_finalize,
3615 (GSourceFunc)socket_source_closure_callback,
3618 static GSource *
3619 socket_source_new (GSocket *socket,
3620 GIOCondition condition,
3621 GCancellable *cancellable)
3623 GSource *source;
3624 GSocketSource *socket_source;
3626 #ifdef G_OS_WIN32
3627 ensure_event (socket);
3629 if (socket->priv->event == WSA_INVALID_EVENT)
3631 g_warning ("Failed to create WSAEvent");
3632 return g_source_new (&broken_funcs, sizeof (GSource));
3634 #endif
3636 condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
3638 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3639 g_source_set_name (source, "GSocket");
3640 socket_source = (GSocketSource *)source;
3642 socket_source->socket = g_object_ref (socket);
3643 socket_source->condition = condition;
3645 if (cancellable)
3647 GSource *cancellable_source;
3649 cancellable_source = g_cancellable_source_new (cancellable);
3650 g_source_add_child_source (source, cancellable_source);
3651 g_source_set_dummy_callback (cancellable_source);
3652 g_source_unref (cancellable_source);
3655 #ifdef G_OS_WIN32
3656 add_condition_watch (socket, &socket_source->condition);
3657 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3658 socket_source->pollfd.events = condition;
3659 socket_source->pollfd.revents = 0;
3660 g_source_add_poll (source, &socket_source->pollfd);
3661 #else
3662 socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
3663 #endif
3665 if (socket->priv->timeout)
3666 g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
3667 else
3668 g_source_set_ready_time (source, -1);
3670 return source;
3674 * g_socket_create_source: (skip)
3675 * @socket: a #GSocket
3676 * @condition: a #GIOCondition mask to monitor
3677 * @cancellable: (nullable): a %GCancellable or %NULL
3679 * Creates a #GSource that can be attached to a %GMainContext to monitor
3680 * for the availability of the specified @condition on the socket. The #GSource
3681 * keeps a reference to the @socket.
3683 * The callback on the source is of the #GSocketSourceFunc type.
3685 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3686 * these conditions will always be reported output if they are true.
3688 * @cancellable if not %NULL can be used to cancel the source, which will
3689 * cause the source to trigger, reporting the current condition (which
3690 * is likely 0 unless cancellation happened at the same time as a
3691 * condition change). You can check for this in the callback using
3692 * g_cancellable_is_cancelled().
3694 * If @socket has a timeout set, and it is reached before @condition
3695 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3696 * %G_IO_OUT depending on @condition. However, @socket will have been
3697 * marked as having had a timeout, and so the next #GSocket I/O method
3698 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3700 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3702 * Since: 2.22
3704 GSource *
3705 g_socket_create_source (GSocket *socket,
3706 GIOCondition condition,
3707 GCancellable *cancellable)
3709 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3711 return socket_source_new (socket, condition, cancellable);
3715 * g_socket_condition_check:
3716 * @socket: a #GSocket
3717 * @condition: a #GIOCondition mask to check
3719 * Checks on the readiness of @socket to perform operations.
3720 * The operations specified in @condition are checked for and masked
3721 * against the currently-satisfied conditions on @socket. The result
3722 * is returned.
3724 * Note that on Windows, it is possible for an operation to return
3725 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3726 * g_socket_condition_check() has claimed that the socket is ready for
3727 * writing. Rather than calling g_socket_condition_check() and then
3728 * writing to the socket if it succeeds, it is generally better to
3729 * simply try writing to the socket right away, and try again later if
3730 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3732 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3733 * these conditions will always be set in the output if they are true.
3735 * This call never blocks.
3737 * Returns: the @GIOCondition mask of the current state
3739 * Since: 2.22
3741 GIOCondition
3742 g_socket_condition_check (GSocket *socket,
3743 GIOCondition condition)
3745 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3747 if (!check_socket (socket, NULL))
3748 return 0;
3750 #ifdef G_OS_WIN32
3752 GIOCondition current_condition;
3754 condition |= G_IO_ERR | G_IO_HUP;
3756 add_condition_watch (socket, &condition);
3757 current_condition = update_condition (socket);
3758 remove_condition_watch (socket, &condition);
3759 return condition & current_condition;
3761 #else
3763 GPollFD poll_fd;
3764 gint result;
3765 poll_fd.fd = socket->priv->fd;
3766 poll_fd.events = condition;
3767 poll_fd.revents = 0;
3770 result = g_poll (&poll_fd, 1, 0);
3771 while (result == -1 && get_socket_errno () == EINTR);
3773 return poll_fd.revents;
3775 #endif
3779 * g_socket_condition_wait:
3780 * @socket: a #GSocket
3781 * @condition: a #GIOCondition mask to wait for
3782 * @cancellable: (nullable): a #GCancellable, or %NULL
3783 * @error: a #GError pointer, or %NULL
3785 * Waits for @condition to become true on @socket. When the condition
3786 * is met, %TRUE is returned.
3788 * If @cancellable is cancelled before the condition is met, or if the
3789 * socket has a timeout set and it is reached before the condition is
3790 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3791 * the appropriate value (%G_IO_ERROR_CANCELLED or
3792 * %G_IO_ERROR_TIMED_OUT).
3794 * See also g_socket_condition_timed_wait().
3796 * Returns: %TRUE if the condition was met, %FALSE otherwise
3798 * Since: 2.22
3800 gboolean
3801 g_socket_condition_wait (GSocket *socket,
3802 GIOCondition condition,
3803 GCancellable *cancellable,
3804 GError **error)
3806 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3808 return g_socket_condition_timed_wait (socket, condition, -1,
3809 cancellable, error);
3813 * g_socket_condition_timed_wait:
3814 * @socket: a #GSocket
3815 * @condition: a #GIOCondition mask to wait for
3816 * @timeout: the maximum time (in microseconds) to wait, or -1
3817 * @cancellable: (nullable): a #GCancellable, or %NULL
3818 * @error: a #GError pointer, or %NULL
3820 * Waits for up to @timeout microseconds for @condition to become true
3821 * on @socket. If the condition is met, %TRUE is returned.
3823 * If @cancellable is cancelled before the condition is met, or if
3824 * @timeout (or the socket's #GSocket:timeout) is reached before the
3825 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3826 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3827 * %G_IO_ERROR_TIMED_OUT).
3829 * If you don't want a timeout, use g_socket_condition_wait().
3830 * (Alternatively, you can pass -1 for @timeout.)
3832 * Note that although @timeout is in microseconds for consistency with
3833 * other GLib APIs, this function actually only has millisecond
3834 * resolution, and the behavior is undefined if @timeout is not an
3835 * exact number of milliseconds.
3837 * Returns: %TRUE if the condition was met, %FALSE otherwise
3839 * Since: 2.32
3841 gboolean
3842 g_socket_condition_timed_wait (GSocket *socket,
3843 GIOCondition condition,
3844 gint64 timeout,
3845 GCancellable *cancellable,
3846 GError **error)
3848 gint64 start_time;
3850 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3852 if (!check_socket (socket, error))
3853 return FALSE;
3855 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3856 return FALSE;
3858 if (socket->priv->timeout &&
3859 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3860 timeout = socket->priv->timeout * 1000;
3861 else if (timeout != -1)
3862 timeout = timeout / 1000;
3864 start_time = g_get_monotonic_time ();
3866 #ifdef G_OS_WIN32
3868 GIOCondition current_condition;
3869 WSAEVENT events[2];
3870 DWORD res;
3871 GPollFD cancel_fd;
3872 int num_events;
3874 /* Always check these */
3875 condition |= G_IO_ERR | G_IO_HUP;
3877 add_condition_watch (socket, &condition);
3879 num_events = 0;
3880 events[num_events++] = socket->priv->event;
3882 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3883 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3885 if (timeout == -1)
3886 timeout = WSA_INFINITE;
3888 g_mutex_lock (&socket->priv->win32_source_lock);
3889 current_condition = update_condition_unlocked (socket);
3890 while ((condition & current_condition) == 0)
3892 if (!socket->priv->waiting)
3894 socket->priv->waiting = TRUE;
3895 socket->priv->waiting_result = 0;
3896 g_mutex_unlock (&socket->priv->win32_source_lock);
3898 res = WSAWaitForMultipleEvents (num_events, events, FALSE, timeout, FALSE);
3900 g_mutex_lock (&socket->priv->win32_source_lock);
3901 socket->priv->waiting = FALSE;
3902 socket->priv->waiting_result = res;
3903 g_cond_broadcast (&socket->priv->win32_source_cond);
3905 else
3907 if (timeout != WSA_INFINITE)
3909 if (!g_cond_wait_until (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock, timeout))
3911 res = WSA_WAIT_TIMEOUT;
3912 break;
3914 else
3916 res = socket->priv->waiting_result;
3919 else
3921 g_cond_wait (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock);
3922 res = socket->priv->waiting_result;
3926 if (res == WSA_WAIT_FAILED)
3928 int errsv = get_socket_errno ();
3930 g_set_error (error, G_IO_ERROR,
3931 socket_io_error_from_errno (errsv),
3932 _("Waiting for socket condition: %s"),
3933 socket_strerror (errsv));
3934 break;
3936 else if (res == WSA_WAIT_TIMEOUT)
3938 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3939 _("Socket I/O timed out"));
3940 break;
3943 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3944 break;
3946 current_condition = update_condition_unlocked (socket);
3948 if (timeout != WSA_INFINITE)
3950 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3951 if (timeout < 0)
3952 timeout = 0;
3955 g_mutex_unlock (&socket->priv->win32_source_lock);
3956 remove_condition_watch (socket, &condition);
3957 if (num_events > 1)
3958 g_cancellable_release_fd (cancellable);
3960 return (condition & current_condition) != 0;
3962 #else
3964 GPollFD poll_fd[2];
3965 gint result;
3966 gint num;
3968 poll_fd[0].fd = socket->priv->fd;
3969 poll_fd[0].events = condition;
3970 num = 1;
3972 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3973 num++;
3975 while (TRUE)
3977 result = g_poll (poll_fd, num, timeout);
3978 if (result != -1 || errno != EINTR)
3979 break;
3981 if (timeout != -1)
3983 timeout -= (g_get_monotonic_time () - start_time) / 1000;
3984 if (timeout < 0)
3985 timeout = 0;
3989 if (num > 1)
3990 g_cancellable_release_fd (cancellable);
3992 if (result == 0)
3994 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3995 _("Socket I/O timed out"));
3996 return FALSE;
3999 return !g_cancellable_set_error_if_cancelled (cancellable, error);
4001 #endif
4004 #ifndef G_OS_WIN32
4006 /* Unfortunately these have to be macros rather than inline functions due to
4007 * using alloca(). */
4008 #define output_message_to_msghdr(message, prev_message, msg, prev_msg, error) \
4009 G_STMT_START { \
4010 const GOutputMessage *_message = (message); \
4011 const GOutputMessage *_prev_message = (prev_message); \
4012 struct msghdr *_msg = (msg); \
4013 const struct msghdr *_prev_msg = (prev_msg); \
4014 GError **_error = (error); \
4016 _msg->msg_flags = 0; \
4018 /* name */ \
4019 if (_prev_message != NULL && _prev_message->address == _message->address) \
4021 _msg->msg_name = _prev_msg->msg_name; \
4022 _msg->msg_namelen = _prev_msg->msg_namelen; \
4024 else if (_message->address != NULL) \
4026 _msg->msg_namelen = g_socket_address_get_native_size (_message->address); \
4027 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4028 if (!g_socket_address_to_native (_message->address, _msg->msg_name, \
4029 _msg->msg_namelen, _error)) \
4030 break; \
4032 else \
4034 _msg->msg_name = NULL; \
4035 _msg->msg_namelen = 0; \
4038 /* iov */ \
4040 /* this entire expression will be evaluated at compile time */ \
4041 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4042 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4043 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4044 G_STRUCT_OFFSET (GOutputVector, buffer) && \
4045 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4046 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4047 G_STRUCT_OFFSET (GOutputVector, size)) \
4048 /* ABI is compatible */ \
4050 _msg->msg_iov = (struct iovec *) _message->vectors; \
4051 _msg->msg_iovlen = _message->num_vectors; \
4053 else \
4054 /* ABI is incompatible */ \
4056 gint i; \
4058 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4059 for (i = 0; i < _message->num_vectors; i++) \
4061 _msg->msg_iov[i].iov_base = (void *) _message->vectors[i].buffer; \
4062 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4064 _msg->msg_iovlen = _message->num_vectors; \
4068 /* control */ \
4070 struct cmsghdr *cmsg; \
4071 gint i; \
4073 _msg->msg_controllen = 0; \
4074 for (i = 0; i < _message->num_control_messages; i++) \
4075 _msg->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (_message->control_messages[i])); \
4077 if (_msg->msg_controllen == 0) \
4078 _msg->msg_control = NULL; \
4079 else \
4081 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4082 memset (_msg->msg_control, '\0', _msg->msg_controllen); \
4085 cmsg = CMSG_FIRSTHDR (_msg); \
4086 for (i = 0; i < _message->num_control_messages; i++) \
4088 cmsg->cmsg_level = g_socket_control_message_get_level (_message->control_messages[i]); \
4089 cmsg->cmsg_type = g_socket_control_message_get_msg_type (_message->control_messages[i]); \
4090 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (_message->control_messages[i])); \
4091 g_socket_control_message_serialize (_message->control_messages[i], \
4092 CMSG_DATA (cmsg)); \
4093 cmsg = CMSG_NXTHDR (_msg, cmsg); \
4095 g_assert (cmsg == NULL); \
4097 } G_STMT_END
4099 #define input_message_to_msghdr(message, msg) \
4100 G_STMT_START { \
4101 const GInputMessage *_message = (message); \
4102 struct msghdr *_msg = (msg); \
4104 /* name */ \
4105 if (_message->address) \
4107 _msg->msg_namelen = sizeof (struct sockaddr_storage); \
4108 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4110 else \
4112 _msg->msg_name = NULL; \
4113 _msg->msg_namelen = 0; \
4116 /* iov */ \
4117 /* this entire expression will be evaluated at compile time */ \
4118 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4119 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4120 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4121 G_STRUCT_OFFSET (GInputVector, buffer) && \
4122 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4123 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4124 G_STRUCT_OFFSET (GInputVector, size)) \
4125 /* ABI is compatible */ \
4127 _msg->msg_iov = (struct iovec *) _message->vectors; \
4128 _msg->msg_iovlen = _message->num_vectors; \
4130 else \
4131 /* ABI is incompatible */ \
4133 guint i; \
4135 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4136 for (i = 0; i < _message->num_vectors; i++) \
4138 _msg->msg_iov[i].iov_base = _message->vectors[i].buffer; \
4139 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4141 _msg->msg_iovlen = _message->num_vectors; \
4144 /* control */ \
4145 if (_message->control_messages == NULL) \
4147 _msg->msg_controllen = 0; \
4148 _msg->msg_control = NULL; \
4150 else \
4152 _msg->msg_controllen = 2048; \
4153 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4156 /* flags */ \
4157 _msg->msg_flags = _message->flags; \
4158 } G_STMT_END
4160 static void
4161 input_message_from_msghdr (const struct msghdr *msg,
4162 GInputMessage *message,
4163 GSocket *socket)
4165 /* decode address */
4166 if (message->address != NULL)
4168 *message->address = cache_recv_address (socket, msg->msg_name,
4169 msg->msg_namelen);
4172 /* decode control messages */
4174 GPtrArray *my_messages = NULL;
4175 struct cmsghdr *cmsg;
4177 if (msg->msg_controllen >= sizeof (struct cmsghdr))
4179 g_assert (message->control_messages != NULL);
4180 for (cmsg = CMSG_FIRSTHDR (msg);
4181 cmsg != NULL;
4182 cmsg = CMSG_NXTHDR ((struct msghdr *) msg, cmsg))
4184 GSocketControlMessage *control_message;
4186 control_message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4187 cmsg->cmsg_type,
4188 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4189 CMSG_DATA (cmsg));
4190 if (control_message == NULL)
4191 /* We've already spewed about the problem in the
4192 deserialization code, so just continue */
4193 continue;
4195 if (my_messages == NULL)
4196 my_messages = g_ptr_array_new ();
4197 g_ptr_array_add (my_messages, control_message);
4201 if (message->num_control_messages)
4202 *message->num_control_messages = my_messages != NULL ? my_messages->len : 0;
4204 if (message->control_messages)
4206 if (my_messages == NULL)
4208 *message->control_messages = NULL;
4210 else
4212 g_ptr_array_add (my_messages, NULL);
4213 *message->control_messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4216 else
4218 g_assert (my_messages == NULL);
4222 /* capture the flags */
4223 message->flags = msg->msg_flags;
4225 #endif
4228 * g_socket_send_message:
4229 * @socket: a #GSocket
4230 * @address: (nullable): a #GSocketAddress, or %NULL
4231 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4232 * @num_vectors: the number of elements in @vectors, or -1
4233 * @messages: (array length=num_messages) (nullable): a pointer to an
4234 * array of #GSocketControlMessages, or %NULL.
4235 * @num_messages: number of elements in @messages, or -1.
4236 * @flags: an int containing #GSocketMsgFlags flags
4237 * @cancellable: (nullable): a %GCancellable or %NULL
4238 * @error: #GError for error reporting, or %NULL to ignore.
4240 * Send data to @address on @socket. For sending multiple messages see
4241 * g_socket_send_messages(); for easier use, see
4242 * g_socket_send() and g_socket_send_to().
4244 * If @address is %NULL then the message is sent to the default receiver
4245 * (set by g_socket_connect()).
4247 * @vectors must point to an array of #GOutputVector structs and
4248 * @num_vectors must be the length of this array. (If @num_vectors is -1,
4249 * then @vectors is assumed to be terminated by a #GOutputVector with a
4250 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
4251 * that the sent data will be gathered from. Using multiple
4252 * #GOutputVectors is more memory-efficient than manually copying
4253 * data from multiple sources into a single buffer, and more
4254 * network-efficient than making multiple calls to g_socket_send().
4256 * @messages, if non-%NULL, is taken to point to an array of @num_messages
4257 * #GSocketControlMessage instances. These correspond to the control
4258 * messages to be sent on the socket.
4259 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
4260 * array.
4262 * @flags modify how the message is sent. The commonly available arguments
4263 * for this are available in the #GSocketMsgFlags enum, but the
4264 * values there are the same as the system values, and the flags
4265 * are passed in as-is, so you can pass in system-specific flags too.
4267 * If the socket is in blocking mode the call will block until there is
4268 * space for the data in the socket queue. If there is no space available
4269 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4270 * will be returned. To be notified when space is available, wait for the
4271 * %G_IO_OUT condition. Note though that you may still receive
4272 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4273 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4274 * very common due to the way the underlying APIs work.)
4276 * On error -1 is returned and @error is set accordingly.
4278 * Returns: Number of bytes written (which may be less than @size), or -1
4279 * on error
4281 * Since: 2.22
4283 gssize
4284 g_socket_send_message (GSocket *socket,
4285 GSocketAddress *address,
4286 GOutputVector *vectors,
4287 gint num_vectors,
4288 GSocketControlMessage **messages,
4289 gint num_messages,
4290 gint flags,
4291 GCancellable *cancellable,
4292 GError **error)
4294 return g_socket_send_message_with_timeout (socket, address,
4295 vectors, num_vectors,
4296 messages, num_messages, flags,
4297 socket->priv->blocking ? -1 : 0,
4298 cancellable, error);
4301 static gssize
4302 g_socket_send_message_with_timeout (GSocket *socket,
4303 GSocketAddress *address,
4304 GOutputVector *vectors,
4305 gint num_vectors,
4306 GSocketControlMessage **messages,
4307 gint num_messages,
4308 gint flags,
4309 gint64 timeout,
4310 GCancellable *cancellable,
4311 GError **error)
4313 GOutputVector one_vector;
4314 char zero;
4315 gint64 start_time;
4317 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4318 g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), -1);
4319 g_return_val_if_fail (num_vectors == 0 || vectors != NULL, -1);
4320 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
4321 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
4322 g_return_val_if_fail (error == NULL || *error == NULL, -1);
4324 start_time = g_get_monotonic_time ();
4326 if (!check_socket (socket, error))
4327 return -1;
4329 if (!check_timeout (socket, error))
4330 return -1;
4332 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4333 return -1;
4335 if (num_vectors == -1)
4337 for (num_vectors = 0;
4338 vectors[num_vectors].buffer != NULL;
4339 num_vectors++)
4343 if (num_messages == -1)
4345 for (num_messages = 0;
4346 messages != NULL && messages[num_messages] != NULL;
4347 num_messages++)
4351 if (num_vectors == 0)
4353 zero = '\0';
4355 one_vector.buffer = &zero;
4356 one_vector.size = 1;
4357 num_vectors = 1;
4358 vectors = &one_vector;
4361 #ifndef G_OS_WIN32
4363 GOutputMessage output_message;
4364 struct msghdr msg;
4365 gssize result;
4366 GError *child_error = NULL;
4368 output_message.address = address;
4369 output_message.vectors = vectors;
4370 output_message.num_vectors = num_vectors;
4371 output_message.bytes_sent = 0;
4372 output_message.control_messages = messages;
4373 output_message.num_control_messages = num_messages;
4375 output_message_to_msghdr (&output_message, NULL, &msg, NULL, &child_error);
4377 if (child_error != NULL)
4379 g_propagate_error (error, child_error);
4380 return -1;
4383 while (1)
4385 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4386 if (result < 0)
4388 int errsv = get_socket_errno ();
4390 if (errsv == EINTR)
4391 continue;
4393 if (timeout != 0 &&
4394 (errsv == EWOULDBLOCK ||
4395 errsv == EAGAIN))
4397 if (!block_on_timeout (socket, G_IO_OUT, timeout, start_time,
4398 cancellable, error))
4399 return -1;
4401 continue;
4404 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4405 return -1;
4407 break;
4410 return result;
4412 #else
4414 struct sockaddr_storage addr;
4415 guint addrlen;
4416 DWORD bytes_sent;
4417 int result;
4418 WSABUF *bufs;
4419 gint i;
4421 /* Win32 doesn't support control messages.
4422 Actually this is possible for raw and datagram sockets
4423 via WSASendMessage on Vista or later, but that doesn't
4424 seem very useful */
4425 if (num_messages != 0)
4427 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
4428 _("GSocketControlMessage not supported on Windows"));
4429 return -1;
4432 /* iov */
4433 bufs = g_newa (WSABUF, num_vectors);
4434 for (i = 0; i < num_vectors; i++)
4436 bufs[i].buf = (char *)vectors[i].buffer;
4437 bufs[i].len = (gulong)vectors[i].size;
4440 /* name */
4441 addrlen = 0; /* Avoid warning */
4442 if (address)
4444 addrlen = g_socket_address_get_native_size (address);
4445 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
4446 return -1;
4449 while (1)
4451 win32_unset_event_mask (socket, FD_WRITE);
4453 if (address)
4454 result = WSASendTo (socket->priv->fd,
4455 bufs, num_vectors,
4456 &bytes_sent, flags,
4457 (const struct sockaddr *)&addr, addrlen,
4458 NULL, NULL);
4459 else
4460 result = WSASend (socket->priv->fd,
4461 bufs, num_vectors,
4462 &bytes_sent, flags,
4463 NULL, NULL);
4465 if (result != 0)
4467 int errsv = get_socket_errno ();
4469 if (errsv == WSAEINTR)
4470 continue;
4472 if (errsv == WSAEWOULDBLOCK)
4474 if (timeout != 0)
4476 if (!block_on_timeout (socket, G_IO_OUT, timeout,
4477 start_time, cancellable, error))
4478 return -1;
4480 continue;
4484 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4485 return -1;
4487 break;
4490 return bytes_sent;
4492 #endif
4496 * g_socket_send_messages:
4497 * @socket: a #GSocket
4498 * @messages: (array length=num_messages): an array of #GOutputMessage structs
4499 * @num_messages: the number of elements in @messages
4500 * @flags: an int containing #GSocketMsgFlags flags
4501 * @cancellable: (nullable): a %GCancellable or %NULL
4502 * @error: #GError for error reporting, or %NULL to ignore.
4504 * Send multiple data messages from @socket in one go. This is the most
4505 * complicated and fully-featured version of this call. For easier use, see
4506 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
4508 * @messages must point to an array of #GOutputMessage structs and
4509 * @num_messages must be the length of this array. Each #GOutputMessage
4510 * contains an address to send the data to, and a pointer to an array of
4511 * #GOutputVector structs to describe the buffers that the data to be sent
4512 * for each message will be gathered from. Using multiple #GOutputVectors is
4513 * more memory-efficient than manually copying data from multiple sources
4514 * into a single buffer, and more network-efficient than making multiple
4515 * calls to g_socket_send(). Sending multiple messages in one go avoids the
4516 * overhead of making a lot of syscalls in scenarios where a lot of data
4517 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
4518 * or where the same data needs to be sent to multiple recipients.
4520 * @flags modify how the message is sent. The commonly available arguments
4521 * for this are available in the #GSocketMsgFlags enum, but the
4522 * values there are the same as the system values, and the flags
4523 * are passed in as-is, so you can pass in system-specific flags too.
4525 * If the socket is in blocking mode the call will block until there is
4526 * space for all the data in the socket queue. If there is no space available
4527 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4528 * will be returned if no data was written at all, otherwise the number of
4529 * messages sent will be returned. To be notified when space is available,
4530 * wait for the %G_IO_OUT condition. Note though that you may still receive
4531 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4532 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4533 * very common due to the way the underlying APIs work.)
4535 * On error -1 is returned and @error is set accordingly. An error will only
4536 * be returned if zero messages could be sent; otherwise the number of messages
4537 * successfully sent before the error will be returned.
4539 * Returns: number of messages sent, or -1 on error. Note that the number of
4540 * messages sent may be smaller than @num_messages if the socket is
4541 * non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
4542 * in which case the caller may re-try to send the remaining messages.
4544 * Since: 2.44
4546 gint
4547 g_socket_send_messages (GSocket *socket,
4548 GOutputMessage *messages,
4549 guint num_messages,
4550 gint flags,
4551 GCancellable *cancellable,
4552 GError **error)
4554 return g_socket_send_messages_with_timeout (socket, messages, num_messages,
4555 flags,
4556 socket->priv->blocking ? -1 : 0,
4557 cancellable, error);
4560 static gint
4561 g_socket_send_messages_with_timeout (GSocket *socket,
4562 GOutputMessage *messages,
4563 guint num_messages,
4564 gint flags,
4565 gint64 timeout,
4566 GCancellable *cancellable,
4567 GError **error)
4569 gint64 start_time;
4571 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4572 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
4573 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
4574 g_return_val_if_fail (error == NULL || *error == NULL, -1);
4576 start_time = g_get_monotonic_time ();
4578 if (!check_socket (socket, error))
4579 return -1;
4581 if (!check_timeout (socket, error))
4582 return -1;
4584 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4585 return -1;
4587 if (num_messages == 0)
4588 return 0;
4590 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
4592 struct mmsghdr *msgvec;
4593 gint i, num_sent;
4595 #ifdef UIO_MAXIOV
4596 #define MAX_NUM_MESSAGES UIO_MAXIOV
4597 #else
4598 #define MAX_NUM_MESSAGES 1024
4599 #endif
4601 if (num_messages > MAX_NUM_MESSAGES)
4602 num_messages = MAX_NUM_MESSAGES;
4604 msgvec = g_newa (struct mmsghdr, num_messages);
4606 for (i = 0; i < num_messages; ++i)
4608 GOutputMessage *msg = &messages[i];
4609 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
4610 GError *child_error = NULL;
4612 msgvec[i].msg_len = 0;
4614 output_message_to_msghdr (msg, (i > 0) ? &messages[i - 1] : NULL,
4615 msg_hdr, (i > 0) ? &msgvec[i - 1].msg_hdr : NULL,
4616 &child_error);
4618 if (child_error != NULL)
4620 g_propagate_error (error, child_error);
4621 return -1;
4625 for (num_sent = 0; num_sent < num_messages;)
4627 gint ret;
4629 ret = sendmmsg (socket->priv->fd, msgvec + num_sent, num_messages - num_sent,
4630 flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4632 if (ret < 0)
4634 int errsv = get_socket_errno ();
4636 if (errsv == EINTR)
4637 continue;
4639 if (timeout != 0 &&
4640 (errsv == EWOULDBLOCK ||
4641 errsv == EAGAIN))
4643 if (!block_on_timeout (socket, G_IO_OUT, timeout, start_time,
4644 cancellable, error))
4646 if (num_sent > 0)
4648 g_clear_error (error);
4649 break;
4652 return -1;
4655 continue;
4658 /* If any messages were successfully sent, do not error. */
4659 if (num_sent > 0)
4660 break;
4662 socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
4664 return -1;
4667 num_sent += ret;
4670 for (i = 0; i < num_sent; ++i)
4671 messages[i].bytes_sent = msgvec[i].msg_len;
4673 return num_sent;
4675 #else
4677 gssize result;
4678 gint i;
4679 gint64 wait_timeout;
4681 wait_timeout = timeout;
4683 for (i = 0; i < num_messages; ++i)
4685 GOutputMessage *msg = &messages[i];
4686 GError *msg_error = NULL;
4688 result = g_socket_send_message_with_timeout (socket, msg->address,
4689 msg->vectors,
4690 msg->num_vectors,
4691 msg->control_messages,
4692 msg->num_control_messages,
4693 flags, wait_timeout,
4694 cancellable, &msg_error);
4696 /* check if we've timed out or how much time to wait at most */
4697 if (timeout > 0)
4699 gint64 elapsed = g_get_monotonic_time () - start_time;
4700 wait_timeout = MAX (timeout - elapsed, 1);
4703 if (result < 0)
4705 /* if we couldn't send all messages, just return how many we did
4706 * manage to send, provided we managed to send at least one */
4707 if (i > 0)
4709 g_error_free (msg_error);
4710 return i;
4712 else
4714 g_propagate_error (error, msg_error);
4715 return -1;
4719 msg->bytes_sent = result;
4722 return i;
4724 #endif
4727 static GSocketAddress *
4728 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
4730 GSocketAddress *saddr;
4731 gint i;
4732 guint64 oldest_time = G_MAXUINT64;
4733 gint oldest_index = 0;
4735 if (native_len <= 0)
4736 return NULL;
4738 saddr = NULL;
4739 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
4741 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
4742 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
4743 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
4745 if (!tmp)
4746 continue;
4748 if (tmp_native_len != native_len)
4749 continue;
4751 if (memcmp (tmp_native, native, native_len) == 0)
4753 saddr = g_object_ref (tmp);
4754 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
4755 return saddr;
4758 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
4760 oldest_time = socket->priv->recv_addr_cache[i].last_used;
4761 oldest_index = i;
4765 saddr = g_socket_address_new_from_native (native, native_len);
4767 if (socket->priv->recv_addr_cache[oldest_index].addr)
4769 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
4770 g_free (socket->priv->recv_addr_cache[oldest_index].native);
4773 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
4774 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
4775 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
4776 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
4778 return saddr;
4781 static gssize
4782 g_socket_receive_message_with_timeout (GSocket *socket,
4783 GSocketAddress **address,
4784 GInputVector *vectors,
4785 gint num_vectors,
4786 GSocketControlMessage ***messages,
4787 gint *num_messages,
4788 gint *flags,
4789 gint64 timeout,
4790 GCancellable *cancellable,
4791 GError **error)
4793 GInputVector one_vector;
4794 char one_byte;
4795 gint64 start_time;
4797 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4799 start_time = g_get_monotonic_time ();
4801 if (!check_socket (socket, error))
4802 return -1;
4804 if (!check_timeout (socket, error))
4805 return -1;
4807 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4808 return -1;
4810 if (num_vectors == -1)
4812 for (num_vectors = 0;
4813 vectors[num_vectors].buffer != NULL;
4814 num_vectors++)
4818 if (num_vectors == 0)
4820 one_vector.buffer = &one_byte;
4821 one_vector.size = 1;
4822 num_vectors = 1;
4823 vectors = &one_vector;
4826 #ifndef G_OS_WIN32
4828 GInputMessage input_message;
4829 struct msghdr msg;
4830 gssize result;
4832 input_message.address = address;
4833 input_message.vectors = vectors;
4834 input_message.num_vectors = num_vectors;
4835 input_message.bytes_received = 0;
4836 input_message.flags = (flags != NULL) ? *flags : 0;
4837 input_message.control_messages = messages;
4838 input_message.num_control_messages = (guint *) num_messages;
4840 /* We always set the close-on-exec flag so we don't leak file
4841 * descriptors into child processes. Note that gunixfdmessage.c
4842 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4844 #ifdef MSG_CMSG_CLOEXEC
4845 input_message.flags |= MSG_CMSG_CLOEXEC;
4846 #endif
4848 input_message_to_msghdr (&input_message, &msg);
4850 /* do it */
4851 while (1)
4853 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4854 #ifdef MSG_CMSG_CLOEXEC
4855 if (result < 0 && get_socket_errno () == EINVAL)
4857 /* We must be running on an old kernel. Call without the flag. */
4858 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4859 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4861 #endif
4863 if (result < 0)
4865 int errsv = get_socket_errno ();
4867 if (errsv == EINTR)
4868 continue;
4870 if (timeout != 0 &&
4871 (errsv == EWOULDBLOCK ||
4872 errsv == EAGAIN))
4874 if (!block_on_timeout (socket, G_IO_IN, timeout, start_time,
4875 cancellable, error))
4876 return -1;
4878 continue;
4881 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
4882 return -1;
4884 break;
4887 input_message_from_msghdr (&msg, &input_message, socket);
4889 if (flags != NULL)
4890 *flags = input_message.flags;
4892 return result;
4894 #else
4896 struct sockaddr_storage addr;
4897 int addrlen;
4898 DWORD bytes_received;
4899 DWORD win_flags;
4900 int result;
4901 WSABUF *bufs;
4902 gint i;
4904 /* iov */
4905 bufs = g_newa (WSABUF, num_vectors);
4906 for (i = 0; i < num_vectors; i++)
4908 bufs[i].buf = (char *)vectors[i].buffer;
4909 bufs[i].len = (gulong)vectors[i].size;
4912 /* flags */
4913 if (flags != NULL)
4914 win_flags = *flags;
4915 else
4916 win_flags = 0;
4918 /* do it */
4919 while (1)
4921 win32_unset_event_mask (socket, FD_READ);
4923 addrlen = sizeof addr;
4924 if (address)
4925 result = WSARecvFrom (socket->priv->fd,
4926 bufs, num_vectors,
4927 &bytes_received, &win_flags,
4928 (struct sockaddr *)&addr, &addrlen,
4929 NULL, NULL);
4930 else
4931 result = WSARecv (socket->priv->fd,
4932 bufs, num_vectors,
4933 &bytes_received, &win_flags,
4934 NULL, NULL);
4935 if (result != 0)
4937 int errsv = get_socket_errno ();
4939 if (errsv == WSAEINTR)
4940 continue;
4942 if (errsv == WSAEWOULDBLOCK)
4944 if (timeout != 0)
4946 if (!block_on_timeout (socket, G_IO_IN, timeout,
4947 start_time, cancellable, error))
4948 return -1;
4950 continue;
4954 socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
4955 return -1;
4957 break;
4960 /* decode address */
4961 if (address != NULL)
4963 *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
4966 /* capture the flags */
4967 if (flags != NULL)
4968 *flags = win_flags;
4970 if (messages != NULL)
4971 *messages = NULL;
4972 if (num_messages != NULL)
4973 *num_messages = 0;
4975 return bytes_received;
4977 #endif
4981 * g_socket_receive_messages:
4982 * @socket: a #GSocket
4983 * @messages: (array length=num_messages): an array of #GInputMessage structs
4984 * @num_messages: the number of elements in @messages
4985 * @flags: an int containing #GSocketMsgFlags flags for the overall operation
4986 * @cancellable: (nullable): a %GCancellable or %NULL
4987 * @error: #GError for error reporting, or %NULL to ignore
4989 * Receive multiple data messages from @socket in one go. This is the most
4990 * complicated and fully-featured version of this call. For easier use, see
4991 * g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
4993 * @messages must point to an array of #GInputMessage structs and
4994 * @num_messages must be the length of this array. Each #GInputMessage
4995 * contains a pointer to an array of #GInputVector structs describing the
4996 * buffers that the data received in each message will be written to. Using
4997 * multiple #GInputVectors is more memory-efficient than manually copying data
4998 * out of a single buffer to multiple sources, and more system-call-efficient
4999 * than making multiple calls to g_socket_receive(), such as in scenarios where
5000 * a lot of data packets need to be received (e.g. high-bandwidth video
5001 * streaming over RTP/UDP).
5003 * @flags modify how all messages are received. The commonly available
5004 * arguments for this are available in the #GSocketMsgFlags enum, but the
5005 * values there are the same as the system values, and the flags
5006 * are passed in as-is, so you can pass in system-specific flags too. These
5007 * flags affect the overall receive operation. Flags affecting individual
5008 * messages are returned in #GInputMessage.flags.
5010 * The other members of #GInputMessage are treated as described in its
5011 * documentation.
5013 * If #GSocket:blocking is %TRUE the call will block until @num_messages have
5014 * been received, or the end of the stream is reached.
5016 * If #GSocket:blocking is %FALSE the call will return up to @num_messages
5017 * without blocking, or %G_IO_ERROR_WOULD_BLOCK if no messages are queued in the
5018 * operating system to be received.
5020 * In blocking mode, if #GSocket:timeout is positive and is reached before any
5021 * messages are received, %G_IO_ERROR_TIMED_OUT is returned, otherwise up to
5022 * @num_messages are returned. (Note: This is effectively the
5023 * behaviour of `MSG_WAITFORONE` with recvmmsg().)
5025 * To be notified when messages are available, wait for the
5026 * %G_IO_IN condition. Note though that you may still receive
5027 * %G_IO_ERROR_WOULD_BLOCK from g_socket_receive_messages() even if you were
5028 * previously notified of a %G_IO_IN condition.
5030 * If the remote peer closes the connection, any messages queued in the
5031 * operating system will be returned, and subsequent calls to
5032 * g_socket_receive_messages() will return 0 (with no error set).
5034 * On error -1 is returned and @error is set accordingly. An error will only
5035 * be returned if zero messages could be received; otherwise the number of
5036 * messages successfully received before the error will be returned.
5038 * Returns: number of messages received, or -1 on error. Note that the number
5039 * of messages received may be smaller than @num_messages if in non-blocking
5040 * mode, if the peer closed the connection, or if @num_messages
5041 * was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
5042 * to receive the remaining messages.
5044 * Since: 2.48
5046 gint
5047 g_socket_receive_messages (GSocket *socket,
5048 GInputMessage *messages,
5049 guint num_messages,
5050 gint flags,
5051 GCancellable *cancellable,
5052 GError **error)
5054 if (!check_socket (socket, error) ||
5055 !check_timeout (socket, error))
5056 return -1;
5058 return g_socket_receive_messages_with_timeout (socket, messages, num_messages,
5059 flags,
5060 socket->priv->blocking ? -1 : 0,
5061 cancellable, error);
5064 static gint
5065 g_socket_receive_messages_with_timeout (GSocket *socket,
5066 GInputMessage *messages,
5067 guint num_messages,
5068 gint flags,
5069 gint64 timeout,
5070 GCancellable *cancellable,
5071 GError **error)
5073 gint64 start_time;
5075 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5076 g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5077 g_return_val_if_fail (cancellable == NULL ||
5078 G_IS_CANCELLABLE (cancellable), -1);
5079 g_return_val_if_fail (error == NULL || *error == NULL, -1);
5081 start_time = g_get_monotonic_time ();
5083 if (!check_socket (socket, error))
5084 return -1;
5086 if (!check_timeout (socket, error))
5087 return -1;
5089 if (g_cancellable_set_error_if_cancelled (cancellable, error))
5090 return -1;
5092 if (num_messages == 0)
5093 return 0;
5095 #if !defined (G_OS_WIN32) && defined (HAVE_RECVMMSG)
5097 struct mmsghdr *msgvec;
5098 guint i, num_received;
5100 #ifdef UIO_MAXIOV
5101 #define MAX_NUM_MESSAGES UIO_MAXIOV
5102 #else
5103 #define MAX_NUM_MESSAGES 1024
5104 #endif
5106 if (num_messages > MAX_NUM_MESSAGES)
5107 num_messages = MAX_NUM_MESSAGES;
5109 msgvec = g_newa (struct mmsghdr, num_messages);
5111 for (i = 0; i < num_messages; ++i)
5113 GInputMessage *msg = &messages[i];
5114 struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5116 input_message_to_msghdr (msg, msg_hdr);
5117 msgvec[i].msg_len = 0;
5120 /* We always set the close-on-exec flag so we don't leak file
5121 * descriptors into child processes. Note that gunixfdmessage.c
5122 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5124 #ifdef MSG_CMSG_CLOEXEC
5125 flags |= MSG_CMSG_CLOEXEC;
5126 #endif
5128 for (num_received = 0; num_received < num_messages;)
5130 gint ret;
5132 /* We operate in non-blocking mode and handle the timeout ourselves. */
5133 ret = recvmmsg (socket->priv->fd,
5134 msgvec + num_received,
5135 num_messages - num_received,
5136 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5137 #ifdef MSG_CMSG_CLOEXEC
5138 if (ret < 0 && get_socket_errno () == EINVAL)
5140 /* We must be running on an old kernel. Call without the flag. */
5141 flags &= ~(MSG_CMSG_CLOEXEC);
5142 ret = recvmmsg (socket->priv->fd,
5143 msgvec + num_received,
5144 num_messages - num_received,
5145 flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5147 #endif
5149 if (ret < 0)
5151 int errsv = get_socket_errno ();
5153 if (errsv == EINTR)
5154 continue;
5156 if (timeout != 0 &&
5157 (errsv == EWOULDBLOCK ||
5158 errsv == EAGAIN))
5160 if (!block_on_timeout (socket, G_IO_IN, timeout, start_time,
5161 cancellable, error))
5163 if (num_received > 0)
5165 g_clear_error (error);
5166 break;
5169 return -1;
5172 continue;
5175 /* If any messages were successfully received, do not error. */
5176 if (num_received > 0)
5177 break;
5179 socket_set_error_lazy (error, errsv,
5180 _("Error receiving message: %s"));
5182 return -1;
5184 else if (ret == 0)
5186 /* EOS. */
5187 break;
5190 num_received += ret;
5193 for (i = 0; i < num_received; ++i)
5195 input_message_from_msghdr (&msgvec[i].msg_hdr, &messages[i], socket);
5196 messages[i].bytes_received = msgvec[i].msg_len;
5199 return num_received;
5201 #else
5203 guint i;
5204 gint64 wait_timeout;
5206 wait_timeout = timeout;
5208 for (i = 0; i < num_messages; i++)
5210 GInputMessage *msg = &messages[i];
5211 gssize len;
5212 GError *msg_error = NULL;
5214 msg->flags = flags; /* in-out parameter */
5216 len = g_socket_receive_message_with_timeout (socket,
5217 msg->address,
5218 msg->vectors,
5219 msg->num_vectors,
5220 msg->control_messages,
5221 (gint *) msg->num_control_messages,
5222 &msg->flags,
5223 wait_timeout,
5224 cancellable,
5225 &msg_error);
5227 /* check if we've timed out or how much time to wait at most */
5228 if (timeout > 0)
5230 gint64 elapsed = g_get_monotonic_time () - start_time;
5231 wait_timeout = MAX (timeout - elapsed, 1);
5234 if (len >= 0)
5235 msg->bytes_received = len;
5237 if (i != 0 &&
5238 (g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK) ||
5239 g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)))
5241 g_clear_error (&msg_error);
5242 break;
5245 if (msg_error != NULL)
5247 g_propagate_error (error, msg_error);
5248 return -1;
5251 if (len == 0)
5252 break;
5255 return i;
5257 #endif
5261 * g_socket_receive_message:
5262 * @socket: a #GSocket
5263 * @address: (out) (optional): a pointer to a #GSocketAddress
5264 * pointer, or %NULL
5265 * @vectors: (array length=num_vectors): an array of #GInputVector structs
5266 * @num_vectors: the number of elements in @vectors, or -1
5267 * @messages: (array length=num_messages) (out) (optional): a pointer which
5268 * may be filled with an array of #GSocketControlMessages, or %NULL
5269 * @num_messages: (out): a pointer which will be filled with the number of
5270 * elements in @messages, or %NULL
5271 * @flags: (inout): a pointer to an int containing #GSocketMsgFlags flags
5272 * @cancellable: a %GCancellable or %NULL
5273 * @error: a #GError pointer, or %NULL
5275 * Receive data from a socket. For receiving multiple messages, see
5276 * g_socket_receive_messages(); for easier use, see
5277 * g_socket_receive() and g_socket_receive_from().
5279 * If @address is non-%NULL then @address will be set equal to the
5280 * source address of the received packet.
5281 * @address is owned by the caller.
5283 * @vector must point to an array of #GInputVector structs and
5284 * @num_vectors must be the length of this array. These structs
5285 * describe the buffers that received data will be scattered into.
5286 * If @num_vectors is -1, then @vectors is assumed to be terminated
5287 * by a #GInputVector with a %NULL buffer pointer.
5289 * As a special case, if @num_vectors is 0 (in which case, @vectors
5290 * may of course be %NULL), then a single byte is received and
5291 * discarded. This is to facilitate the common practice of sending a
5292 * single '\0' byte for the purposes of transferring ancillary data.
5294 * @messages, if non-%NULL, will be set to point to a newly-allocated
5295 * array of #GSocketControlMessage instances or %NULL if no such
5296 * messages was received. These correspond to the control messages
5297 * received from the kernel, one #GSocketControlMessage per message
5298 * from the kernel. This array is %NULL-terminated and must be freed
5299 * by the caller using g_free() after calling g_object_unref() on each
5300 * element. If @messages is %NULL, any control messages received will
5301 * be discarded.
5303 * @num_messages, if non-%NULL, will be set to the number of control
5304 * messages received.
5306 * If both @messages and @num_messages are non-%NULL, then
5307 * @num_messages gives the number of #GSocketControlMessage instances
5308 * in @messages (ie: not including the %NULL terminator).
5310 * @flags is an in/out parameter. The commonly available arguments
5311 * for this are available in the #GSocketMsgFlags enum, but the
5312 * values there are the same as the system values, and the flags
5313 * are passed in as-is, so you can pass in system-specific flags too
5314 * (and g_socket_receive_message() may pass system-specific flags out).
5315 * Flags passed in to the parameter affect the receive operation; flags returned
5316 * out of it are relevant to the specific returned message.
5318 * As with g_socket_receive(), data may be discarded if @socket is
5319 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
5320 * provide enough buffer space to read a complete message. You can pass
5321 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
5322 * removing it from the receive queue, but there is no portable way to find
5323 * out the length of the message other than by reading it into a
5324 * sufficiently-large buffer.
5326 * If the socket is in blocking mode the call will block until there
5327 * is some data to receive, the connection is closed, or there is an
5328 * error. If there is no data available and the socket is in
5329 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
5330 * returned. To be notified when data is available, wait for the
5331 * %G_IO_IN condition.
5333 * On error -1 is returned and @error is set accordingly.
5335 * Returns: Number of bytes read, or 0 if the connection was closed by
5336 * the peer, or -1 on error
5338 * Since: 2.22
5340 gssize
5341 g_socket_receive_message (GSocket *socket,
5342 GSocketAddress **address,
5343 GInputVector *vectors,
5344 gint num_vectors,
5345 GSocketControlMessage ***messages,
5346 gint *num_messages,
5347 gint *flags,
5348 GCancellable *cancellable,
5349 GError **error)
5351 return g_socket_receive_message_with_timeout (socket, address, vectors,
5352 num_vectors, messages,
5353 num_messages, flags,
5354 socket->priv->blocking ? -1 : 0,
5355 cancellable, error);
5359 * g_socket_get_credentials:
5360 * @socket: a #GSocket.
5361 * @error: #GError for error reporting, or %NULL to ignore.
5363 * Returns the credentials of the foreign process connected to this
5364 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
5365 * sockets).
5367 * If this operation isn't supported on the OS, the method fails with
5368 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
5369 * by reading the %SO_PEERCRED option on the underlying socket.
5371 * Other ways to obtain credentials from a foreign peer includes the
5372 * #GUnixCredentialsMessage type and
5373 * g_unix_connection_send_credentials() /
5374 * g_unix_connection_receive_credentials() functions.
5376 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
5377 * that must be freed with g_object_unref().
5379 * Since: 2.26
5381 GCredentials *
5382 g_socket_get_credentials (GSocket *socket,
5383 GError **error)
5385 GCredentials *ret;
5387 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
5388 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5390 ret = NULL;
5392 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
5394 #ifdef SO_PEERCRED
5396 guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
5397 socklen_t optlen = sizeof (native_creds_buf);
5399 if (getsockopt (socket->priv->fd,
5400 SOL_SOCKET,
5401 SO_PEERCRED,
5402 native_creds_buf,
5403 &optlen) == 0)
5405 ret = g_credentials_new ();
5406 g_credentials_set_native (ret,
5407 G_CREDENTIALS_NATIVE_TYPE,
5408 native_creds_buf);
5411 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
5413 struct unpcbid cred;
5414 socklen_t optlen = sizeof (cred);
5416 if (getsockopt (socket->priv->fd,
5418 LOCAL_PEEREID,
5419 &cred,
5420 &optlen) == 0)
5422 ret = g_credentials_new ();
5423 g_credentials_set_native (ret,
5424 G_CREDENTIALS_NATIVE_TYPE,
5425 &cred);
5428 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
5430 ucred_t *ucred = NULL;
5432 if (getpeerucred (socket->priv->fd, &ucred) == 0)
5434 ret = g_credentials_new ();
5435 g_credentials_set_native (ret,
5436 G_CREDENTIALS_TYPE_SOLARIS_UCRED,
5437 ucred);
5438 ucred_free (ucred);
5441 #else
5442 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
5443 #endif
5445 if (!ret)
5447 int errsv = get_socket_errno ();
5449 g_set_error (error,
5450 G_IO_ERROR,
5451 socket_io_error_from_errno (errsv),
5452 _("Unable to read socket credentials: %s"),
5453 socket_strerror (errsv));
5456 #else
5458 g_set_error_literal (error,
5459 G_IO_ERROR,
5460 G_IO_ERROR_NOT_SUPPORTED,
5461 _("g_socket_get_credentials not implemented for this OS"));
5462 #endif
5464 return ret;
5468 * g_socket_get_option:
5469 * @socket: a #GSocket
5470 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5471 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5472 * @value: (out): return location for the option value
5473 * @error: #GError for error reporting, or %NULL to ignore.
5475 * Gets the value of an integer-valued option on @socket, as with
5476 * getsockopt(). (If you need to fetch a non-integer-valued option,
5477 * you will need to call getsockopt() directly.)
5479 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5480 * header pulls in system headers that will define most of the
5481 * standard/portable socket options. For unusual socket protocols or
5482 * platform-dependent options, you may need to include additional
5483 * headers.
5485 * Note that even for socket options that are a single byte in size,
5486 * @value is still a pointer to a #gint variable, not a #guchar;
5487 * g_socket_get_option() will handle the conversion internally.
5489 * Returns: success or failure. On failure, @error will be set, and
5490 * the system error value (`errno` or WSAGetLastError()) will still
5491 * be set to the result of the getsockopt() call.
5493 * Since: 2.36
5495 gboolean
5496 g_socket_get_option (GSocket *socket,
5497 gint level,
5498 gint optname,
5499 gint *value,
5500 GError **error)
5502 guint size;
5504 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
5506 *value = 0;
5507 size = sizeof (gint);
5508 if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
5510 int errsv = get_socket_errno ();
5512 g_set_error_literal (error,
5513 G_IO_ERROR,
5514 socket_io_error_from_errno (errsv),
5515 socket_strerror (errsv));
5516 #ifndef G_OS_WIN32
5517 /* Reset errno in case the caller wants to look at it */
5518 errno = errsv;
5519 #endif
5520 return FALSE;
5523 #if G_BYTE_ORDER == G_BIG_ENDIAN
5524 /* If the returned value is smaller than an int then we need to
5525 * slide it over into the low-order bytes of *value.
5527 if (size != sizeof (gint))
5528 *value = *value >> (8 * (sizeof (gint) - size));
5529 #endif
5531 return TRUE;
5535 * g_socket_set_option:
5536 * @socket: a #GSocket
5537 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5538 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5539 * @value: the value to set the option to
5540 * @error: #GError for error reporting, or %NULL to ignore.
5542 * Sets the value of an integer-valued option on @socket, as with
5543 * setsockopt(). (If you need to set a non-integer-valued option,
5544 * you will need to call setsockopt() directly.)
5546 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5547 * header pulls in system headers that will define most of the
5548 * standard/portable socket options. For unusual socket protocols or
5549 * platform-dependent options, you may need to include additional
5550 * headers.
5552 * Returns: success or failure. On failure, @error will be set, and
5553 * the system error value (`errno` or WSAGetLastError()) will still
5554 * be set to the result of the setsockopt() call.
5556 * Since: 2.36
5558 gboolean
5559 g_socket_set_option (GSocket *socket,
5560 gint level,
5561 gint optname,
5562 gint value,
5563 GError **error)
5565 gint errsv;
5567 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
5569 if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
5570 return TRUE;
5572 #if !defined (__linux__) && !defined (G_OS_WIN32)
5573 /* Linux and Windows let you set a single-byte value from an int,
5574 * but most other platforms don't.
5576 if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
5578 #if G_BYTE_ORDER == G_BIG_ENDIAN
5579 value = value << (8 * (sizeof (gint) - 1));
5580 #endif
5581 if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
5582 return TRUE;
5584 #endif
5586 errsv = get_socket_errno ();
5588 g_set_error_literal (error,
5589 G_IO_ERROR,
5590 socket_io_error_from_errno (errsv),
5591 socket_strerror (errsv));
5592 #ifndef G_OS_WIN32
5593 errno = errsv;
5594 #endif
5595 return FALSE;