1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2008 Christian Kellner, Samuel Cormier-Iijima
4 * Copyright © 2009 Codethink Limited
5 * Copyright © 2009 Red Hat, Inc
6 * Copyright © 2015 Collabora, Ltd.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General
19 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 * Authors: Christian Kellner <gicmo@gnome.org>
22 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
23 * Ryan Lortie <desrt@desrt.ca>
24 * Alexander Larsson <alexl@redhat.com>
25 * Philip Withnall <philip.withnall@collabora.co.uk>
33 #include "glib-unix.h"
44 # include <sys/ioctl.h>
47 #ifdef HAVE_SYS_FILIO_H
48 # include <sys/filio.h>
55 #define GOBJECT_COMPILATION
56 #include "gobject/gtype-private.h" /* For _PRELUDE type define */
57 #undef GOBJECT_COMPILATION
58 #include "gcancellable.h"
59 #include "gdatagrambased.h"
60 #include "gioenumtypes.h"
61 #include "ginetaddress.h"
62 #include "ginitable.h"
66 #include "gnetworkingprivate.h"
67 #include "gsocketaddress.h"
68 #include "gsocketcontrolmessage.h"
69 #include "gcredentials.h"
70 #include "gcredentialsprivate.h"
74 /* For Windows XP runtime compatibility, but use the system's if_nametoindex() if available */
75 #include "gwin32networking.h"
80 * @short_description: Low-level socket object
82 * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
84 * A #GSocket is a low-level networking primitive. It is a more or less
85 * direct mapping of the BSD socket API in a portable GObject based API.
86 * It supports both the UNIX socket implementations and winsock2 on Windows.
88 * #GSocket is the platform independent base upon which the higher level
89 * network primitives are based. Applications are not typically meant to
90 * use it directly, but rather through classes like #GSocketClient,
91 * #GSocketService and #GSocketConnection. However there may be cases where
92 * direct use of #GSocket is useful.
94 * #GSocket implements the #GInitable interface, so if it is manually constructed
95 * by e.g. g_object_new() you must call g_initable_init() and check the
96 * results before using the object. This is done automatically in
97 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
100 * Sockets operate in two general modes, blocking or non-blocking. When
101 * in blocking mode all operations (which don’t take an explicit blocking
102 * parameter) block until the requested operation
103 * is finished or there is an error. In non-blocking mode all calls that
104 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
105 * To know when a call would successfully run you can call g_socket_condition_check(),
106 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
107 * attach it to a #GMainContext to get callbacks when I/O is possible.
108 * Note that all sockets are always set to non blocking mode in the system, and
109 * blocking mode is emulated in GSocket.
111 * When working in non-blocking mode applications should always be able to
112 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
113 * function said that I/O was possible. This can easily happen in case
114 * of a race condition in the application, but it can also happen for other
115 * reasons. For instance, on Windows a socket is always seen as writable
116 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
118 * #GSockets can be either connection oriented or datagram based.
119 * For connection oriented types you must first establish a connection by
120 * either connecting to an address or accepting a connection from another
121 * address. For connectionless socket types the target/source address is
122 * specified or received in each I/O operation.
124 * All socket file descriptors are set to be close-on-exec.
126 * Note that creating a #GSocket causes the signal %SIGPIPE to be
127 * ignored for the remainder of the program. If you are writing a
128 * command-line utility that uses #GSocket, you may need to take into
129 * account the fact that your program will not automatically be killed
130 * if it tries to write to %stdout after it has been closed.
132 * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
133 * a #GSocket concurrently from multiple threads, you must implement your own
139 static void g_socket_initable_iface_init (GInitableIface
*iface
);
140 static gboolean
g_socket_initable_init (GInitable
*initable
,
141 GCancellable
*cancellable
,
144 static void g_socket_datagram_based_iface_init (GDatagramBasedInterface
*iface
);
145 static gint
g_socket_datagram_based_receive_messages (GDatagramBased
*self
,
146 GInputMessage
*messages
,
150 GCancellable
*cancellable
,
152 static gint
g_socket_datagram_based_send_messages (GDatagramBased
*self
,
153 GOutputMessage
*messages
,
157 GCancellable
*cancellable
,
159 static GSource
*g_socket_datagram_based_create_source (GDatagramBased
*self
,
160 GIOCondition condition
,
161 GCancellable
*cancellable
);
162 static GIOCondition
g_socket_datagram_based_condition_check (GDatagramBased
*datagram_based
,
163 GIOCondition condition
);
164 static gboolean
g_socket_datagram_based_condition_wait (GDatagramBased
*datagram_based
,
165 GIOCondition condition
,
167 GCancellable
*cancellable
,
170 static GSocketAddress
*
171 cache_recv_address (GSocket
*socket
, struct sockaddr
*native
, int native_len
);
174 g_socket_receive_message_with_timeout (GSocket
*socket
,
175 GSocketAddress
**address
,
176 GInputVector
*vectors
,
178 GSocketControlMessage
***messages
,
182 GCancellable
*cancellable
,
185 g_socket_receive_messages_with_timeout (GSocket
*socket
,
186 GInputMessage
*messages
,
190 GCancellable
*cancellable
,
193 g_socket_send_message_with_timeout (GSocket
*socket
,
194 GSocketAddress
*address
,
195 GOutputVector
*vectors
,
197 GSocketControlMessage
**messages
,
201 GCancellable
*cancellable
,
204 g_socket_send_messages_with_timeout (GSocket
*socket
,
205 GOutputMessage
*messages
,
209 GCancellable
*cancellable
,
227 PROP_MULTICAST_LOOPBACK
,
231 /* Size of the receiver cache for g_socket_receive_from() */
232 #define RECV_ADDR_CACHE_SIZE 8
234 struct _GSocketPrivate
236 GSocketFamily family
;
238 GSocketProtocol protocol
;
242 GError
*construct_error
;
243 GSocketAddress
*remote_address
;
248 guint connected_read
: 1;
249 guint connected_write
: 1;
252 guint connect_pending
: 1;
256 DWORD waiting_result
;
260 GList
*requested_conditions
; /* list of requested GIOCondition * */
261 GMutex win32_source_lock
;
262 GCond win32_source_cond
;
266 GSocketAddress
*addr
;
267 struct sockaddr
*native
;
270 } recv_addr_cache
[RECV_ADDR_CACHE_SIZE
];
273 _G_DEFINE_TYPE_EXTENDED_WITH_PRELUDE (GSocket
, g_socket
, G_TYPE_OBJECT
, 0,
274 /* Need a prelude for https://bugzilla.gnome.org/show_bug.cgi?id=674885 */
275 g_type_ensure (G_TYPE_SOCKET_FAMILY
);
276 g_type_ensure (G_TYPE_SOCKET_TYPE
);
277 g_type_ensure (G_TYPE_SOCKET_PROTOCOL
);
278 g_type_ensure (G_TYPE_SOCKET_ADDRESS
);
279 /* And networking init is appropriate for the prelude */
280 g_networking_init ();
281 , /* And now the regular type init code */
282 G_ADD_PRIVATE (GSocket
)
283 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE
,
284 g_socket_initable_iface_init
);
285 G_IMPLEMENT_INTERFACE (G_TYPE_DATAGRAM_BASED
,
286 g_socket_datagram_based_iface_init
));
289 get_socket_errno (void)
294 return WSAGetLastError ();
299 socket_io_error_from_errno (int err
)
302 return g_io_error_from_win32_error (err
);
304 return g_io_error_from_errno (err
);
309 socket_strerror (int err
)
312 return g_strerror (err
);
317 msg
= g_win32_error_message (err
);
319 msg_ret
= g_intern_string (msg
);
326 /* Wrapper around g_set_error() to avoid doing excess work */
327 #define socket_set_error_lazy(err, errsv, fmt) \
329 GError **__err = (err); \
330 int __errsv = (errsv); \
334 int __code = socket_io_error_from_errno (__errsv); \
335 const char *__strerr = socket_strerror (__errsv); \
337 if (__code == G_IO_ERROR_WOULD_BLOCK) \
338 g_set_error_literal (__err, G_IO_ERROR, __code, __strerr); \
340 g_set_error (__err, G_IO_ERROR, __code, fmt, __strerr); \
345 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
347 _win32_unset_event_mask (GSocket
*socket
, int mask
)
349 g_mutex_lock (&socket
->priv
->win32_source_lock
);
350 socket
->priv
->current_events
&= ~mask
;
351 socket
->priv
->current_errors
&= ~mask
;
352 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
355 #define win32_unset_event_mask(_socket, _mask)
358 /* Windows has broken prototypes... */
360 #define getsockopt(sockfd, level, optname, optval, optlen) \
361 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
362 #define setsockopt(sockfd, level, optname, optval, optlen) \
363 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
364 #define getsockname(sockfd, addr, addrlen) \
365 getsockname (sockfd, addr, (int *)addrlen)
366 #define getpeername(sockfd, addr, addrlen) \
367 getpeername (sockfd, addr, (int *)addrlen)
368 #define recv(sockfd, buf, len, flags) \
369 recv (sockfd, (gpointer)buf, len, flags)
373 check_socket (GSocket
*socket
,
376 if (!socket
->priv
->inited
)
378 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_NOT_INITIALIZED
,
379 _("Invalid socket, not initialized"));
383 if (socket
->priv
->construct_error
)
385 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_INITIALIZED
,
386 _("Invalid socket, initialization failed due to: %s"),
387 socket
->priv
->construct_error
->message
);
391 if (socket
->priv
->closed
)
393 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_CLOSED
,
394 _("Socket is already closed"));
402 check_timeout (GSocket
*socket
,
405 if (socket
->priv
->timed_out
)
407 socket
->priv
->timed_out
= FALSE
;
408 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
,
409 _("Socket I/O timed out"));
417 g_socket_details_from_fd (GSocket
*socket
)
419 struct sockaddr_storage address
;
425 fd
= socket
->priv
->fd
;
426 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_TYPE
, &value
, NULL
))
428 errsv
= get_socket_errno ();
435 socket
->priv
->type
= G_SOCKET_TYPE_STREAM
;
439 socket
->priv
->type
= G_SOCKET_TYPE_DATAGRAM
;
443 socket
->priv
->type
= G_SOCKET_TYPE_SEQPACKET
;
447 socket
->priv
->type
= G_SOCKET_TYPE_INVALID
;
451 addrlen
= sizeof address
;
452 if (getsockname (fd
, (struct sockaddr
*) &address
, &addrlen
) != 0)
454 errsv
= get_socket_errno ();
460 g_assert (G_STRUCT_OFFSET (struct sockaddr
, sa_family
) +
461 sizeof address
.ss_family
<= addrlen
);
462 family
= address
.ss_family
;
466 /* On Solaris, this happens if the socket is not yet connected.
467 * But we can use SO_DOMAIN as a workaround there.
470 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_DOMAIN
, &family
, NULL
))
472 errsv
= get_socket_errno ();
476 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
484 case G_SOCKET_FAMILY_IPV4
:
485 case G_SOCKET_FAMILY_IPV6
:
486 socket
->priv
->family
= address
.ss_family
;
487 switch (socket
->priv
->type
)
489 case G_SOCKET_TYPE_STREAM
:
490 socket
->priv
->protocol
= G_SOCKET_PROTOCOL_TCP
;
493 case G_SOCKET_TYPE_DATAGRAM
:
494 socket
->priv
->protocol
= G_SOCKET_PROTOCOL_UDP
;
497 case G_SOCKET_TYPE_SEQPACKET
:
498 socket
->priv
->protocol
= G_SOCKET_PROTOCOL_SCTP
;
506 case G_SOCKET_FAMILY_UNIX
:
507 socket
->priv
->family
= G_SOCKET_FAMILY_UNIX
;
508 socket
->priv
->protocol
= G_SOCKET_PROTOCOL_DEFAULT
;
512 socket
->priv
->family
= G_SOCKET_FAMILY_INVALID
;
516 if (socket
->priv
->family
!= G_SOCKET_FAMILY_INVALID
)
518 addrlen
= sizeof address
;
519 if (getpeername (fd
, (struct sockaddr
*) &address
, &addrlen
) >= 0)
521 socket
->priv
->connected_read
= TRUE
;
522 socket
->priv
->connected_write
= TRUE
;
526 if (g_socket_get_option (socket
, SOL_SOCKET
, SO_KEEPALIVE
, &value
, NULL
))
528 socket
->priv
->keepalive
= !!value
;
532 /* Can't read, maybe not supported, assume FALSE */
533 socket
->priv
->keepalive
= FALSE
;
539 g_set_error (&socket
->priv
->construct_error
, G_IO_ERROR
,
540 socket_io_error_from_errno (errsv
),
541 _("creating GSocket from fd: %s"),
542 socket_strerror (errsv
));
545 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
547 g_socket (gint domain
,
555 fd
= socket (domain
, type
| SOCK_CLOEXEC
, protocol
);
560 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
561 if (fd
< 0 && (errsv
== EINVAL
|| errsv
== EPROTOTYPE
))
563 fd
= socket (domain
, type
, protocol
);
567 int errsv
= get_socket_errno ();
569 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
570 _("Unable to create socket: %s"), socket_strerror (errsv
));
579 /* We always want to set close-on-exec to protect users. If you
580 need to so some weird inheritance to exec you can re-enable this
581 using lower level hacks with g_socket_get_fd(). */
582 flags
= fcntl (fd
, F_GETFD
, 0);
584 (flags
& FD_CLOEXEC
) == 0)
587 fcntl (fd
, F_SETFD
, flags
);
596 g_socket_create_socket (GSocketFamily family
,
605 case G_SOCKET_TYPE_STREAM
:
606 native_type
= SOCK_STREAM
;
609 case G_SOCKET_TYPE_DATAGRAM
:
610 native_type
= SOCK_DGRAM
;
613 case G_SOCKET_TYPE_SEQPACKET
:
614 native_type
= SOCK_SEQPACKET
;
618 g_assert_not_reached ();
623 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_INVALID_ARGUMENT
,
624 _("Unable to create socket: %s"), _("Unknown family was specified"));
630 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_INVALID_ARGUMENT
,
631 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
635 return g_socket (family
, native_type
, protocol
, error
);
639 g_socket_constructed (GObject
*object
)
641 GSocket
*socket
= G_SOCKET (object
);
643 if (socket
->priv
->fd
>= 0)
644 /* create socket->priv info from the fd */
645 g_socket_details_from_fd (socket
);
648 /* create the fd from socket->priv info */
649 socket
->priv
->fd
= g_socket_create_socket (socket
->priv
->family
,
651 socket
->priv
->protocol
,
652 &socket
->priv
->construct_error
);
654 if (socket
->priv
->fd
!= -1)
657 GError
*error
= NULL
;
662 /* Always use native nonblocking sockets, as Windows sets sockets to
663 * nonblocking automatically in certain operations. This way we make
664 * things work the same on all platforms.
667 if (!g_unix_set_fd_nonblocking (socket
->priv
->fd
, TRUE
, &error
))
669 g_warning ("Error setting socket nonblocking: %s", error
->message
);
670 g_clear_error (&error
);
675 if (ioctlsocket (socket
->priv
->fd
, FIONBIO
, &arg
) == SOCKET_ERROR
)
677 int errsv
= get_socket_errno ();
678 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv
));
683 /* See note about SIGPIPE below. */
684 g_socket_set_option (socket
, SOL_SOCKET
, SO_NOSIGPIPE
, TRUE
, NULL
);
690 g_socket_get_property (GObject
*object
,
695 GSocket
*socket
= G_SOCKET (object
);
696 GSocketAddress
*address
;
701 g_value_set_enum (value
, socket
->priv
->family
);
705 g_value_set_enum (value
, socket
->priv
->type
);
709 g_value_set_enum (value
, socket
->priv
->protocol
);
713 g_value_set_int (value
, socket
->priv
->fd
);
717 g_value_set_boolean (value
, socket
->priv
->blocking
);
720 case PROP_LISTEN_BACKLOG
:
721 g_value_set_int (value
, socket
->priv
->listen_backlog
);
725 g_value_set_boolean (value
, socket
->priv
->keepalive
);
728 case PROP_LOCAL_ADDRESS
:
729 address
= g_socket_get_local_address (socket
, NULL
);
730 g_value_take_object (value
, address
);
733 case PROP_REMOTE_ADDRESS
:
734 address
= g_socket_get_remote_address (socket
, NULL
);
735 g_value_take_object (value
, address
);
739 g_value_set_uint (value
, socket
->priv
->timeout
);
743 g_value_set_uint (value
, g_socket_get_ttl (socket
));
747 g_value_set_boolean (value
, g_socket_get_broadcast (socket
));
750 case PROP_MULTICAST_LOOPBACK
:
751 g_value_set_boolean (value
, g_socket_get_multicast_loopback (socket
));
754 case PROP_MULTICAST_TTL
:
755 g_value_set_uint (value
, g_socket_get_multicast_ttl (socket
));
759 G_OBJECT_WARN_INVALID_PROPERTY_ID (object
, prop_id
, pspec
);
764 g_socket_set_property (GObject
*object
,
769 GSocket
*socket
= G_SOCKET (object
);
774 socket
->priv
->family
= g_value_get_enum (value
);
778 socket
->priv
->type
= g_value_get_enum (value
);
782 socket
->priv
->protocol
= g_value_get_enum (value
);
786 socket
->priv
->fd
= g_value_get_int (value
);
790 g_socket_set_blocking (socket
, g_value_get_boolean (value
));
793 case PROP_LISTEN_BACKLOG
:
794 g_socket_set_listen_backlog (socket
, g_value_get_int (value
));
798 g_socket_set_keepalive (socket
, g_value_get_boolean (value
));
802 g_socket_set_timeout (socket
, g_value_get_uint (value
));
806 g_socket_set_ttl (socket
, g_value_get_uint (value
));
810 g_socket_set_broadcast (socket
, g_value_get_boolean (value
));
813 case PROP_MULTICAST_LOOPBACK
:
814 g_socket_set_multicast_loopback (socket
, g_value_get_boolean (value
));
817 case PROP_MULTICAST_TTL
:
818 g_socket_set_multicast_ttl (socket
, g_value_get_uint (value
));
822 G_OBJECT_WARN_INVALID_PROPERTY_ID (object
, prop_id
, pspec
);
827 g_socket_finalize (GObject
*object
)
829 GSocket
*socket
= G_SOCKET (object
);
832 g_clear_error (&socket
->priv
->construct_error
);
834 if (socket
->priv
->fd
!= -1 &&
835 !socket
->priv
->closed
)
836 g_socket_close (socket
, NULL
);
838 if (socket
->priv
->remote_address
)
839 g_object_unref (socket
->priv
->remote_address
);
842 if (socket
->priv
->event
!= WSA_INVALID_EVENT
)
844 WSACloseEvent (socket
->priv
->event
);
845 socket
->priv
->event
= WSA_INVALID_EVENT
;
848 g_assert (socket
->priv
->requested_conditions
== NULL
);
849 g_mutex_clear (&socket
->priv
->win32_source_lock
);
850 g_cond_clear (&socket
->priv
->win32_source_cond
);
853 for (i
= 0; i
< RECV_ADDR_CACHE_SIZE
; i
++)
855 if (socket
->priv
->recv_addr_cache
[i
].addr
)
857 g_object_unref (socket
->priv
->recv_addr_cache
[i
].addr
);
858 g_free (socket
->priv
->recv_addr_cache
[i
].native
);
862 if (G_OBJECT_CLASS (g_socket_parent_class
)->finalize
)
863 (*G_OBJECT_CLASS (g_socket_parent_class
)->finalize
) (object
);
867 g_socket_class_init (GSocketClass
*klass
)
869 GObjectClass
*gobject_class G_GNUC_UNUSED
= G_OBJECT_CLASS (klass
);
872 /* There is no portable, thread-safe way to avoid having the process
873 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
874 * forced to simply ignore the signal process-wide.
876 * Even if we ignore it though, gdb will still stop if the app
877 * receives a SIGPIPE, which can be confusing and annoying. So when
878 * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
879 * prevent the signal from occurring at all.
881 signal (SIGPIPE
, SIG_IGN
);
884 gobject_class
->finalize
= g_socket_finalize
;
885 gobject_class
->constructed
= g_socket_constructed
;
886 gobject_class
->set_property
= g_socket_set_property
;
887 gobject_class
->get_property
= g_socket_get_property
;
889 g_object_class_install_property (gobject_class
, PROP_FAMILY
,
890 g_param_spec_enum ("family",
892 P_("The sockets address family"),
893 G_TYPE_SOCKET_FAMILY
,
894 G_SOCKET_FAMILY_INVALID
,
895 G_PARAM_CONSTRUCT_ONLY
|
897 G_PARAM_STATIC_STRINGS
));
899 g_object_class_install_property (gobject_class
, PROP_TYPE
,
900 g_param_spec_enum ("type",
902 P_("The sockets type"),
904 G_SOCKET_TYPE_STREAM
,
905 G_PARAM_CONSTRUCT_ONLY
|
907 G_PARAM_STATIC_STRINGS
));
909 g_object_class_install_property (gobject_class
, PROP_PROTOCOL
,
910 g_param_spec_enum ("protocol",
911 P_("Socket protocol"),
912 P_("The id of the protocol to use, or -1 for unknown"),
913 G_TYPE_SOCKET_PROTOCOL
,
914 G_SOCKET_PROTOCOL_UNKNOWN
,
915 G_PARAM_CONSTRUCT_ONLY
|
917 G_PARAM_STATIC_STRINGS
));
919 g_object_class_install_property (gobject_class
, PROP_FD
,
920 g_param_spec_int ("fd",
921 P_("File descriptor"),
922 P_("The sockets file descriptor"),
926 G_PARAM_CONSTRUCT_ONLY
|
928 G_PARAM_STATIC_STRINGS
));
930 g_object_class_install_property (gobject_class
, PROP_BLOCKING
,
931 g_param_spec_boolean ("blocking",
933 P_("Whether or not I/O on this socket is blocking"),
936 G_PARAM_STATIC_STRINGS
));
938 g_object_class_install_property (gobject_class
, PROP_LISTEN_BACKLOG
,
939 g_param_spec_int ("listen-backlog",
940 P_("Listen backlog"),
941 P_("Outstanding connections in the listen queue"),
946 G_PARAM_STATIC_STRINGS
));
948 g_object_class_install_property (gobject_class
, PROP_KEEPALIVE
,
949 g_param_spec_boolean ("keepalive",
950 P_("Keep connection alive"),
951 P_("Keep connection alive by sending periodic pings"),
954 G_PARAM_STATIC_STRINGS
));
956 g_object_class_install_property (gobject_class
, PROP_LOCAL_ADDRESS
,
957 g_param_spec_object ("local-address",
959 P_("The local address the socket is bound to"),
960 G_TYPE_SOCKET_ADDRESS
,
962 G_PARAM_STATIC_STRINGS
));
964 g_object_class_install_property (gobject_class
, PROP_REMOTE_ADDRESS
,
965 g_param_spec_object ("remote-address",
966 P_("Remote address"),
967 P_("The remote address the socket is connected to"),
968 G_TYPE_SOCKET_ADDRESS
,
970 G_PARAM_STATIC_STRINGS
));
975 * The timeout in seconds on socket I/O
979 g_object_class_install_property (gobject_class
, PROP_TIMEOUT
,
980 g_param_spec_uint ("timeout",
982 P_("The timeout in seconds on socket I/O"),
987 G_PARAM_STATIC_STRINGS
));
992 * Whether the socket should allow sending to broadcast addresses.
996 g_object_class_install_property (gobject_class
, PROP_BROADCAST
,
997 g_param_spec_boolean ("broadcast",
999 P_("Whether to allow sending to broadcast addresses"),
1002 G_PARAM_STATIC_STRINGS
));
1007 * Time-to-live for outgoing unicast packets
1011 g_object_class_install_property (gobject_class
, PROP_TTL
,
1012 g_param_spec_uint ("ttl",
1014 P_("Time-to-live of outgoing unicast packets"),
1017 G_PARAM_STATIC_STRINGS
));
1020 * GSocket:multicast-loopback:
1022 * Whether outgoing multicast packets loop back to the local host.
1026 g_object_class_install_property (gobject_class
, PROP_MULTICAST_LOOPBACK
,
1027 g_param_spec_boolean ("multicast-loopback",
1028 P_("Multicast loopback"),
1029 P_("Whether outgoing multicast packets loop back to the local host"),
1032 G_PARAM_STATIC_STRINGS
));
1035 * GSocket:multicast-ttl:
1037 * Time-to-live out outgoing multicast packets
1041 g_object_class_install_property (gobject_class
, PROP_MULTICAST_TTL
,
1042 g_param_spec_uint ("multicast-ttl",
1043 P_("Multicast TTL"),
1044 P_("Time-to-live of outgoing multicast packets"),
1047 G_PARAM_STATIC_STRINGS
));
1051 g_socket_initable_iface_init (GInitableIface
*iface
)
1053 iface
->init
= g_socket_initable_init
;
1057 g_socket_datagram_based_iface_init (GDatagramBasedInterface
*iface
)
1059 iface
->receive_messages
= g_socket_datagram_based_receive_messages
;
1060 iface
->send_messages
= g_socket_datagram_based_send_messages
;
1061 iface
->create_source
= g_socket_datagram_based_create_source
;
1062 iface
->condition_check
= g_socket_datagram_based_condition_check
;
1063 iface
->condition_wait
= g_socket_datagram_based_condition_wait
;
1067 g_socket_init (GSocket
*socket
)
1069 socket
->priv
= g_socket_get_instance_private (socket
);
1071 socket
->priv
->fd
= -1;
1072 socket
->priv
->blocking
= TRUE
;
1073 socket
->priv
->listen_backlog
= 10;
1074 socket
->priv
->construct_error
= NULL
;
1076 socket
->priv
->event
= WSA_INVALID_EVENT
;
1077 g_mutex_init (&socket
->priv
->win32_source_lock
);
1078 g_cond_init (&socket
->priv
->win32_source_cond
);
1083 g_socket_initable_init (GInitable
*initable
,
1084 GCancellable
*cancellable
,
1089 g_return_val_if_fail (G_IS_SOCKET (initable
), FALSE
);
1091 socket
= G_SOCKET (initable
);
1093 if (cancellable
!= NULL
)
1095 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
1096 _("Cancellable initialization not supported"));
1100 socket
->priv
->inited
= TRUE
;
1102 if (socket
->priv
->construct_error
)
1105 *error
= g_error_copy (socket
->priv
->construct_error
);
1114 check_datagram_based (GDatagramBased
*self
,
1117 switch (g_socket_get_socket_type (G_SOCKET (self
)))
1119 case G_SOCKET_TYPE_INVALID
:
1120 case G_SOCKET_TYPE_STREAM
:
1121 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
1122 _("Cannot use datagram operations on a non-datagram "
1125 case G_SOCKET_TYPE_DATAGRAM
:
1126 case G_SOCKET_TYPE_SEQPACKET
:
1131 /* Due to us sharing #GSocketSource with the #GSocket implementation, it is
1132 * pretty tricky to split out #GSocket:timeout so that it does not affect
1133 * #GDatagramBased operations (but still affects #GSocket operations). It is
1134 * not worth that effort — just disallow it and require the user to specify
1135 * timeouts on a per-operation basis. */
1136 if (g_socket_get_timeout (G_SOCKET (self
)) != 0)
1138 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
1139 _("Cannot use datagram operations on a socket with a "
1148 g_socket_datagram_based_receive_messages (GDatagramBased
*self
,
1149 GInputMessage
*messages
,
1153 GCancellable
*cancellable
,
1156 if (!check_datagram_based (self
, error
))
1159 return g_socket_receive_messages_with_timeout (G_SOCKET (self
), messages
,
1160 num_messages
, flags
, timeout
,
1161 cancellable
, error
);
1165 g_socket_datagram_based_send_messages (GDatagramBased
*self
,
1166 GOutputMessage
*messages
,
1170 GCancellable
*cancellable
,
1173 if (!check_datagram_based (self
, error
))
1176 return g_socket_send_messages_with_timeout (G_SOCKET (self
), messages
,
1177 num_messages
, flags
, timeout
,
1178 cancellable
, error
);
1182 g_socket_datagram_based_create_source (GDatagramBased
*self
,
1183 GIOCondition condition
,
1184 GCancellable
*cancellable
)
1186 if (!check_datagram_based (self
, NULL
))
1189 return g_socket_create_source (G_SOCKET (self
), condition
, cancellable
);
1193 g_socket_datagram_based_condition_check (GDatagramBased
*datagram_based
,
1194 GIOCondition condition
)
1196 if (!check_datagram_based (datagram_based
, NULL
))
1199 return g_socket_condition_check (G_SOCKET (datagram_based
), condition
);
1203 g_socket_datagram_based_condition_wait (GDatagramBased
*datagram_based
,
1204 GIOCondition condition
,
1206 GCancellable
*cancellable
,
1209 if (!check_datagram_based (datagram_based
, error
))
1212 return g_socket_condition_timed_wait (G_SOCKET (datagram_based
), condition
,
1213 timeout
, cancellable
, error
);
1218 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1219 * @type: the socket type to use.
1220 * @protocol: the id of the protocol to use, or 0 for default.
1221 * @error: #GError for error reporting, or %NULL to ignore.
1223 * Creates a new #GSocket with the defined family, type and protocol.
1224 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1225 * for the family and type is used.
1227 * The @protocol is a family and type specific int that specifies what
1228 * kind of protocol to use. #GSocketProtocol lists several common ones.
1229 * Many families only support one protocol, and use 0 for this, others
1230 * support several and using 0 means to use the default protocol for
1231 * the family and type.
1233 * The protocol id is passed directly to the operating
1234 * system, so you can use protocols not listed in #GSocketProtocol if you
1235 * know the protocol number used for it.
1237 * Returns: a #GSocket or %NULL on error.
1238 * Free the returned object with g_object_unref().
1243 g_socket_new (GSocketFamily family
,
1245 GSocketProtocol protocol
,
1248 return G_SOCKET (g_initable_new (G_TYPE_SOCKET
,
1252 "protocol", protocol
,
1257 * g_socket_new_from_fd:
1258 * @fd: a native socket file descriptor.
1259 * @error: #GError for error reporting, or %NULL to ignore.
1261 * Creates a new #GSocket from a native file descriptor
1262 * or winsock SOCKET handle.
1264 * This reads all the settings from the file descriptor so that
1265 * all properties should work. Note that the file descriptor
1266 * will be set to non-blocking mode, independent on the blocking
1267 * mode of the #GSocket.
1269 * On success, the returned #GSocket takes ownership of @fd. On failure, the
1270 * caller must close @fd themselves.
1272 * Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
1273 * descriptor. Instead, a GError will be set with code %G_IO_ERROR_FAILED
1275 * Returns: a #GSocket or %NULL on error.
1276 * Free the returned object with g_object_unref().
1281 g_socket_new_from_fd (gint fd
,
1284 return G_SOCKET (g_initable_new (G_TYPE_SOCKET
,
1291 * g_socket_set_blocking:
1292 * @socket: a #GSocket.
1293 * @blocking: Whether to use blocking I/O or not.
1295 * Sets the blocking mode of the socket. In blocking mode
1296 * all operations (which don’t take an explicit blocking parameter) block until
1297 * they succeed or there is an error. In
1298 * non-blocking mode all functions return results immediately or
1299 * with a %G_IO_ERROR_WOULD_BLOCK error.
1301 * All sockets are created in blocking mode. However, note that the
1302 * platform level socket is always non-blocking, and blocking mode
1303 * is a GSocket level feature.
1308 g_socket_set_blocking (GSocket
*socket
,
1311 g_return_if_fail (G_IS_SOCKET (socket
));
1313 blocking
= !!blocking
;
1315 if (socket
->priv
->blocking
== blocking
)
1318 socket
->priv
->blocking
= blocking
;
1319 g_object_notify (G_OBJECT (socket
), "blocking");
1323 * g_socket_get_blocking:
1324 * @socket: a #GSocket.
1326 * Gets the blocking mode of the socket. For details on blocking I/O,
1327 * see g_socket_set_blocking().
1329 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1334 g_socket_get_blocking (GSocket
*socket
)
1336 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
1338 return socket
->priv
->blocking
;
1342 * g_socket_set_keepalive:
1343 * @socket: a #GSocket.
1344 * @keepalive: Value for the keepalive flag
1346 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1347 * this flag is set on a socket, the system will attempt to verify that the
1348 * remote socket endpoint is still present if a sufficiently long period of
1349 * time passes with no data being exchanged. If the system is unable to
1350 * verify the presence of the remote endpoint, it will automatically close
1353 * This option is only functional on certain kinds of sockets. (Notably,
1354 * %G_SOCKET_PROTOCOL_TCP sockets.)
1356 * The exact time between pings is system- and protocol-dependent, but will
1357 * normally be at least two hours. Most commonly, you would set this flag
1358 * on a server socket if you want to allow clients to remain idle for long
1359 * periods of time, but also want to ensure that connections are eventually
1360 * garbage-collected if clients crash or become unreachable.
1365 g_socket_set_keepalive (GSocket
*socket
,
1368 GError
*error
= NULL
;
1370 g_return_if_fail (G_IS_SOCKET (socket
));
1372 keepalive
= !!keepalive
;
1373 if (socket
->priv
->keepalive
== keepalive
)
1376 if (!g_socket_set_option (socket
, SOL_SOCKET
, SO_KEEPALIVE
,
1379 g_warning ("error setting keepalive: %s", error
->message
);
1380 g_error_free (error
);
1384 socket
->priv
->keepalive
= keepalive
;
1385 g_object_notify (G_OBJECT (socket
), "keepalive");
1389 * g_socket_get_keepalive:
1390 * @socket: a #GSocket.
1392 * Gets the keepalive mode of the socket. For details on this,
1393 * see g_socket_set_keepalive().
1395 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1400 g_socket_get_keepalive (GSocket
*socket
)
1402 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
1404 return socket
->priv
->keepalive
;
1408 * g_socket_get_listen_backlog:
1409 * @socket: a #GSocket.
1411 * Gets the listen backlog setting of the socket. For details on this,
1412 * see g_socket_set_listen_backlog().
1414 * Returns: the maximum number of pending connections.
1419 g_socket_get_listen_backlog (GSocket
*socket
)
1421 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
1423 return socket
->priv
->listen_backlog
;
1427 * g_socket_set_listen_backlog:
1428 * @socket: a #GSocket.
1429 * @backlog: the maximum number of pending connections.
1431 * Sets the maximum number of outstanding connections allowed
1432 * when listening on this socket. If more clients than this are
1433 * connecting to the socket and the application is not handling them
1434 * on time then the new connections will be refused.
1436 * Note that this must be called before g_socket_listen() and has no
1437 * effect if called after that.
1442 g_socket_set_listen_backlog (GSocket
*socket
,
1445 g_return_if_fail (G_IS_SOCKET (socket
));
1446 g_return_if_fail (!socket
->priv
->listening
);
1448 if (backlog
!= socket
->priv
->listen_backlog
)
1450 socket
->priv
->listen_backlog
= backlog
;
1451 g_object_notify (G_OBJECT (socket
), "listen-backlog");
1456 * g_socket_get_timeout:
1457 * @socket: a #GSocket.
1459 * Gets the timeout setting of the socket. For details on this, see
1460 * g_socket_set_timeout().
1462 * Returns: the timeout in seconds
1467 g_socket_get_timeout (GSocket
*socket
)
1469 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
1471 return socket
->priv
->timeout
;
1475 * g_socket_set_timeout:
1476 * @socket: a #GSocket.
1477 * @timeout: the timeout for @socket, in seconds, or 0 for none
1479 * Sets the time in seconds after which I/O operations on @socket will
1480 * time out if they have not yet completed.
1482 * On a blocking socket, this means that any blocking #GSocket
1483 * operation will time out after @timeout seconds of inactivity,
1484 * returning %G_IO_ERROR_TIMED_OUT.
1486 * On a non-blocking socket, calls to g_socket_condition_wait() will
1487 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1488 * created with g_socket_create_source() will trigger after
1489 * @timeout seconds of inactivity, with the requested condition
1490 * set, at which point calling g_socket_receive(), g_socket_send(),
1491 * g_socket_check_connect_result(), etc, will fail with
1492 * %G_IO_ERROR_TIMED_OUT.
1494 * If @timeout is 0 (the default), operations will never time out
1497 * Note that if an I/O operation is interrupted by a signal, this may
1498 * cause the timeout to be reset.
1503 g_socket_set_timeout (GSocket
*socket
,
1506 g_return_if_fail (G_IS_SOCKET (socket
));
1508 if (timeout
!= socket
->priv
->timeout
)
1510 socket
->priv
->timeout
= timeout
;
1511 g_object_notify (G_OBJECT (socket
), "timeout");
1517 * @socket: a #GSocket.
1519 * Gets the unicast time-to-live setting on @socket; see
1520 * g_socket_set_ttl() for more details.
1522 * Returns: the time-to-live setting on @socket
1527 g_socket_get_ttl (GSocket
*socket
)
1529 GError
*error
= NULL
;
1532 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
1534 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1536 g_socket_get_option (socket
, IPPROTO_IP
, IP_TTL
,
1539 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1541 g_socket_get_option (socket
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
,
1545 g_return_val_if_reached (0);
1549 g_warning ("error getting unicast ttl: %s", error
->message
);
1550 g_error_free (error
);
1559 * @socket: a #GSocket.
1560 * @ttl: the time-to-live value for all unicast packets on @socket
1562 * Sets the time-to-live for outgoing unicast packets on @socket.
1563 * By default the platform-specific default value is used.
1568 g_socket_set_ttl (GSocket
*socket
,
1571 GError
*error
= NULL
;
1573 g_return_if_fail (G_IS_SOCKET (socket
));
1575 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1577 g_socket_set_option (socket
, IPPROTO_IP
, IP_TTL
,
1580 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1582 g_socket_set_option (socket
, IPPROTO_IP
, IP_TTL
,
1584 g_socket_set_option (socket
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
,
1588 g_return_if_reached ();
1592 g_warning ("error setting unicast ttl: %s", error
->message
);
1593 g_error_free (error
);
1597 g_object_notify (G_OBJECT (socket
), "ttl");
1601 * g_socket_get_broadcast:
1602 * @socket: a #GSocket.
1604 * Gets the broadcast setting on @socket; if %TRUE,
1605 * it is possible to send packets to broadcast
1608 * Returns: the broadcast setting on @socket
1613 g_socket_get_broadcast (GSocket
*socket
)
1615 GError
*error
= NULL
;
1618 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
1620 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_BROADCAST
,
1623 g_warning ("error getting broadcast: %s", error
->message
);
1624 g_error_free (error
);
1632 * g_socket_set_broadcast:
1633 * @socket: a #GSocket.
1634 * @broadcast: whether @socket should allow sending to broadcast
1637 * Sets whether @socket should allow sending to broadcast addresses.
1638 * This is %FALSE by default.
1643 g_socket_set_broadcast (GSocket
*socket
,
1646 GError
*error
= NULL
;
1648 g_return_if_fail (G_IS_SOCKET (socket
));
1650 broadcast
= !!broadcast
;
1652 if (!g_socket_set_option (socket
, SOL_SOCKET
, SO_BROADCAST
,
1655 g_warning ("error setting broadcast: %s", error
->message
);
1656 g_error_free (error
);
1660 g_object_notify (G_OBJECT (socket
), "broadcast");
1664 * g_socket_get_multicast_loopback:
1665 * @socket: a #GSocket.
1667 * Gets the multicast loopback setting on @socket; if %TRUE (the
1668 * default), outgoing multicast packets will be looped back to
1669 * multicast listeners on the same host.
1671 * Returns: the multicast loopback setting on @socket
1676 g_socket_get_multicast_loopback (GSocket
*socket
)
1678 GError
*error
= NULL
;
1681 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
1683 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1685 g_socket_get_option (socket
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
1688 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1690 g_socket_get_option (socket
, IPPROTO_IPV6
, IPV6_MULTICAST_LOOP
,
1694 g_return_val_if_reached (FALSE
);
1698 g_warning ("error getting multicast loopback: %s", error
->message
);
1699 g_error_free (error
);
1707 * g_socket_set_multicast_loopback:
1708 * @socket: a #GSocket.
1709 * @loopback: whether @socket should receive messages sent to its
1710 * multicast groups from the local host
1712 * Sets whether outgoing multicast packets will be received by sockets
1713 * listening on that multicast address on the same host. This is %TRUE
1719 g_socket_set_multicast_loopback (GSocket
*socket
,
1722 GError
*error
= NULL
;
1724 g_return_if_fail (G_IS_SOCKET (socket
));
1726 loopback
= !!loopback
;
1728 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1730 g_socket_set_option (socket
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
1733 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1735 g_socket_set_option (socket
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
1737 g_socket_set_option (socket
, IPPROTO_IPV6
, IPV6_MULTICAST_LOOP
,
1741 g_return_if_reached ();
1745 g_warning ("error setting multicast loopback: %s", error
->message
);
1746 g_error_free (error
);
1750 g_object_notify (G_OBJECT (socket
), "multicast-loopback");
1754 * g_socket_get_multicast_ttl:
1755 * @socket: a #GSocket.
1757 * Gets the multicast time-to-live setting on @socket; see
1758 * g_socket_set_multicast_ttl() for more details.
1760 * Returns: the multicast time-to-live setting on @socket
1765 g_socket_get_multicast_ttl (GSocket
*socket
)
1767 GError
*error
= NULL
;
1770 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
1772 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1774 g_socket_get_option (socket
, IPPROTO_IP
, IP_MULTICAST_TTL
,
1777 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1779 g_socket_get_option (socket
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
,
1783 g_return_val_if_reached (FALSE
);
1787 g_warning ("error getting multicast ttl: %s", error
->message
);
1788 g_error_free (error
);
1796 * g_socket_set_multicast_ttl:
1797 * @socket: a #GSocket.
1798 * @ttl: the time-to-live value for all multicast datagrams on @socket
1800 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1801 * By default, this is 1, meaning that multicast packets will not leave
1802 * the local network.
1807 g_socket_set_multicast_ttl (GSocket
*socket
,
1810 GError
*error
= NULL
;
1812 g_return_if_fail (G_IS_SOCKET (socket
));
1814 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1816 g_socket_set_option (socket
, IPPROTO_IP
, IP_MULTICAST_TTL
,
1819 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1821 g_socket_set_option (socket
, IPPROTO_IP
, IP_MULTICAST_TTL
,
1823 g_socket_set_option (socket
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
,
1827 g_return_if_reached ();
1831 g_warning ("error setting multicast ttl: %s", error
->message
);
1832 g_error_free (error
);
1836 g_object_notify (G_OBJECT (socket
), "multicast-ttl");
1840 * g_socket_get_family:
1841 * @socket: a #GSocket.
1843 * Gets the socket family of the socket.
1845 * Returns: a #GSocketFamily
1850 g_socket_get_family (GSocket
*socket
)
1852 g_return_val_if_fail (G_IS_SOCKET (socket
), G_SOCKET_FAMILY_INVALID
);
1854 return socket
->priv
->family
;
1858 * g_socket_get_socket_type:
1859 * @socket: a #GSocket.
1861 * Gets the socket type of the socket.
1863 * Returns: a #GSocketType
1868 g_socket_get_socket_type (GSocket
*socket
)
1870 g_return_val_if_fail (G_IS_SOCKET (socket
), G_SOCKET_TYPE_INVALID
);
1872 return socket
->priv
->type
;
1876 * g_socket_get_protocol:
1877 * @socket: a #GSocket.
1879 * Gets the socket protocol id the socket was created with.
1880 * In case the protocol is unknown, -1 is returned.
1882 * Returns: a protocol id, or -1 if unknown
1887 g_socket_get_protocol (GSocket
*socket
)
1889 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
1891 return socket
->priv
->protocol
;
1896 * @socket: a #GSocket.
1898 * Returns the underlying OS socket object. On unix this
1899 * is a socket file descriptor, and on Windows this is
1900 * a Winsock2 SOCKET handle. This may be useful for
1901 * doing platform specific or otherwise unusual operations
1904 * Returns: the file descriptor of the socket.
1909 g_socket_get_fd (GSocket
*socket
)
1911 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
1913 return socket
->priv
->fd
;
1917 * g_socket_get_local_address:
1918 * @socket: a #GSocket.
1919 * @error: #GError for error reporting, or %NULL to ignore.
1921 * Try to get the local address of a bound socket. This is only
1922 * useful if the socket has been bound to a local address,
1923 * either explicitly or implicitly when connecting.
1925 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1926 * Free the returned object with g_object_unref().
1931 g_socket_get_local_address (GSocket
*socket
,
1934 struct sockaddr_storage buffer
;
1935 guint len
= sizeof (buffer
);
1937 g_return_val_if_fail (G_IS_SOCKET (socket
), NULL
);
1939 if (getsockname (socket
->priv
->fd
, (struct sockaddr
*) &buffer
, &len
) < 0)
1941 int errsv
= get_socket_errno ();
1942 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
1943 _("could not get local address: %s"), socket_strerror (errsv
));
1947 return g_socket_address_new_from_native (&buffer
, len
);
1951 * g_socket_get_remote_address:
1952 * @socket: a #GSocket.
1953 * @error: #GError for error reporting, or %NULL to ignore.
1955 * Try to get the remove address of a connected socket. This is only
1956 * useful for connection oriented sockets that have been connected.
1958 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1959 * Free the returned object with g_object_unref().
1964 g_socket_get_remote_address (GSocket
*socket
,
1967 struct sockaddr_storage buffer
;
1968 guint len
= sizeof (buffer
);
1970 g_return_val_if_fail (G_IS_SOCKET (socket
), NULL
);
1972 if (socket
->priv
->connect_pending
)
1974 if (!g_socket_check_connect_result (socket
, error
))
1977 socket
->priv
->connect_pending
= FALSE
;
1980 if (!socket
->priv
->remote_address
)
1982 if (getpeername (socket
->priv
->fd
, (struct sockaddr
*) &buffer
, &len
) < 0)
1984 int errsv
= get_socket_errno ();
1985 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
1986 _("could not get remote address: %s"), socket_strerror (errsv
));
1990 socket
->priv
->remote_address
= g_socket_address_new_from_native (&buffer
, len
);
1993 return g_object_ref (socket
->priv
->remote_address
);
1997 * g_socket_is_connected:
1998 * @socket: a #GSocket.
2000 * Check whether the socket is connected. This is only useful for
2001 * connection-oriented sockets.
2003 * If using g_socket_shutdown(), this function will return %TRUE until the
2004 * socket has been shut down for reading and writing. If you do a non-blocking
2005 * connect, this function will not return %TRUE until after you call
2006 * g_socket_check_connect_result().
2008 * Returns: %TRUE if socket is connected, %FALSE otherwise.
2013 g_socket_is_connected (GSocket
*socket
)
2015 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2017 return (socket
->priv
->connected_read
|| socket
->priv
->connected_write
);
2022 * @socket: a #GSocket.
2023 * @error: #GError for error reporting, or %NULL to ignore.
2025 * Marks the socket as a server socket, i.e. a socket that is used
2026 * to accept incoming requests using g_socket_accept().
2028 * Before calling this the socket must be bound to a local address using
2031 * To set the maximum amount of outstanding clients, use
2032 * g_socket_set_listen_backlog().
2034 * Returns: %TRUE on success, %FALSE on error.
2039 g_socket_listen (GSocket
*socket
,
2042 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2044 if (!check_socket (socket
, error
))
2047 if (listen (socket
->priv
->fd
, socket
->priv
->listen_backlog
) < 0)
2049 int errsv
= get_socket_errno ();
2051 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
2052 _("could not listen: %s"), socket_strerror (errsv
));
2056 socket
->priv
->listening
= TRUE
;
2063 * @socket: a #GSocket.
2064 * @address: a #GSocketAddress specifying the local address.
2065 * @allow_reuse: whether to allow reusing this address
2066 * @error: #GError for error reporting, or %NULL to ignore.
2068 * When a socket is created it is attached to an address family, but it
2069 * doesn't have an address in this family. g_socket_bind() assigns the
2070 * address (sometimes called name) of the socket.
2072 * It is generally required to bind to a local address before you can
2073 * receive connections. (See g_socket_listen() and g_socket_accept() ).
2074 * In certain situations, you may also want to bind a socket that will be
2075 * used to initiate connections, though this is not normally required.
2077 * If @socket is a TCP socket, then @allow_reuse controls the setting
2078 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
2079 * server sockets (sockets that you will eventually call
2080 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
2081 * set this flag on a server socket may cause g_socket_bind() to return
2082 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
2083 * immediately restarted.)
2085 * If @socket is a UDP socket, then @allow_reuse determines whether or
2086 * not other UDP sockets can be bound to the same address at the same
2087 * time. In particular, you can have several UDP sockets bound to the
2088 * same address, and they will all receive all of the multicast and
2089 * broadcast packets sent to that address. (The behavior of unicast
2090 * UDP packets to an address with multiple listeners is not defined.)
2092 * Returns: %TRUE on success, %FALSE on error.
2097 g_socket_bind (GSocket
*socket
,
2098 GSocketAddress
*address
,
2099 gboolean reuse_address
,
2102 struct sockaddr_storage addr
;
2103 gboolean so_reuseaddr
;
2105 gboolean so_reuseport
;
2108 g_return_val_if_fail (G_IS_SOCKET (socket
) && G_IS_SOCKET_ADDRESS (address
), FALSE
);
2110 if (!check_socket (socket
, error
))
2113 if (!g_socket_address_to_native (address
, &addr
, sizeof addr
, error
))
2116 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
2117 * sockets, but has nasty side effects we don't want for TCP
2120 * On other platforms, we set SO_REUSEPORT, if it exists, for
2121 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
2122 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
2123 * the desired semantics on UDP (as it does on Linux, although
2124 * Linux has SO_REUSEPORT too as of 3.9).
2128 so_reuseaddr
= reuse_address
&& (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
);
2130 so_reuseaddr
= !!reuse_address
;
2134 so_reuseport
= reuse_address
&& (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
);
2137 /* Ignore errors here, the only likely error is "not supported", and
2138 * this is a "best effort" thing mainly.
2140 g_socket_set_option (socket
, SOL_SOCKET
, SO_REUSEADDR
, so_reuseaddr
, NULL
);
2142 g_socket_set_option (socket
, SOL_SOCKET
, SO_REUSEPORT
, so_reuseport
, NULL
);
2145 if (bind (socket
->priv
->fd
, (struct sockaddr
*) &addr
,
2146 g_socket_address_get_native_size (address
)) < 0)
2148 int errsv
= get_socket_errno ();
2150 G_IO_ERROR
, socket_io_error_from_errno (errsv
),
2151 _("Error binding to address: %s"), socket_strerror (errsv
));
2158 #if !defined(HAVE_IF_NAMETOINDEX) && defined(G_OS_WIN32)
2160 if_nametoindex (const gchar
*iface
)
2162 PIP_ADAPTER_ADDRESSES addresses
= NULL
, p
;
2163 gulong addresses_len
= 0;
2167 if (ws2funcs
.pIfNameToIndex
!= NULL
)
2168 return ws2funcs
.pIfNameToIndex (iface
);
2170 res
= GetAdaptersAddresses (AF_UNSPEC
, 0, NULL
, NULL
, &addresses_len
);
2171 if (res
!= NO_ERROR
&& res
!= ERROR_BUFFER_OVERFLOW
)
2173 if (res
== ERROR_NO_DATA
)
2180 addresses
= g_malloc (addresses_len
);
2181 res
= GetAdaptersAddresses (AF_UNSPEC
, 0, NULL
, addresses
, &addresses_len
);
2183 if (res
!= NO_ERROR
)
2186 if (res
== ERROR_NO_DATA
)
2196 if (strcmp (p
->AdapterName
, iface
) == 0)
2212 #define HAVE_IF_NAMETOINDEX 1
2216 g_socket_multicast_group_operation (GSocket
*socket
,
2217 GInetAddress
*group
,
2218 gboolean source_specific
,
2220 gboolean join_group
,
2223 const guint8
*native_addr
;
2224 gint optname
, result
;
2226 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2227 g_return_val_if_fail (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
, FALSE
);
2228 g_return_val_if_fail (G_IS_INET_ADDRESS (group
), FALSE
);
2230 if (!check_socket (socket
, error
))
2233 native_addr
= g_inet_address_to_bytes (group
);
2234 if (g_inet_address_get_family (group
) == G_SOCKET_FAMILY_IPV4
)
2236 #ifdef HAVE_IP_MREQN
2237 struct ip_mreqn mc_req
;
2239 struct ip_mreq mc_req
;
2242 memset (&mc_req
, 0, sizeof (mc_req
));
2243 memcpy (&mc_req
.imr_multiaddr
, native_addr
, sizeof (struct in_addr
));
2245 #ifdef HAVE_IP_MREQN
2247 mc_req
.imr_ifindex
= if_nametoindex (iface
);
2249 mc_req
.imr_ifindex
= 0; /* Pick any. */
2250 #elif defined(G_OS_WIN32)
2252 mc_req
.imr_interface
.s_addr
= g_htonl (if_nametoindex (iface
));
2254 mc_req
.imr_interface
.s_addr
= g_htonl (INADDR_ANY
);
2256 mc_req
.imr_interface
.s_addr
= g_htonl (INADDR_ANY
);
2259 if (source_specific
)
2261 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2262 optname
= join_group
? IP_ADD_SOURCE_MEMBERSHIP
: IP_DROP_SOURCE_MEMBERSHIP
;
2264 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
2266 _("Error joining multicast group: %s") :
2267 _("Error leaving multicast group: %s"),
2268 _("No support for source-specific multicast"));
2273 optname
= join_group
? IP_ADD_MEMBERSHIP
: IP_DROP_MEMBERSHIP
;
2274 result
= setsockopt (socket
->priv
->fd
, IPPROTO_IP
, optname
,
2275 &mc_req
, sizeof (mc_req
));
2277 else if (g_inet_address_get_family (group
) == G_SOCKET_FAMILY_IPV6
)
2279 struct ipv6_mreq mc_req_ipv6
;
2281 memset (&mc_req_ipv6
, 0, sizeof (mc_req_ipv6
));
2282 memcpy (&mc_req_ipv6
.ipv6mr_multiaddr
, native_addr
, sizeof (struct in6_addr
));
2283 #ifdef HAVE_IF_NAMETOINDEX
2285 mc_req_ipv6
.ipv6mr_interface
= if_nametoindex (iface
);
2288 mc_req_ipv6
.ipv6mr_interface
= 0;
2290 optname
= join_group
? IPV6_JOIN_GROUP
: IPV6_LEAVE_GROUP
;
2291 result
= setsockopt (socket
->priv
->fd
, IPPROTO_IPV6
, optname
,
2292 &mc_req_ipv6
, sizeof (mc_req_ipv6
));
2295 g_return_val_if_reached (FALSE
);
2299 int errsv
= get_socket_errno ();
2301 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
2303 _("Error joining multicast group: %s") :
2304 _("Error leaving multicast group: %s"),
2305 socket_strerror (errsv
));
2313 * g_socket_join_multicast_group:
2314 * @socket: a #GSocket.
2315 * @group: a #GInetAddress specifying the group address to join.
2316 * @iface: (nullable): Name of the interface to use, or %NULL
2317 * @source_specific: %TRUE if source-specific multicast should be used
2318 * @error: #GError for error reporting, or %NULL to ignore.
2320 * Registers @socket to receive multicast messages sent to @group.
2321 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2322 * been bound to an appropriate interface and port with
2325 * If @iface is %NULL, the system will automatically pick an interface
2326 * to bind to based on @group.
2328 * If @source_specific is %TRUE, source-specific multicast as defined
2329 * in RFC 4604 is used. Note that on older platforms this may fail
2330 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2332 * Returns: %TRUE on success, %FALSE on error.
2337 g_socket_join_multicast_group (GSocket
*socket
,
2338 GInetAddress
*group
,
2339 gboolean source_specific
,
2343 return g_socket_multicast_group_operation (socket
, group
, source_specific
, iface
, TRUE
, error
);
2347 * g_socket_leave_multicast_group:
2348 * @socket: a #GSocket.
2349 * @group: a #GInetAddress specifying the group address to leave.
2350 * @iface: (nullable): Interface used
2351 * @source_specific: %TRUE if source-specific multicast was used
2352 * @error: #GError for error reporting, or %NULL to ignore.
2354 * Removes @socket from the multicast group defined by @group, @iface,
2355 * and @source_specific (which must all have the same values they had
2356 * when you joined the group).
2358 * @socket remains bound to its address and port, and can still receive
2359 * unicast messages after calling this.
2361 * Returns: %TRUE on success, %FALSE on error.
2366 g_socket_leave_multicast_group (GSocket
*socket
,
2367 GInetAddress
*group
,
2368 gboolean source_specific
,
2372 return g_socket_multicast_group_operation (socket
, group
, source_specific
, iface
, FALSE
, error
);
2376 * g_socket_speaks_ipv4:
2377 * @socket: a #GSocket
2379 * Checks if a socket is capable of speaking IPv4.
2381 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2382 * and under some combinations of circumstances IPv6 sockets are also
2383 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2386 * No other types of sockets are currently considered as being capable
2389 * Returns: %TRUE if this socket can be used with IPv4.
2394 g_socket_speaks_ipv4 (GSocket
*socket
)
2396 switch (socket
->priv
->family
)
2398 case G_SOCKET_FAMILY_IPV4
:
2401 case G_SOCKET_FAMILY_IPV6
:
2402 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2406 if (!g_socket_get_option (socket
,
2407 IPPROTO_IPV6
, IPV6_V6ONLY
,
2424 * @socket: a #GSocket.
2425 * @cancellable: (nullable): a %GCancellable or %NULL
2426 * @error: #GError for error reporting, or %NULL to ignore.
2428 * Accept incoming connections on a connection-based socket. This removes
2429 * the first outstanding connection request from the listening socket and
2430 * creates a #GSocket object for it.
2432 * The @socket must be bound to a local address with g_socket_bind() and
2433 * must be listening for incoming connections (g_socket_listen()).
2435 * If there are no outstanding connections then the operation will block
2436 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2437 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2439 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2440 * Free the returned object with g_object_unref().
2445 g_socket_accept (GSocket
*socket
,
2446 GCancellable
*cancellable
,
2449 GSocket
*new_socket
;
2452 g_return_val_if_fail (G_IS_SOCKET (socket
), NULL
);
2454 if (!check_socket (socket
, error
))
2457 if (!check_timeout (socket
, error
))
2462 win32_unset_event_mask (socket
, FD_ACCEPT
);
2464 if ((ret
= accept (socket
->priv
->fd
, NULL
, 0)) < 0)
2466 int errsv
= get_socket_errno ();
2471 #ifdef WSAEWOULDBLOCK
2472 if (errsv
== WSAEWOULDBLOCK
)
2474 if (errsv
== EWOULDBLOCK
||
2478 if (socket
->priv
->blocking
)
2480 if (!g_socket_condition_wait (socket
,
2481 G_IO_IN
, cancellable
, error
))
2488 socket_set_error_lazy (error
, errsv
, _("Error accepting connection: %s"));
2496 /* The socket inherits the accepting sockets event mask and even object,
2497 we need to remove that */
2498 WSAEventSelect (ret
, NULL
, 0);
2504 /* We always want to set close-on-exec to protect users. If you
2505 need to so some weird inheritance to exec you can re-enable this
2506 using lower level hacks with g_socket_get_fd(). */
2507 flags
= fcntl (ret
, F_GETFD
, 0);
2509 (flags
& FD_CLOEXEC
) == 0)
2511 flags
|= FD_CLOEXEC
;
2512 fcntl (ret
, F_SETFD
, flags
);
2517 new_socket
= g_socket_new_from_fd (ret
, error
);
2518 if (new_socket
== NULL
)
2527 new_socket
->priv
->protocol
= socket
->priv
->protocol
;
2534 * @socket: a #GSocket.
2535 * @address: a #GSocketAddress specifying the remote address.
2536 * @cancellable: (nullable): a %GCancellable or %NULL
2537 * @error: #GError for error reporting, or %NULL to ignore.
2539 * Connect the socket to the specified remote address.
2541 * For connection oriented socket this generally means we attempt to make
2542 * a connection to the @address. For a connection-less socket it sets
2543 * the default address for g_socket_send() and discards all incoming datagrams
2544 * from other sources.
2546 * Generally connection oriented sockets can only connect once, but
2547 * connection-less sockets can connect multiple times to change the
2550 * If the connect call needs to do network I/O it will block, unless
2551 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2552 * and the user can be notified of the connection finishing by waiting
2553 * for the G_IO_OUT condition. The result of the connection must then be
2554 * checked with g_socket_check_connect_result().
2556 * Returns: %TRUE if connected, %FALSE on error.
2561 g_socket_connect (GSocket
*socket
,
2562 GSocketAddress
*address
,
2563 GCancellable
*cancellable
,
2566 struct sockaddr_storage buffer
;
2568 g_return_val_if_fail (G_IS_SOCKET (socket
) && G_IS_SOCKET_ADDRESS (address
), FALSE
);
2570 if (!check_socket (socket
, error
))
2573 if (!g_socket_address_to_native (address
, &buffer
, sizeof buffer
, error
))
2576 if (socket
->priv
->remote_address
)
2577 g_object_unref (socket
->priv
->remote_address
);
2578 socket
->priv
->remote_address
= g_object_ref (address
);
2582 win32_unset_event_mask (socket
, FD_CONNECT
);
2584 if (connect (socket
->priv
->fd
, (struct sockaddr
*) &buffer
,
2585 g_socket_address_get_native_size (address
)) < 0)
2587 int errsv
= get_socket_errno ();
2593 if (errsv
== EINPROGRESS
)
2595 if (errsv
== WSAEWOULDBLOCK
)
2598 if (socket
->priv
->blocking
)
2600 if (g_socket_condition_wait (socket
, G_IO_OUT
, cancellable
, error
))
2602 if (g_socket_check_connect_result (socket
, error
))
2608 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_PENDING
,
2609 _("Connection in progress"));
2610 socket
->priv
->connect_pending
= TRUE
;
2614 g_set_error_literal (error
, G_IO_ERROR
,
2615 socket_io_error_from_errno (errsv
),
2616 socket_strerror (errsv
));
2623 socket
->priv
->connected_read
= TRUE
;
2624 socket
->priv
->connected_write
= TRUE
;
2630 * g_socket_check_connect_result:
2631 * @socket: a #GSocket
2632 * @error: #GError for error reporting, or %NULL to ignore.
2634 * Checks and resets the pending connect error for the socket.
2635 * This is used to check for errors when g_socket_connect() is
2636 * used in non-blocking mode.
2638 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2643 g_socket_check_connect_result (GSocket
*socket
,
2648 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2650 if (!check_socket (socket
, error
))
2653 if (!check_timeout (socket
, error
))
2656 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_ERROR
, &value
, error
))
2658 g_prefix_error (error
, _("Unable to get pending error: "));
2664 g_set_error_literal (error
, G_IO_ERROR
, socket_io_error_from_errno (value
),
2665 socket_strerror (value
));
2666 if (socket
->priv
->remote_address
)
2668 g_object_unref (socket
->priv
->remote_address
);
2669 socket
->priv
->remote_address
= NULL
;
2674 socket
->priv
->connected_read
= TRUE
;
2675 socket
->priv
->connected_write
= TRUE
;
2681 * g_socket_get_available_bytes:
2682 * @socket: a #GSocket
2684 * Get the amount of data pending in the OS input buffer, without blocking.
2686 * If @socket is a UDP or SCTP socket, this will return the size of
2687 * just the next packet, even if additional packets are buffered after
2690 * Note that on Windows, this function is rather inefficient in the
2691 * UDP case, and so if you know any plausible upper bound on the size
2692 * of the incoming packet, it is better to just do a
2693 * g_socket_receive() with a buffer of that size, rather than calling
2694 * g_socket_get_available_bytes() first and then doing a receive of
2695 * exactly the right size.
2697 * Returns: the number of bytes that can be read from the socket
2698 * without blocking or truncating, or -1 on error.
2703 g_socket_get_available_bytes (GSocket
*socket
)
2706 const gint bufsize
= 64 * 1024;
2707 static guchar
*buf
= NULL
;
2713 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
2715 #if defined (SO_NREAD)
2716 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_NREAD
, &avail
, NULL
))
2718 #elif !defined (G_OS_WIN32)
2719 if (ioctl (socket
->priv
->fd
, FIONREAD
, &avail
) < 0)
2722 if (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
)
2724 if (G_UNLIKELY (g_once_init_enter (&buf
)))
2725 g_once_init_leave (&buf
, g_malloc (bufsize
));
2727 avail
= recv (socket
->priv
->fd
, buf
, bufsize
, MSG_PEEK
);
2728 if (avail
== -1 && get_socket_errno () == WSAEWOULDBLOCK
)
2733 if (ioctlsocket (socket
->priv
->fd
, FIONREAD
, &avail
) < 0)
2741 /* Block on a timed wait for @condition until (@start_time + @timeout).
2742 * Return %G_IO_ERROR_TIMED_OUT if the timeout is reached; otherwise %TRUE.
2745 block_on_timeout (GSocket
*socket
,
2746 GIOCondition condition
,
2749 GCancellable
*cancellable
,
2752 gint64 wait_timeout
= -1;
2754 g_return_val_if_fail (timeout
!= 0, TRUE
);
2756 /* check if we've timed out or how much time to wait at most */
2759 gint64 elapsed
= g_get_monotonic_time () - start_time
;
2761 if (elapsed
>= timeout
)
2763 g_set_error_literal (error
,
2764 G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
,
2765 _("Socket I/O timed out"));
2769 wait_timeout
= timeout
- elapsed
;
2772 return g_socket_condition_timed_wait (socket
, condition
, wait_timeout
,
2773 cancellable
, error
);
2777 g_socket_receive_with_timeout (GSocket
*socket
,
2781 GCancellable
*cancellable
,
2787 g_return_val_if_fail (G_IS_SOCKET (socket
) && buffer
!= NULL
, -1);
2789 start_time
= g_get_monotonic_time ();
2791 if (!check_socket (socket
, error
))
2794 if (!check_timeout (socket
, error
))
2797 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
2802 win32_unset_event_mask (socket
, FD_READ
);
2804 if ((ret
= recv (socket
->priv
->fd
, buffer
, size
, 0)) < 0)
2806 int errsv
= get_socket_errno ();
2811 #ifdef WSAEWOULDBLOCK
2812 if (errsv
== WSAEWOULDBLOCK
)
2814 if (errsv
== EWOULDBLOCK
||
2820 if (!block_on_timeout (socket
, G_IO_IN
, timeout
, start_time
,
2821 cancellable
, error
))
2828 socket_set_error_lazy (error
, errsv
, _("Error receiving data: %s"));
2840 * @socket: a #GSocket
2841 * @buffer: (array length=size) (element-type guint8): a buffer to
2842 * read data into (which should be at least @size bytes long).
2843 * @size: the number of bytes you want to read from the socket
2844 * @cancellable: (nullable): a %GCancellable or %NULL
2845 * @error: #GError for error reporting, or %NULL to ignore.
2847 * Receive data (up to @size bytes) from a socket. This is mainly used by
2848 * connection-oriented sockets; it is identical to g_socket_receive_from()
2849 * with @address set to %NULL.
2851 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2852 * g_socket_receive() will always read either 0 or 1 complete messages from
2853 * the socket. If the received message is too large to fit in @buffer, then
2854 * the data beyond @size bytes will be discarded, without any explicit
2855 * indication that this has occurred.
2857 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2858 * number of bytes, up to @size. If more than @size bytes have been
2859 * received, the additional data will be returned in future calls to
2860 * g_socket_receive().
2862 * If the socket is in blocking mode the call will block until there
2863 * is some data to receive, the connection is closed, or there is an
2864 * error. If there is no data available and the socket is in
2865 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2866 * returned. To be notified when data is available, wait for the
2867 * %G_IO_IN condition.
2869 * On error -1 is returned and @error is set accordingly.
2871 * Returns: Number of bytes read, or 0 if the connection was closed by
2872 * the peer, or -1 on error
2877 g_socket_receive (GSocket
*socket
,
2880 GCancellable
*cancellable
,
2883 return g_socket_receive_with_timeout (socket
, (guint8
*) buffer
, size
,
2884 socket
->priv
->blocking
? -1 : 0,
2885 cancellable
, error
);
2889 * g_socket_receive_with_blocking:
2890 * @socket: a #GSocket
2891 * @buffer: (array length=size) (element-type guint8): a buffer to
2892 * read data into (which should be at least @size bytes long).
2893 * @size: the number of bytes you want to read from the socket
2894 * @blocking: whether to do blocking or non-blocking I/O
2895 * @cancellable: (nullable): a %GCancellable or %NULL
2896 * @error: #GError for error reporting, or %NULL to ignore.
2898 * This behaves exactly the same as g_socket_receive(), except that
2899 * the choice of blocking or non-blocking behavior is determined by
2900 * the @blocking argument rather than by @socket's properties.
2902 * Returns: Number of bytes read, or 0 if the connection was closed by
2903 * the peer, or -1 on error
2908 g_socket_receive_with_blocking (GSocket
*socket
,
2912 GCancellable
*cancellable
,
2915 return g_socket_receive_with_timeout (socket
, (guint8
*) buffer
, size
,
2916 blocking
? -1 : 0, cancellable
, error
);
2920 * g_socket_receive_from:
2921 * @socket: a #GSocket
2922 * @address: (out) (optional): a pointer to a #GSocketAddress
2924 * @buffer: (array length=size) (element-type guint8): a buffer to
2925 * read data into (which should be at least @size bytes long).
2926 * @size: the number of bytes you want to read from the socket
2927 * @cancellable: (nullable): a %GCancellable or %NULL
2928 * @error: #GError for error reporting, or %NULL to ignore.
2930 * Receive data (up to @size bytes) from a socket.
2932 * If @address is non-%NULL then @address will be set equal to the
2933 * source address of the received packet.
2934 * @address is owned by the caller.
2936 * See g_socket_receive() for additional information.
2938 * Returns: Number of bytes read, or 0 if the connection was closed by
2939 * the peer, or -1 on error
2944 g_socket_receive_from (GSocket
*socket
,
2945 GSocketAddress
**address
,
2948 GCancellable
*cancellable
,
2956 return g_socket_receive_message (socket
,
2964 /* See the comment about SIGPIPE above. */
2966 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2968 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2972 g_socket_send_with_timeout (GSocket
*socket
,
2973 const guint8
*buffer
,
2976 GCancellable
*cancellable
,
2982 g_return_val_if_fail (G_IS_SOCKET (socket
) && buffer
!= NULL
, -1);
2984 start_time
= g_get_monotonic_time ();
2986 if (!check_socket (socket
, error
))
2989 if (!check_timeout (socket
, error
))
2992 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
2997 win32_unset_event_mask (socket
, FD_WRITE
);
2999 if ((ret
= send (socket
->priv
->fd
, buffer
, size
, G_SOCKET_DEFAULT_SEND_FLAGS
)) < 0)
3001 int errsv
= get_socket_errno ();
3006 #ifdef WSAEWOULDBLOCK
3007 if (errsv
== WSAEWOULDBLOCK
)
3009 if (errsv
== EWOULDBLOCK
||
3015 if (!block_on_timeout (socket
, G_IO_OUT
, timeout
, start_time
,
3016 cancellable
, error
))
3023 socket_set_error_lazy (error
, errsv
, _("Error sending data: %s"));
3034 * @socket: a #GSocket
3035 * @buffer: (array length=size) (element-type guint8): the buffer
3036 * containing the data to send.
3037 * @size: the number of bytes to send
3038 * @cancellable: (nullable): a %GCancellable or %NULL
3039 * @error: #GError for error reporting, or %NULL to ignore.
3041 * Tries to send @size bytes from @buffer on the socket. This is
3042 * mainly used by connection-oriented sockets; it is identical to
3043 * g_socket_send_to() with @address set to %NULL.
3045 * If the socket is in blocking mode the call will block until there is
3046 * space for the data in the socket queue. If there is no space available
3047 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3048 * will be returned. To be notified when space is available, wait for the
3049 * %G_IO_OUT condition. Note though that you may still receive
3050 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3051 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3052 * very common due to the way the underlying APIs work.)
3054 * On error -1 is returned and @error is set accordingly.
3056 * Returns: Number of bytes written (which may be less than @size), or -1
3062 g_socket_send (GSocket
*socket
,
3063 const gchar
*buffer
,
3065 GCancellable
*cancellable
,
3068 return g_socket_send_with_blocking (socket
, buffer
, size
,
3069 socket
->priv
->blocking
,
3070 cancellable
, error
);
3074 * g_socket_send_with_blocking:
3075 * @socket: a #GSocket
3076 * @buffer: (array length=size) (element-type guint8): the buffer
3077 * containing the data to send.
3078 * @size: the number of bytes to send
3079 * @blocking: whether to do blocking or non-blocking I/O
3080 * @cancellable: (nullable): a %GCancellable or %NULL
3081 * @error: #GError for error reporting, or %NULL to ignore.
3083 * This behaves exactly the same as g_socket_send(), except that
3084 * the choice of blocking or non-blocking behavior is determined by
3085 * the @blocking argument rather than by @socket's properties.
3087 * Returns: Number of bytes written (which may be less than @size), or -1
3093 g_socket_send_with_blocking (GSocket
*socket
,
3094 const gchar
*buffer
,
3097 GCancellable
*cancellable
,
3100 return g_socket_send_with_timeout (socket
, (const guint8
*) buffer
, size
,
3101 blocking
? -1 : 0, cancellable
, error
);
3106 * @socket: a #GSocket
3107 * @address: (nullable): a #GSocketAddress, or %NULL
3108 * @buffer: (array length=size) (element-type guint8): the buffer
3109 * containing the data to send.
3110 * @size: the number of bytes to send
3111 * @cancellable: (nullable): a %GCancellable or %NULL
3112 * @error: #GError for error reporting, or %NULL to ignore.
3114 * Tries to send @size bytes from @buffer to @address. If @address is
3115 * %NULL then the message is sent to the default receiver (set by
3116 * g_socket_connect()).
3118 * See g_socket_send() for additional information.
3120 * Returns: Number of bytes written (which may be less than @size), or -1
3126 g_socket_send_to (GSocket
*socket
,
3127 GSocketAddress
*address
,
3128 const gchar
*buffer
,
3130 GCancellable
*cancellable
,
3138 return g_socket_send_message (socket
,
3148 * g_socket_shutdown:
3149 * @socket: a #GSocket
3150 * @shutdown_read: whether to shut down the read side
3151 * @shutdown_write: whether to shut down the write side
3152 * @error: #GError for error reporting, or %NULL to ignore.
3154 * Shut down part or all of a full-duplex connection.
3156 * If @shutdown_read is %TRUE then the receiving side of the connection
3157 * is shut down, and further reading is disallowed.
3159 * If @shutdown_write is %TRUE then the sending side of the connection
3160 * is shut down, and further writing is disallowed.
3162 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
3164 * One example where it is useful to shut down only one side of a connection is
3165 * graceful disconnect for TCP connections where you close the sending side,
3166 * then wait for the other side to close the connection, thus ensuring that the
3167 * other side saw all sent data.
3169 * Returns: %TRUE on success, %FALSE on error
3174 g_socket_shutdown (GSocket
*socket
,
3175 gboolean shutdown_read
,
3176 gboolean shutdown_write
,
3181 g_return_val_if_fail (G_IS_SOCKET (socket
), TRUE
);
3183 if (!check_socket (socket
, error
))
3187 if (!shutdown_read
&& !shutdown_write
)
3191 if (shutdown_read
&& shutdown_write
)
3193 else if (shutdown_read
)
3198 if (shutdown_read
&& shutdown_write
)
3200 else if (shutdown_read
)
3206 if (shutdown (socket
->priv
->fd
, how
) != 0)
3208 int errsv
= get_socket_errno ();
3209 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
3210 _("Unable to shutdown socket: %s"), socket_strerror (errsv
));
3215 socket
->priv
->connected_read
= FALSE
;
3217 socket
->priv
->connected_write
= FALSE
;
3224 * @socket: a #GSocket
3225 * @error: #GError for error reporting, or %NULL to ignore.
3227 * Closes the socket, shutting down any active connection.
3229 * Closing a socket does not wait for all outstanding I/O operations
3230 * to finish, so the caller should not rely on them to be guaranteed
3231 * to complete even if the close returns with no error.
3233 * Once the socket is closed, all other operations will return
3234 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
3237 * Sockets will be automatically closed when the last reference
3238 * is dropped, but you might want to call this function to make sure
3239 * resources are released as early as possible.
3241 * Beware that due to the way that TCP works, it is possible for
3242 * recently-sent data to be lost if either you close a socket while the
3243 * %G_IO_IN condition is set, or else if the remote connection tries to
3244 * send something to you after you close the socket but before it has
3245 * finished reading all of the data you sent. There is no easy generic
3246 * way to avoid this problem; the easiest fix is to design the network
3247 * protocol such that the client will never send data "out of turn".
3248 * Another solution is for the server to half-close the connection by
3249 * calling g_socket_shutdown() with only the @shutdown_write flag set,
3250 * and then wait for the client to notice this and close its side of the
3251 * connection, after which the server can safely call g_socket_close().
3252 * (This is what #GTcpConnection does if you call
3253 * g_tcp_connection_set_graceful_disconnect(). But of course, this
3254 * only works if the client will close its connection after the server
3257 * Returns: %TRUE on success, %FALSE on error
3262 g_socket_close (GSocket
*socket
,
3267 g_return_val_if_fail (G_IS_SOCKET (socket
), TRUE
);
3269 if (socket
->priv
->closed
)
3270 return TRUE
; /* Multiple close not an error */
3272 if (!check_socket (socket
, error
))
3278 res
= closesocket (socket
->priv
->fd
);
3280 res
= close (socket
->priv
->fd
);
3284 int errsv
= get_socket_errno ();
3289 g_set_error (error
, G_IO_ERROR
,
3290 socket_io_error_from_errno (errsv
),
3291 _("Error closing socket: %s"),
3292 socket_strerror (errsv
));
3298 socket
->priv
->fd
= -1;
3299 socket
->priv
->connected_read
= FALSE
;
3300 socket
->priv
->connected_write
= FALSE
;
3301 socket
->priv
->closed
= TRUE
;
3302 if (socket
->priv
->remote_address
)
3304 g_object_unref (socket
->priv
->remote_address
);
3305 socket
->priv
->remote_address
= NULL
;
3312 * g_socket_is_closed:
3313 * @socket: a #GSocket
3315 * Checks whether a socket is closed.
3317 * Returns: %TRUE if socket is closed, %FALSE otherwise
3322 g_socket_is_closed (GSocket
*socket
)
3324 return socket
->priv
->closed
;
3328 /* Broken source, used on errors */
3330 broken_dispatch (GSource
*source
,
3331 GSourceFunc callback
,
3337 static GSourceFuncs broken_funcs
=
3346 network_events_for_condition (GIOCondition condition
)
3350 if (condition
& G_IO_IN
)
3351 event_mask
|= (FD_READ
| FD_ACCEPT
);
3352 if (condition
& G_IO_OUT
)
3353 event_mask
|= (FD_WRITE
| FD_CONNECT
);
3354 event_mask
|= FD_CLOSE
;
3360 ensure_event (GSocket
*socket
)
3362 if (socket
->priv
->event
== WSA_INVALID_EVENT
)
3363 socket
->priv
->event
= WSACreateEvent();
3367 update_select_events (GSocket
*socket
)
3374 ensure_event (socket
);
3377 for (l
= socket
->priv
->requested_conditions
; l
!= NULL
; l
= l
->next
)
3380 event_mask
|= network_events_for_condition (*ptr
);
3383 if (event_mask
!= socket
->priv
->selected_events
)
3385 /* If no events selected, disable event so we can unset
3388 if (event_mask
== 0)
3391 event
= socket
->priv
->event
;
3393 if (WSAEventSelect (socket
->priv
->fd
, event
, event_mask
) == 0)
3394 socket
->priv
->selected_events
= event_mask
;
3399 add_condition_watch (GSocket
*socket
,
3400 GIOCondition
*condition
)
3402 g_mutex_lock (&socket
->priv
->win32_source_lock
);
3403 g_assert (g_list_find (socket
->priv
->requested_conditions
, condition
) == NULL
);
3405 socket
->priv
->requested_conditions
=
3406 g_list_prepend (socket
->priv
->requested_conditions
, condition
);
3408 update_select_events (socket
);
3409 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
3413 remove_condition_watch (GSocket
*socket
,
3414 GIOCondition
*condition
)
3416 g_mutex_lock (&socket
->priv
->win32_source_lock
);
3417 g_assert (g_list_find (socket
->priv
->requested_conditions
, condition
) != NULL
);
3419 socket
->priv
->requested_conditions
=
3420 g_list_remove (socket
->priv
->requested_conditions
, condition
);
3422 update_select_events (socket
);
3423 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
3427 update_condition_unlocked (GSocket
*socket
)
3429 WSANETWORKEVENTS events
;
3430 GIOCondition condition
;
3432 if (WSAEnumNetworkEvents (socket
->priv
->fd
,
3433 socket
->priv
->event
,
3436 socket
->priv
->current_events
|= events
.lNetworkEvents
;
3437 if (events
.lNetworkEvents
& FD_WRITE
&&
3438 events
.iErrorCode
[FD_WRITE_BIT
] != 0)
3439 socket
->priv
->current_errors
|= FD_WRITE
;
3440 if (events
.lNetworkEvents
& FD_CONNECT
&&
3441 events
.iErrorCode
[FD_CONNECT_BIT
] != 0)
3442 socket
->priv
->current_errors
|= FD_CONNECT
;
3446 if (socket
->priv
->current_events
& (FD_READ
| FD_ACCEPT
))
3447 condition
|= G_IO_IN
;
3449 if (socket
->priv
->current_events
& FD_CLOSE
)
3451 int r
, errsv
, buffer
;
3453 r
= recv (socket
->priv
->fd
, &buffer
, sizeof (buffer
), MSG_PEEK
);
3455 errsv
= get_socket_errno ();
3458 (r
< 0 && errsv
== WSAENOTCONN
))
3459 condition
|= G_IO_IN
;
3461 (r
< 0 && (errsv
== WSAESHUTDOWN
|| errsv
== WSAECONNRESET
||
3462 errsv
== WSAECONNABORTED
|| errsv
== WSAENETRESET
)))
3463 condition
|= G_IO_HUP
;
3465 condition
|= G_IO_ERR
;
3468 if (socket
->priv
->closed
)
3469 condition
|= G_IO_HUP
;
3471 /* Never report both G_IO_OUT and HUP, these are
3472 mutually exclusive (can't write to a closed socket) */
3473 if ((condition
& G_IO_HUP
) == 0 &&
3474 socket
->priv
->current_events
& FD_WRITE
)
3476 if (socket
->priv
->current_errors
& FD_WRITE
)
3477 condition
|= G_IO_ERR
;
3479 condition
|= G_IO_OUT
;
3483 if (socket
->priv
->current_events
& FD_CONNECT
)
3485 if (socket
->priv
->current_errors
& FD_CONNECT
)
3486 condition
|= (G_IO_HUP
| G_IO_ERR
);
3488 condition
|= G_IO_OUT
;
3496 update_condition (GSocket
*socket
)
3499 g_mutex_lock (&socket
->priv
->win32_source_lock
);
3500 res
= update_condition_unlocked (socket
);
3501 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
3514 GIOCondition condition
;
3519 socket_source_prepare_win32 (GSource
*source
,
3522 GSocketSource
*socket_source
= (GSocketSource
*)source
;
3526 return (update_condition (socket_source
->socket
) & socket_source
->condition
) != 0;
3530 socket_source_check_win32 (GSource
*source
)
3534 return socket_source_prepare_win32 (source
, &timeout
);
3539 socket_source_dispatch (GSource
*source
,
3540 GSourceFunc callback
,
3543 GSocketSourceFunc func
= (GSocketSourceFunc
)callback
;
3544 GSocketSource
*socket_source
= (GSocketSource
*)source
;
3545 GSocket
*socket
= socket_source
->socket
;
3551 events
= update_condition (socket_source
->socket
);
3553 events
= g_source_query_unix_fd (source
, socket_source
->fd_tag
);
3556 timeout
= g_source_get_ready_time (source
);
3557 if (timeout
>= 0 && timeout
< g_source_get_time (source
))
3559 socket
->priv
->timed_out
= TRUE
;
3560 events
|= (G_IO_IN
| G_IO_OUT
);
3563 ret
= (*func
) (socket
, events
& socket_source
->condition
, user_data
);
3565 if (socket
->priv
->timeout
)
3566 g_source_set_ready_time (source
, g_get_monotonic_time () + socket
->priv
->timeout
* 1000000);
3568 g_source_set_ready_time (source
, -1);
3574 socket_source_finalize (GSource
*source
)
3576 GSocketSource
*socket_source
= (GSocketSource
*)source
;
3579 socket
= socket_source
->socket
;
3582 remove_condition_watch (socket
, &socket_source
->condition
);
3585 g_object_unref (socket
);
3589 socket_source_closure_callback (GSocket
*socket
,
3590 GIOCondition condition
,
3593 GClosure
*closure
= data
;
3595 GValue params
[2] = { G_VALUE_INIT
, G_VALUE_INIT
};
3596 GValue result_value
= G_VALUE_INIT
;
3599 g_value_init (&result_value
, G_TYPE_BOOLEAN
);
3601 g_value_init (¶ms
[0], G_TYPE_SOCKET
);
3602 g_value_set_object (¶ms
[0], socket
);
3603 g_value_init (¶ms
[1], G_TYPE_IO_CONDITION
);
3604 g_value_set_flags (¶ms
[1], condition
);
3606 g_closure_invoke (closure
, &result_value
, 2, params
, NULL
);
3608 result
= g_value_get_boolean (&result_value
);
3609 g_value_unset (&result_value
);
3610 g_value_unset (¶ms
[0]);
3611 g_value_unset (¶ms
[1]);
3616 static GSourceFuncs socket_source_funcs
=
3619 socket_source_prepare_win32
,
3620 socket_source_check_win32
,
3622 NULL
, NULL
, /* check, prepare */
3624 socket_source_dispatch
,
3625 socket_source_finalize
,
3626 (GSourceFunc
)socket_source_closure_callback
,
3630 socket_source_new (GSocket
*socket
,
3631 GIOCondition condition
,
3632 GCancellable
*cancellable
)
3635 GSocketSource
*socket_source
;
3638 ensure_event (socket
);
3640 if (socket
->priv
->event
== WSA_INVALID_EVENT
)
3642 g_warning ("Failed to create WSAEvent");
3643 return g_source_new (&broken_funcs
, sizeof (GSource
));
3647 condition
|= G_IO_HUP
| G_IO_ERR
| G_IO_NVAL
;
3649 source
= g_source_new (&socket_source_funcs
, sizeof (GSocketSource
));
3650 g_source_set_name (source
, "GSocket");
3651 socket_source
= (GSocketSource
*)source
;
3653 socket_source
->socket
= g_object_ref (socket
);
3654 socket_source
->condition
= condition
;
3658 GSource
*cancellable_source
;
3660 cancellable_source
= g_cancellable_source_new (cancellable
);
3661 g_source_add_child_source (source
, cancellable_source
);
3662 g_source_set_dummy_callback (cancellable_source
);
3663 g_source_unref (cancellable_source
);
3667 add_condition_watch (socket
, &socket_source
->condition
);
3668 socket_source
->pollfd
.fd
= (gintptr
) socket
->priv
->event
;
3669 socket_source
->pollfd
.events
= condition
;
3670 socket_source
->pollfd
.revents
= 0;
3671 g_source_add_poll (source
, &socket_source
->pollfd
);
3673 socket_source
->fd_tag
= g_source_add_unix_fd (source
, socket
->priv
->fd
, condition
);
3676 if (socket
->priv
->timeout
)
3677 g_source_set_ready_time (source
, g_get_monotonic_time () + socket
->priv
->timeout
* 1000000);
3679 g_source_set_ready_time (source
, -1);
3685 * g_socket_create_source: (skip)
3686 * @socket: a #GSocket
3687 * @condition: a #GIOCondition mask to monitor
3688 * @cancellable: (nullable): a %GCancellable or %NULL
3690 * Creates a #GSource that can be attached to a %GMainContext to monitor
3691 * for the availability of the specified @condition on the socket. The #GSource
3692 * keeps a reference to the @socket.
3694 * The callback on the source is of the #GSocketSourceFunc type.
3696 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3697 * these conditions will always be reported output if they are true.
3699 * @cancellable if not %NULL can be used to cancel the source, which will
3700 * cause the source to trigger, reporting the current condition (which
3701 * is likely 0 unless cancellation happened at the same time as a
3702 * condition change). You can check for this in the callback using
3703 * g_cancellable_is_cancelled().
3705 * If @socket has a timeout set, and it is reached before @condition
3706 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3707 * %G_IO_OUT depending on @condition. However, @socket will have been
3708 * marked as having had a timeout, and so the next #GSocket I/O method
3709 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3711 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3716 g_socket_create_source (GSocket
*socket
,
3717 GIOCondition condition
,
3718 GCancellable
*cancellable
)
3720 g_return_val_if_fail (G_IS_SOCKET (socket
) && (cancellable
== NULL
|| G_IS_CANCELLABLE (cancellable
)), NULL
);
3722 return socket_source_new (socket
, condition
, cancellable
);
3726 * g_socket_condition_check:
3727 * @socket: a #GSocket
3728 * @condition: a #GIOCondition mask to check
3730 * Checks on the readiness of @socket to perform operations.
3731 * The operations specified in @condition are checked for and masked
3732 * against the currently-satisfied conditions on @socket. The result
3735 * Note that on Windows, it is possible for an operation to return
3736 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3737 * g_socket_condition_check() has claimed that the socket is ready for
3738 * writing. Rather than calling g_socket_condition_check() and then
3739 * writing to the socket if it succeeds, it is generally better to
3740 * simply try writing to the socket right away, and try again later if
3741 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3743 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3744 * these conditions will always be set in the output if they are true.
3746 * This call never blocks.
3748 * Returns: the @GIOCondition mask of the current state
3753 g_socket_condition_check (GSocket
*socket
,
3754 GIOCondition condition
)
3756 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
3758 if (!check_socket (socket
, NULL
))
3763 GIOCondition current_condition
;
3765 condition
|= G_IO_ERR
| G_IO_HUP
;
3767 add_condition_watch (socket
, &condition
);
3768 current_condition
= update_condition (socket
);
3769 remove_condition_watch (socket
, &condition
);
3770 return condition
& current_condition
;
3776 poll_fd
.fd
= socket
->priv
->fd
;
3777 poll_fd
.events
= condition
;
3778 poll_fd
.revents
= 0;
3781 result
= g_poll (&poll_fd
, 1, 0);
3782 while (result
== -1 && get_socket_errno () == EINTR
);
3784 return poll_fd
.revents
;
3790 * g_socket_condition_wait:
3791 * @socket: a #GSocket
3792 * @condition: a #GIOCondition mask to wait for
3793 * @cancellable: (nullable): a #GCancellable, or %NULL
3794 * @error: a #GError pointer, or %NULL
3796 * Waits for @condition to become true on @socket. When the condition
3797 * is met, %TRUE is returned.
3799 * If @cancellable is cancelled before the condition is met, or if the
3800 * socket has a timeout set and it is reached before the condition is
3801 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3802 * the appropriate value (%G_IO_ERROR_CANCELLED or
3803 * %G_IO_ERROR_TIMED_OUT).
3805 * See also g_socket_condition_timed_wait().
3807 * Returns: %TRUE if the condition was met, %FALSE otherwise
3812 g_socket_condition_wait (GSocket
*socket
,
3813 GIOCondition condition
,
3814 GCancellable
*cancellable
,
3817 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
3819 return g_socket_condition_timed_wait (socket
, condition
, -1,
3820 cancellable
, error
);
3824 * g_socket_condition_timed_wait:
3825 * @socket: a #GSocket
3826 * @condition: a #GIOCondition mask to wait for
3827 * @timeout: the maximum time (in microseconds) to wait, or -1
3828 * @cancellable: (nullable): a #GCancellable, or %NULL
3829 * @error: a #GError pointer, or %NULL
3831 * Waits for up to @timeout microseconds for @condition to become true
3832 * on @socket. If the condition is met, %TRUE is returned.
3834 * If @cancellable is cancelled before the condition is met, or if
3835 * @timeout (or the socket's #GSocket:timeout) is reached before the
3836 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3837 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3838 * %G_IO_ERROR_TIMED_OUT).
3840 * If you don't want a timeout, use g_socket_condition_wait().
3841 * (Alternatively, you can pass -1 for @timeout.)
3843 * Note that although @timeout is in microseconds for consistency with
3844 * other GLib APIs, this function actually only has millisecond
3845 * resolution, and the behavior is undefined if @timeout is not an
3846 * exact number of milliseconds.
3848 * Returns: %TRUE if the condition was met, %FALSE otherwise
3853 g_socket_condition_timed_wait (GSocket
*socket
,
3854 GIOCondition condition
,
3856 GCancellable
*cancellable
,
3861 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
3863 if (!check_socket (socket
, error
))
3866 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
3869 if (socket
->priv
->timeout
&&
3870 (timeout
< 0 || socket
->priv
->timeout
< timeout
/ G_USEC_PER_SEC
))
3871 timeout
= (gint64
) socket
->priv
->timeout
* 1000;
3872 else if (timeout
!= -1)
3873 timeout
= timeout
/ 1000;
3875 start_time
= g_get_monotonic_time ();
3879 GIOCondition current_condition
;
3885 /* Always check these */
3886 condition
|= G_IO_ERR
| G_IO_HUP
;
3888 add_condition_watch (socket
, &condition
);
3891 events
[num_events
++] = socket
->priv
->event
;
3893 if (g_cancellable_make_pollfd (cancellable
, &cancel_fd
))
3894 events
[num_events
++] = (WSAEVENT
)cancel_fd
.fd
;
3897 timeout
= WSA_INFINITE
;
3899 g_mutex_lock (&socket
->priv
->win32_source_lock
);
3900 current_condition
= update_condition_unlocked (socket
);
3901 while ((condition
& current_condition
) == 0)
3903 if (!socket
->priv
->waiting
)
3905 socket
->priv
->waiting
= TRUE
;
3906 socket
->priv
->waiting_result
= 0;
3907 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
3909 res
= WSAWaitForMultipleEvents (num_events
, events
, FALSE
, timeout
, FALSE
);
3911 g_mutex_lock (&socket
->priv
->win32_source_lock
);
3912 socket
->priv
->waiting
= FALSE
;
3913 socket
->priv
->waiting_result
= res
;
3914 g_cond_broadcast (&socket
->priv
->win32_source_cond
);
3918 if (timeout
!= WSA_INFINITE
)
3920 if (!g_cond_wait_until (&socket
->priv
->win32_source_cond
, &socket
->priv
->win32_source_lock
, timeout
))
3922 res
= WSA_WAIT_TIMEOUT
;
3927 res
= socket
->priv
->waiting_result
;
3932 g_cond_wait (&socket
->priv
->win32_source_cond
, &socket
->priv
->win32_source_lock
);
3933 res
= socket
->priv
->waiting_result
;
3937 if (res
== WSA_WAIT_FAILED
)
3939 int errsv
= get_socket_errno ();
3941 g_set_error (error
, G_IO_ERROR
,
3942 socket_io_error_from_errno (errsv
),
3943 _("Waiting for socket condition: %s"),
3944 socket_strerror (errsv
));
3947 else if (res
== WSA_WAIT_TIMEOUT
)
3949 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
,
3950 _("Socket I/O timed out"));
3954 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
3957 current_condition
= update_condition_unlocked (socket
);
3959 if (timeout
!= WSA_INFINITE
)
3961 timeout
-= (g_get_monotonic_time () - start_time
) * 1000;
3966 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
3967 remove_condition_watch (socket
, &condition
);
3969 g_cancellable_release_fd (cancellable
);
3971 return (condition
& current_condition
) != 0;
3979 poll_fd
[0].fd
= socket
->priv
->fd
;
3980 poll_fd
[0].events
= condition
;
3983 if (g_cancellable_make_pollfd (cancellable
, &poll_fd
[1]))
3989 result
= g_poll (poll_fd
, num
, timeout
);
3991 if (result
!= -1 || errsv
!= EINTR
)
3996 timeout
-= (g_get_monotonic_time () - start_time
) / 1000;
4003 g_cancellable_release_fd (cancellable
);
4007 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
,
4008 _("Socket I/O timed out"));
4012 return !g_cancellable_set_error_if_cancelled (cancellable
, error
);
4019 /* Unfortunately these have to be macros rather than inline functions due to
4020 * using alloca(). */
4021 #define output_message_to_msghdr(message, prev_message, msg, prev_msg, error) \
4023 const GOutputMessage *_message = (message); \
4024 const GOutputMessage *_prev_message = (prev_message); \
4025 struct msghdr *_msg = (msg); \
4026 const struct msghdr *_prev_msg = (prev_msg); \
4027 GError **_error = (error); \
4029 _msg->msg_flags = 0; \
4032 if (_prev_message != NULL && _prev_message->address == _message->address) \
4034 _msg->msg_name = _prev_msg->msg_name; \
4035 _msg->msg_namelen = _prev_msg->msg_namelen; \
4037 else if (_message->address != NULL) \
4039 _msg->msg_namelen = g_socket_address_get_native_size (_message->address); \
4040 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4041 if (!g_socket_address_to_native (_message->address, _msg->msg_name, \
4042 _msg->msg_namelen, _error)) \
4047 _msg->msg_name = NULL; \
4048 _msg->msg_namelen = 0; \
4053 /* this entire expression will be evaluated at compile time */ \
4054 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4055 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4056 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4057 G_STRUCT_OFFSET (GOutputVector, buffer) && \
4058 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4059 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4060 G_STRUCT_OFFSET (GOutputVector, size)) \
4061 /* ABI is compatible */ \
4063 _msg->msg_iov = (struct iovec *) _message->vectors; \
4064 _msg->msg_iovlen = _message->num_vectors; \
4067 /* ABI is incompatible */ \
4071 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4072 for (i = 0; i < _message->num_vectors; i++) \
4074 _msg->msg_iov[i].iov_base = (void *) _message->vectors[i].buffer; \
4075 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4077 _msg->msg_iovlen = _message->num_vectors; \
4083 struct cmsghdr *cmsg; \
4086 _msg->msg_controllen = 0; \
4087 for (i = 0; i < _message->num_control_messages; i++) \
4088 _msg->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (_message->control_messages[i])); \
4090 if (_msg->msg_controllen == 0) \
4091 _msg->msg_control = NULL; \
4094 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4095 memset (_msg->msg_control, '\0', _msg->msg_controllen); \
4098 cmsg = CMSG_FIRSTHDR (_msg); \
4099 for (i = 0; i < _message->num_control_messages; i++) \
4101 cmsg->cmsg_level = g_socket_control_message_get_level (_message->control_messages[i]); \
4102 cmsg->cmsg_type = g_socket_control_message_get_msg_type (_message->control_messages[i]); \
4103 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (_message->control_messages[i])); \
4104 g_socket_control_message_serialize (_message->control_messages[i], \
4105 CMSG_DATA (cmsg)); \
4106 cmsg = CMSG_NXTHDR (_msg, cmsg); \
4108 g_assert (cmsg == NULL); \
4112 #define input_message_to_msghdr(message, msg) \
4114 const GInputMessage *_message = (message); \
4115 struct msghdr *_msg = (msg); \
4118 if (_message->address) \
4120 _msg->msg_namelen = sizeof (struct sockaddr_storage); \
4121 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4125 _msg->msg_name = NULL; \
4126 _msg->msg_namelen = 0; \
4130 /* this entire expression will be evaluated at compile time */ \
4131 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4132 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4133 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4134 G_STRUCT_OFFSET (GInputVector, buffer) && \
4135 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4136 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4137 G_STRUCT_OFFSET (GInputVector, size)) \
4138 /* ABI is compatible */ \
4140 _msg->msg_iov = (struct iovec *) _message->vectors; \
4141 _msg->msg_iovlen = _message->num_vectors; \
4144 /* ABI is incompatible */ \
4148 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4149 for (i = 0; i < _message->num_vectors; i++) \
4151 _msg->msg_iov[i].iov_base = _message->vectors[i].buffer; \
4152 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4154 _msg->msg_iovlen = _message->num_vectors; \
4158 if (_message->control_messages == NULL) \
4160 _msg->msg_controllen = 0; \
4161 _msg->msg_control = NULL; \
4165 _msg->msg_controllen = 2048; \
4166 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4170 _msg->msg_flags = _message->flags; \
4174 input_message_from_msghdr (const struct msghdr
*msg
,
4175 GInputMessage
*message
,
4178 /* decode address */
4179 if (message
->address
!= NULL
)
4181 *message
->address
= cache_recv_address (socket
, msg
->msg_name
,
4185 /* decode control messages */
4187 GPtrArray
*my_messages
= NULL
;
4188 struct cmsghdr
*cmsg
;
4190 if (msg
->msg_controllen
>= sizeof (struct cmsghdr
))
4192 g_assert (message
->control_messages
!= NULL
);
4193 for (cmsg
= CMSG_FIRSTHDR (msg
);
4195 cmsg
= CMSG_NXTHDR ((struct msghdr
*) msg
, cmsg
))
4197 GSocketControlMessage
*control_message
;
4199 control_message
= g_socket_control_message_deserialize (cmsg
->cmsg_level
,
4201 cmsg
->cmsg_len
- ((char *)CMSG_DATA (cmsg
) - (char *)cmsg
),
4203 if (control_message
== NULL
)
4204 /* We've already spewed about the problem in the
4205 deserialization code, so just continue */
4208 if (my_messages
== NULL
)
4209 my_messages
= g_ptr_array_new ();
4210 g_ptr_array_add (my_messages
, control_message
);
4214 if (message
->num_control_messages
)
4215 *message
->num_control_messages
= my_messages
!= NULL
? my_messages
->len
: 0;
4217 if (message
->control_messages
)
4219 if (my_messages
== NULL
)
4221 *message
->control_messages
= NULL
;
4225 g_ptr_array_add (my_messages
, NULL
);
4226 *message
->control_messages
= (GSocketControlMessage
**) g_ptr_array_free (my_messages
, FALSE
);
4231 g_assert (my_messages
== NULL
);
4235 /* capture the flags */
4236 message
->flags
= msg
->msg_flags
;
4241 * g_socket_send_message:
4242 * @socket: a #GSocket
4243 * @address: (nullable): a #GSocketAddress, or %NULL
4244 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4245 * @num_vectors: the number of elements in @vectors, or -1
4246 * @messages: (array length=num_messages) (nullable): a pointer to an
4247 * array of #GSocketControlMessages, or %NULL.
4248 * @num_messages: number of elements in @messages, or -1.
4249 * @flags: an int containing #GSocketMsgFlags flags
4250 * @cancellable: (nullable): a %GCancellable or %NULL
4251 * @error: #GError for error reporting, or %NULL to ignore.
4253 * Send data to @address on @socket. For sending multiple messages see
4254 * g_socket_send_messages(); for easier use, see
4255 * g_socket_send() and g_socket_send_to().
4257 * If @address is %NULL then the message is sent to the default receiver
4258 * (set by g_socket_connect()).
4260 * @vectors must point to an array of #GOutputVector structs and
4261 * @num_vectors must be the length of this array. (If @num_vectors is -1,
4262 * then @vectors is assumed to be terminated by a #GOutputVector with a
4263 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
4264 * that the sent data will be gathered from. Using multiple
4265 * #GOutputVectors is more memory-efficient than manually copying
4266 * data from multiple sources into a single buffer, and more
4267 * network-efficient than making multiple calls to g_socket_send().
4269 * @messages, if non-%NULL, is taken to point to an array of @num_messages
4270 * #GSocketControlMessage instances. These correspond to the control
4271 * messages to be sent on the socket.
4272 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
4275 * @flags modify how the message is sent. The commonly available arguments
4276 * for this are available in the #GSocketMsgFlags enum, but the
4277 * values there are the same as the system values, and the flags
4278 * are passed in as-is, so you can pass in system-specific flags too.
4280 * If the socket is in blocking mode the call will block until there is
4281 * space for the data in the socket queue. If there is no space available
4282 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4283 * will be returned. To be notified when space is available, wait for the
4284 * %G_IO_OUT condition. Note though that you may still receive
4285 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4286 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4287 * very common due to the way the underlying APIs work.)
4289 * On error -1 is returned and @error is set accordingly.
4291 * Returns: Number of bytes written (which may be less than @size), or -1
4297 g_socket_send_message (GSocket
*socket
,
4298 GSocketAddress
*address
,
4299 GOutputVector
*vectors
,
4301 GSocketControlMessage
**messages
,
4304 GCancellable
*cancellable
,
4307 return g_socket_send_message_with_timeout (socket
, address
,
4308 vectors
, num_vectors
,
4309 messages
, num_messages
, flags
,
4310 socket
->priv
->blocking
? -1 : 0,
4311 cancellable
, error
);
4315 g_socket_send_message_with_timeout (GSocket
*socket
,
4316 GSocketAddress
*address
,
4317 GOutputVector
*vectors
,
4319 GSocketControlMessage
**messages
,
4323 GCancellable
*cancellable
,
4326 GOutputVector one_vector
;
4330 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
4331 g_return_val_if_fail (address
== NULL
|| G_IS_SOCKET_ADDRESS (address
), -1);
4332 g_return_val_if_fail (num_vectors
== 0 || vectors
!= NULL
, -1);
4333 g_return_val_if_fail (num_messages
== 0 || messages
!= NULL
, -1);
4334 g_return_val_if_fail (cancellable
== NULL
|| G_IS_CANCELLABLE (cancellable
), -1);
4335 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, -1);
4337 start_time
= g_get_monotonic_time ();
4339 if (!check_socket (socket
, error
))
4342 if (!check_timeout (socket
, error
))
4345 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
4348 if (num_vectors
== -1)
4350 for (num_vectors
= 0;
4351 vectors
[num_vectors
].buffer
!= NULL
;
4356 if (num_messages
== -1)
4358 for (num_messages
= 0;
4359 messages
!= NULL
&& messages
[num_messages
] != NULL
;
4364 if (num_vectors
== 0)
4368 one_vector
.buffer
= &zero
;
4369 one_vector
.size
= 1;
4371 vectors
= &one_vector
;
4376 GOutputMessage output_message
;
4379 GError
*child_error
= NULL
;
4381 output_message
.address
= address
;
4382 output_message
.vectors
= vectors
;
4383 output_message
.num_vectors
= num_vectors
;
4384 output_message
.bytes_sent
= 0;
4385 output_message
.control_messages
= messages
;
4386 output_message
.num_control_messages
= num_messages
;
4388 output_message_to_msghdr (&output_message
, NULL
, &msg
, NULL
, &child_error
);
4390 if (child_error
!= NULL
)
4392 g_propagate_error (error
, child_error
);
4398 result
= sendmsg (socket
->priv
->fd
, &msg
, flags
| G_SOCKET_DEFAULT_SEND_FLAGS
);
4401 int errsv
= get_socket_errno ();
4407 (errsv
== EWOULDBLOCK
||
4410 if (!block_on_timeout (socket
, G_IO_OUT
, timeout
, start_time
,
4411 cancellable
, error
))
4417 socket_set_error_lazy (error
, errsv
, _("Error sending message: %s"));
4427 struct sockaddr_storage addr
;
4434 /* Win32 doesn't support control messages.
4435 Actually this is possible for raw and datagram sockets
4436 via WSASendMessage on Vista or later, but that doesn't
4438 if (num_messages
!= 0)
4440 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
4441 _("GSocketControlMessage not supported on Windows"));
4446 bufs
= g_newa (WSABUF
, num_vectors
);
4447 for (i
= 0; i
< num_vectors
; i
++)
4449 bufs
[i
].buf
= (char *)vectors
[i
].buffer
;
4450 bufs
[i
].len
= (gulong
)vectors
[i
].size
;
4454 addrlen
= 0; /* Avoid warning */
4457 addrlen
= g_socket_address_get_native_size (address
);
4458 if (!g_socket_address_to_native (address
, &addr
, sizeof addr
, error
))
4464 win32_unset_event_mask (socket
, FD_WRITE
);
4467 result
= WSASendTo (socket
->priv
->fd
,
4470 (const struct sockaddr
*)&addr
, addrlen
,
4473 result
= WSASend (socket
->priv
->fd
,
4480 int errsv
= get_socket_errno ();
4482 if (errsv
== WSAEINTR
)
4485 if (errsv
== WSAEWOULDBLOCK
)
4489 if (!block_on_timeout (socket
, G_IO_OUT
, timeout
,
4490 start_time
, cancellable
, error
))
4497 socket_set_error_lazy (error
, errsv
, _("Error sending message: %s"));
4509 * g_socket_send_messages:
4510 * @socket: a #GSocket
4511 * @messages: (array length=num_messages): an array of #GOutputMessage structs
4512 * @num_messages: the number of elements in @messages
4513 * @flags: an int containing #GSocketMsgFlags flags
4514 * @cancellable: (nullable): a %GCancellable or %NULL
4515 * @error: #GError for error reporting, or %NULL to ignore.
4517 * Send multiple data messages from @socket in one go. This is the most
4518 * complicated and fully-featured version of this call. For easier use, see
4519 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
4521 * @messages must point to an array of #GOutputMessage structs and
4522 * @num_messages must be the length of this array. Each #GOutputMessage
4523 * contains an address to send the data to, and a pointer to an array of
4524 * #GOutputVector structs to describe the buffers that the data to be sent
4525 * for each message will be gathered from. Using multiple #GOutputVectors is
4526 * more memory-efficient than manually copying data from multiple sources
4527 * into a single buffer, and more network-efficient than making multiple
4528 * calls to g_socket_send(). Sending multiple messages in one go avoids the
4529 * overhead of making a lot of syscalls in scenarios where a lot of data
4530 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
4531 * or where the same data needs to be sent to multiple recipients.
4533 * @flags modify how the message is sent. The commonly available arguments
4534 * for this are available in the #GSocketMsgFlags enum, but the
4535 * values there are the same as the system values, and the flags
4536 * are passed in as-is, so you can pass in system-specific flags too.
4538 * If the socket is in blocking mode the call will block until there is
4539 * space for all the data in the socket queue. If there is no space available
4540 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4541 * will be returned if no data was written at all, otherwise the number of
4542 * messages sent will be returned. To be notified when space is available,
4543 * wait for the %G_IO_OUT condition. Note though that you may still receive
4544 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4545 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4546 * very common due to the way the underlying APIs work.)
4548 * On error -1 is returned and @error is set accordingly. An error will only
4549 * be returned if zero messages could be sent; otherwise the number of messages
4550 * successfully sent before the error will be returned.
4552 * Returns: number of messages sent, or -1 on error. Note that the number of
4553 * messages sent may be smaller than @num_messages if the socket is
4554 * non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
4555 * in which case the caller may re-try to send the remaining messages.
4560 g_socket_send_messages (GSocket
*socket
,
4561 GOutputMessage
*messages
,
4564 GCancellable
*cancellable
,
4567 return g_socket_send_messages_with_timeout (socket
, messages
, num_messages
,
4569 socket
->priv
->blocking
? -1 : 0,
4570 cancellable
, error
);
4574 g_socket_send_messages_with_timeout (GSocket
*socket
,
4575 GOutputMessage
*messages
,
4579 GCancellable
*cancellable
,
4584 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
4585 g_return_val_if_fail (num_messages
== 0 || messages
!= NULL
, -1);
4586 g_return_val_if_fail (cancellable
== NULL
|| G_IS_CANCELLABLE (cancellable
), -1);
4587 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, -1);
4589 start_time
= g_get_monotonic_time ();
4591 if (!check_socket (socket
, error
))
4594 if (!check_timeout (socket
, error
))
4597 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
4600 if (num_messages
== 0)
4603 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
4605 struct mmsghdr
*msgvec
;
4609 #define MAX_NUM_MESSAGES UIO_MAXIOV
4611 #define MAX_NUM_MESSAGES 1024
4614 if (num_messages
> MAX_NUM_MESSAGES
)
4615 num_messages
= MAX_NUM_MESSAGES
;
4617 msgvec
= g_newa (struct mmsghdr
, num_messages
);
4619 for (i
= 0; i
< num_messages
; ++i
)
4621 GOutputMessage
*msg
= &messages
[i
];
4622 struct msghdr
*msg_hdr
= &msgvec
[i
].msg_hdr
;
4623 GError
*child_error
= NULL
;
4625 msgvec
[i
].msg_len
= 0;
4627 output_message_to_msghdr (msg
, (i
> 0) ? &messages
[i
- 1] : NULL
,
4628 msg_hdr
, (i
> 0) ? &msgvec
[i
- 1].msg_hdr
: NULL
,
4631 if (child_error
!= NULL
)
4633 g_propagate_error (error
, child_error
);
4638 for (num_sent
= 0; num_sent
< num_messages
;)
4642 ret
= sendmmsg (socket
->priv
->fd
, msgvec
+ num_sent
, num_messages
- num_sent
,
4643 flags
| G_SOCKET_DEFAULT_SEND_FLAGS
);
4647 int errsv
= get_socket_errno ();
4653 (errsv
== EWOULDBLOCK
||
4656 if (!block_on_timeout (socket
, G_IO_OUT
, timeout
, start_time
,
4657 cancellable
, error
))
4661 g_clear_error (error
);
4671 /* If any messages were successfully sent, do not error. */
4675 socket_set_error_lazy (error
, errsv
, _("Error sending message: %s"));
4683 for (i
= 0; i
< num_sent
; ++i
)
4684 messages
[i
].bytes_sent
= msgvec
[i
].msg_len
;
4692 gint64 wait_timeout
;
4694 wait_timeout
= timeout
;
4696 for (i
= 0; i
< num_messages
; ++i
)
4698 GOutputMessage
*msg
= &messages
[i
];
4699 GError
*msg_error
= NULL
;
4701 result
= g_socket_send_message_with_timeout (socket
, msg
->address
,
4704 msg
->control_messages
,
4705 msg
->num_control_messages
,
4706 flags
, wait_timeout
,
4707 cancellable
, &msg_error
);
4709 /* check if we've timed out or how much time to wait at most */
4712 gint64 elapsed
= g_get_monotonic_time () - start_time
;
4713 wait_timeout
= MAX (timeout
- elapsed
, 1);
4718 /* if we couldn't send all messages, just return how many we did
4719 * manage to send, provided we managed to send at least one */
4722 g_error_free (msg_error
);
4727 g_propagate_error (error
, msg_error
);
4732 msg
->bytes_sent
= result
;
4740 static GSocketAddress
*
4741 cache_recv_address (GSocket
*socket
, struct sockaddr
*native
, int native_len
)
4743 GSocketAddress
*saddr
;
4745 guint64 oldest_time
= G_MAXUINT64
;
4746 gint oldest_index
= 0;
4748 if (native_len
<= 0)
4752 for (i
= 0; i
< RECV_ADDR_CACHE_SIZE
; i
++)
4754 GSocketAddress
*tmp
= socket
->priv
->recv_addr_cache
[i
].addr
;
4755 gpointer tmp_native
= socket
->priv
->recv_addr_cache
[i
].native
;
4756 gint tmp_native_len
= socket
->priv
->recv_addr_cache
[i
].native_len
;
4761 if (tmp_native_len
!= native_len
)
4764 if (memcmp (tmp_native
, native
, native_len
) == 0)
4766 saddr
= g_object_ref (tmp
);
4767 socket
->priv
->recv_addr_cache
[i
].last_used
= g_get_monotonic_time ();
4771 if (socket
->priv
->recv_addr_cache
[i
].last_used
< oldest_time
)
4773 oldest_time
= socket
->priv
->recv_addr_cache
[i
].last_used
;
4778 saddr
= g_socket_address_new_from_native (native
, native_len
);
4780 if (socket
->priv
->recv_addr_cache
[oldest_index
].addr
)
4782 g_object_unref (socket
->priv
->recv_addr_cache
[oldest_index
].addr
);
4783 g_free (socket
->priv
->recv_addr_cache
[oldest_index
].native
);
4786 socket
->priv
->recv_addr_cache
[oldest_index
].native
= g_memdup (native
, native_len
);
4787 socket
->priv
->recv_addr_cache
[oldest_index
].native_len
= native_len
;
4788 socket
->priv
->recv_addr_cache
[oldest_index
].addr
= g_object_ref (saddr
);
4789 socket
->priv
->recv_addr_cache
[oldest_index
].last_used
= g_get_monotonic_time ();
4795 g_socket_receive_message_with_timeout (GSocket
*socket
,
4796 GSocketAddress
**address
,
4797 GInputVector
*vectors
,
4799 GSocketControlMessage
***messages
,
4803 GCancellable
*cancellable
,
4806 GInputVector one_vector
;
4810 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
4812 start_time
= g_get_monotonic_time ();
4814 if (!check_socket (socket
, error
))
4817 if (!check_timeout (socket
, error
))
4820 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
4823 if (num_vectors
== -1)
4825 for (num_vectors
= 0;
4826 vectors
[num_vectors
].buffer
!= NULL
;
4831 if (num_vectors
== 0)
4833 one_vector
.buffer
= &one_byte
;
4834 one_vector
.size
= 1;
4836 vectors
= &one_vector
;
4841 GInputMessage input_message
;
4845 input_message
.address
= address
;
4846 input_message
.vectors
= vectors
;
4847 input_message
.num_vectors
= num_vectors
;
4848 input_message
.bytes_received
= 0;
4849 input_message
.flags
= (flags
!= NULL
) ? *flags
: 0;
4850 input_message
.control_messages
= messages
;
4851 input_message
.num_control_messages
= (guint
*) num_messages
;
4853 /* We always set the close-on-exec flag so we don't leak file
4854 * descriptors into child processes. Note that gunixfdmessage.c
4855 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4857 #ifdef MSG_CMSG_CLOEXEC
4858 input_message
.flags
|= MSG_CMSG_CLOEXEC
;
4861 input_message_to_msghdr (&input_message
, &msg
);
4866 result
= recvmsg (socket
->priv
->fd
, &msg
, msg
.msg_flags
);
4867 #ifdef MSG_CMSG_CLOEXEC
4868 if (result
< 0 && get_socket_errno () == EINVAL
)
4870 /* We must be running on an old kernel. Call without the flag. */
4871 msg
.msg_flags
&= ~(MSG_CMSG_CLOEXEC
);
4872 result
= recvmsg (socket
->priv
->fd
, &msg
, msg
.msg_flags
);
4878 int errsv
= get_socket_errno ();
4884 (errsv
== EWOULDBLOCK
||
4887 if (!block_on_timeout (socket
, G_IO_IN
, timeout
, start_time
,
4888 cancellable
, error
))
4894 socket_set_error_lazy (error
, errsv
, _("Error receiving message: %s"));
4900 input_message_from_msghdr (&msg
, &input_message
, socket
);
4903 *flags
= input_message
.flags
;
4909 struct sockaddr_storage addr
;
4911 DWORD bytes_received
;
4918 bufs
= g_newa (WSABUF
, num_vectors
);
4919 for (i
= 0; i
< num_vectors
; i
++)
4921 bufs
[i
].buf
= (char *)vectors
[i
].buffer
;
4922 bufs
[i
].len
= (gulong
)vectors
[i
].size
;
4934 win32_unset_event_mask (socket
, FD_READ
);
4936 addrlen
= sizeof addr
;
4938 result
= WSARecvFrom (socket
->priv
->fd
,
4940 &bytes_received
, &win_flags
,
4941 (struct sockaddr
*)&addr
, &addrlen
,
4944 result
= WSARecv (socket
->priv
->fd
,
4946 &bytes_received
, &win_flags
,
4950 int errsv
= get_socket_errno ();
4952 if (errsv
== WSAEINTR
)
4955 if (errsv
== WSAEWOULDBLOCK
)
4959 if (!block_on_timeout (socket
, G_IO_IN
, timeout
,
4960 start_time
, cancellable
, error
))
4967 socket_set_error_lazy (error
, errsv
, _("Error receiving message: %s"));
4973 /* decode address */
4974 if (address
!= NULL
)
4976 *address
= cache_recv_address (socket
, (struct sockaddr
*)&addr
, addrlen
);
4979 /* capture the flags */
4983 if (messages
!= NULL
)
4985 if (num_messages
!= NULL
)
4988 return bytes_received
;
4994 * g_socket_receive_messages:
4995 * @socket: a #GSocket
4996 * @messages: (array length=num_messages): an array of #GInputMessage structs
4997 * @num_messages: the number of elements in @messages
4998 * @flags: an int containing #GSocketMsgFlags flags for the overall operation
4999 * @cancellable: (nullable): a %GCancellable or %NULL
5000 * @error: #GError for error reporting, or %NULL to ignore
5002 * Receive multiple data messages from @socket in one go. This is the most
5003 * complicated and fully-featured version of this call. For easier use, see
5004 * g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
5006 * @messages must point to an array of #GInputMessage structs and
5007 * @num_messages must be the length of this array. Each #GInputMessage
5008 * contains a pointer to an array of #GInputVector structs describing the
5009 * buffers that the data received in each message will be written to. Using
5010 * multiple #GInputVectors is more memory-efficient than manually copying data
5011 * out of a single buffer to multiple sources, and more system-call-efficient
5012 * than making multiple calls to g_socket_receive(), such as in scenarios where
5013 * a lot of data packets need to be received (e.g. high-bandwidth video
5014 * streaming over RTP/UDP).
5016 * @flags modify how all messages are received. The commonly available
5017 * arguments for this are available in the #GSocketMsgFlags enum, but the
5018 * values there are the same as the system values, and the flags
5019 * are passed in as-is, so you can pass in system-specific flags too. These
5020 * flags affect the overall receive operation. Flags affecting individual
5021 * messages are returned in #GInputMessage.flags.
5023 * The other members of #GInputMessage are treated as described in its
5026 * If #GSocket:blocking is %TRUE the call will block until @num_messages have
5027 * been received, or the end of the stream is reached.
5029 * If #GSocket:blocking is %FALSE the call will return up to @num_messages
5030 * without blocking, or %G_IO_ERROR_WOULD_BLOCK if no messages are queued in the
5031 * operating system to be received.
5033 * In blocking mode, if #GSocket:timeout is positive and is reached before any
5034 * messages are received, %G_IO_ERROR_TIMED_OUT is returned, otherwise up to
5035 * @num_messages are returned. (Note: This is effectively the
5036 * behaviour of `MSG_WAITFORONE` with recvmmsg().)
5038 * To be notified when messages are available, wait for the
5039 * %G_IO_IN condition. Note though that you may still receive
5040 * %G_IO_ERROR_WOULD_BLOCK from g_socket_receive_messages() even if you were
5041 * previously notified of a %G_IO_IN condition.
5043 * If the remote peer closes the connection, any messages queued in the
5044 * operating system will be returned, and subsequent calls to
5045 * g_socket_receive_messages() will return 0 (with no error set).
5047 * On error -1 is returned and @error is set accordingly. An error will only
5048 * be returned if zero messages could be received; otherwise the number of
5049 * messages successfully received before the error will be returned.
5051 * Returns: number of messages received, or -1 on error. Note that the number
5052 * of messages received may be smaller than @num_messages if in non-blocking
5053 * mode, if the peer closed the connection, or if @num_messages
5054 * was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
5055 * to receive the remaining messages.
5060 g_socket_receive_messages (GSocket
*socket
,
5061 GInputMessage
*messages
,
5064 GCancellable
*cancellable
,
5067 if (!check_socket (socket
, error
) ||
5068 !check_timeout (socket
, error
))
5071 return g_socket_receive_messages_with_timeout (socket
, messages
, num_messages
,
5073 socket
->priv
->blocking
? -1 : 0,
5074 cancellable
, error
);
5078 g_socket_receive_messages_with_timeout (GSocket
*socket
,
5079 GInputMessage
*messages
,
5083 GCancellable
*cancellable
,
5088 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
5089 g_return_val_if_fail (num_messages
== 0 || messages
!= NULL
, -1);
5090 g_return_val_if_fail (cancellable
== NULL
||
5091 G_IS_CANCELLABLE (cancellable
), -1);
5092 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, -1);
5094 start_time
= g_get_monotonic_time ();
5096 if (!check_socket (socket
, error
))
5099 if (!check_timeout (socket
, error
))
5102 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
5105 if (num_messages
== 0)
5108 #if !defined (G_OS_WIN32) && defined (HAVE_RECVMMSG)
5110 struct mmsghdr
*msgvec
;
5111 guint i
, num_received
;
5114 #define MAX_NUM_MESSAGES UIO_MAXIOV
5116 #define MAX_NUM_MESSAGES 1024
5119 if (num_messages
> MAX_NUM_MESSAGES
)
5120 num_messages
= MAX_NUM_MESSAGES
;
5122 msgvec
= g_newa (struct mmsghdr
, num_messages
);
5124 for (i
= 0; i
< num_messages
; ++i
)
5126 GInputMessage
*msg
= &messages
[i
];
5127 struct msghdr
*msg_hdr
= &msgvec
[i
].msg_hdr
;
5129 input_message_to_msghdr (msg
, msg_hdr
);
5130 msgvec
[i
].msg_len
= 0;
5133 /* We always set the close-on-exec flag so we don't leak file
5134 * descriptors into child processes. Note that gunixfdmessage.c
5135 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5137 #ifdef MSG_CMSG_CLOEXEC
5138 flags
|= MSG_CMSG_CLOEXEC
;
5141 for (num_received
= 0; num_received
< num_messages
;)
5145 /* We operate in non-blocking mode and handle the timeout ourselves. */
5146 ret
= recvmmsg (socket
->priv
->fd
,
5147 msgvec
+ num_received
,
5148 num_messages
- num_received
,
5149 flags
| G_SOCKET_DEFAULT_SEND_FLAGS
, NULL
);
5150 #ifdef MSG_CMSG_CLOEXEC
5151 if (ret
< 0 && get_socket_errno () == EINVAL
)
5153 /* We must be running on an old kernel. Call without the flag. */
5154 flags
&= ~(MSG_CMSG_CLOEXEC
);
5155 ret
= recvmmsg (socket
->priv
->fd
,
5156 msgvec
+ num_received
,
5157 num_messages
- num_received
,
5158 flags
| G_SOCKET_DEFAULT_SEND_FLAGS
, NULL
);
5164 int errsv
= get_socket_errno ();
5170 (errsv
== EWOULDBLOCK
||
5173 if (!block_on_timeout (socket
, G_IO_IN
, timeout
, start_time
,
5174 cancellable
, error
))
5176 if (num_received
> 0)
5178 g_clear_error (error
);
5188 /* If any messages were successfully received, do not error. */
5189 if (num_received
> 0)
5192 socket_set_error_lazy (error
, errsv
,
5193 _("Error receiving message: %s"));
5203 num_received
+= ret
;
5206 for (i
= 0; i
< num_received
; ++i
)
5208 input_message_from_msghdr (&msgvec
[i
].msg_hdr
, &messages
[i
], socket
);
5209 messages
[i
].bytes_received
= msgvec
[i
].msg_len
;
5212 return num_received
;
5217 gint64 wait_timeout
;
5219 wait_timeout
= timeout
;
5221 for (i
= 0; i
< num_messages
; i
++)
5223 GInputMessage
*msg
= &messages
[i
];
5225 GError
*msg_error
= NULL
;
5227 msg
->flags
= flags
; /* in-out parameter */
5229 len
= g_socket_receive_message_with_timeout (socket
,
5233 msg
->control_messages
,
5234 (gint
*) msg
->num_control_messages
,
5240 /* check if we've timed out or how much time to wait at most */
5243 gint64 elapsed
= g_get_monotonic_time () - start_time
;
5244 wait_timeout
= MAX (timeout
- elapsed
, 1);
5248 msg
->bytes_received
= len
;
5251 (g_error_matches (msg_error
, G_IO_ERROR
, G_IO_ERROR_WOULD_BLOCK
) ||
5252 g_error_matches (msg_error
, G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
)))
5254 g_clear_error (&msg_error
);
5258 if (msg_error
!= NULL
)
5260 g_propagate_error (error
, msg_error
);
5274 * g_socket_receive_message:
5275 * @socket: a #GSocket
5276 * @address: (out) (optional): a pointer to a #GSocketAddress
5278 * @vectors: (array length=num_vectors): an array of #GInputVector structs
5279 * @num_vectors: the number of elements in @vectors, or -1
5280 * @messages: (array length=num_messages) (out) (optional) (nullable): a pointer
5281 * which may be filled with an array of #GSocketControlMessages, or %NULL
5282 * @num_messages: (out): a pointer which will be filled with the number of
5283 * elements in @messages, or %NULL
5284 * @flags: (inout): a pointer to an int containing #GSocketMsgFlags flags
5285 * @cancellable: a %GCancellable or %NULL
5286 * @error: a #GError pointer, or %NULL
5288 * Receive data from a socket. For receiving multiple messages, see
5289 * g_socket_receive_messages(); for easier use, see
5290 * g_socket_receive() and g_socket_receive_from().
5292 * If @address is non-%NULL then @address will be set equal to the
5293 * source address of the received packet.
5294 * @address is owned by the caller.
5296 * @vector must point to an array of #GInputVector structs and
5297 * @num_vectors must be the length of this array. These structs
5298 * describe the buffers that received data will be scattered into.
5299 * If @num_vectors is -1, then @vectors is assumed to be terminated
5300 * by a #GInputVector with a %NULL buffer pointer.
5302 * As a special case, if @num_vectors is 0 (in which case, @vectors
5303 * may of course be %NULL), then a single byte is received and
5304 * discarded. This is to facilitate the common practice of sending a
5305 * single '\0' byte for the purposes of transferring ancillary data.
5307 * @messages, if non-%NULL, will be set to point to a newly-allocated
5308 * array of #GSocketControlMessage instances or %NULL if no such
5309 * messages was received. These correspond to the control messages
5310 * received from the kernel, one #GSocketControlMessage per message
5311 * from the kernel. This array is %NULL-terminated and must be freed
5312 * by the caller using g_free() after calling g_object_unref() on each
5313 * element. If @messages is %NULL, any control messages received will
5316 * @num_messages, if non-%NULL, will be set to the number of control
5317 * messages received.
5319 * If both @messages and @num_messages are non-%NULL, then
5320 * @num_messages gives the number of #GSocketControlMessage instances
5321 * in @messages (ie: not including the %NULL terminator).
5323 * @flags is an in/out parameter. The commonly available arguments
5324 * for this are available in the #GSocketMsgFlags enum, but the
5325 * values there are the same as the system values, and the flags
5326 * are passed in as-is, so you can pass in system-specific flags too
5327 * (and g_socket_receive_message() may pass system-specific flags out).
5328 * Flags passed in to the parameter affect the receive operation; flags returned
5329 * out of it are relevant to the specific returned message.
5331 * As with g_socket_receive(), data may be discarded if @socket is
5332 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
5333 * provide enough buffer space to read a complete message. You can pass
5334 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
5335 * removing it from the receive queue, but there is no portable way to find
5336 * out the length of the message other than by reading it into a
5337 * sufficiently-large buffer.
5339 * If the socket is in blocking mode the call will block until there
5340 * is some data to receive, the connection is closed, or there is an
5341 * error. If there is no data available and the socket is in
5342 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
5343 * returned. To be notified when data is available, wait for the
5344 * %G_IO_IN condition.
5346 * On error -1 is returned and @error is set accordingly.
5348 * Returns: Number of bytes read, or 0 if the connection was closed by
5349 * the peer, or -1 on error
5354 g_socket_receive_message (GSocket
*socket
,
5355 GSocketAddress
**address
,
5356 GInputVector
*vectors
,
5358 GSocketControlMessage
***messages
,
5361 GCancellable
*cancellable
,
5364 return g_socket_receive_message_with_timeout (socket
, address
, vectors
,
5365 num_vectors
, messages
,
5366 num_messages
, flags
,
5367 socket
->priv
->blocking
? -1 : 0,
5368 cancellable
, error
);
5372 * g_socket_get_credentials:
5373 * @socket: a #GSocket.
5374 * @error: #GError for error reporting, or %NULL to ignore.
5376 * Returns the credentials of the foreign process connected to this
5377 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
5380 * If this operation isn't supported on the OS, the method fails with
5381 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
5382 * by reading the %SO_PEERCRED option on the underlying socket.
5384 * Other ways to obtain credentials from a foreign peer includes the
5385 * #GUnixCredentialsMessage type and
5386 * g_unix_connection_send_credentials() /
5387 * g_unix_connection_receive_credentials() functions.
5389 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
5390 * that must be freed with g_object_unref().
5395 g_socket_get_credentials (GSocket
*socket
,
5400 g_return_val_if_fail (G_IS_SOCKET (socket
), NULL
);
5401 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
5405 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
5409 guint8 native_creds_buf
[G_CREDENTIALS_NATIVE_SIZE
];
5410 socklen_t optlen
= sizeof (native_creds_buf
);
5412 if (getsockopt (socket
->priv
->fd
,
5418 ret
= g_credentials_new ();
5419 g_credentials_set_native (ret
,
5420 G_CREDENTIALS_NATIVE_TYPE
,
5424 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
5426 struct unpcbid cred
;
5427 socklen_t optlen
= sizeof (cred
);
5429 if (getsockopt (socket
->priv
->fd
,
5435 ret
= g_credentials_new ();
5436 g_credentials_set_native (ret
,
5437 G_CREDENTIALS_NATIVE_TYPE
,
5441 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
5443 ucred_t
*ucred
= NULL
;
5445 if (getpeerucred (socket
->priv
->fd
, &ucred
) == 0)
5447 ret
= g_credentials_new ();
5448 g_credentials_set_native (ret
,
5449 G_CREDENTIALS_TYPE_SOLARIS_UCRED
,
5455 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
5460 int errsv
= get_socket_errno ();
5464 socket_io_error_from_errno (errsv
),
5465 _("Unable to read socket credentials: %s"),
5466 socket_strerror (errsv
));
5471 g_set_error_literal (error
,
5473 G_IO_ERROR_NOT_SUPPORTED
,
5474 _("g_socket_get_credentials not implemented for this OS"));
5481 * g_socket_get_option:
5482 * @socket: a #GSocket
5483 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5484 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5485 * @value: (out): return location for the option value
5486 * @error: #GError for error reporting, or %NULL to ignore.
5488 * Gets the value of an integer-valued option on @socket, as with
5489 * getsockopt(). (If you need to fetch a non-integer-valued option,
5490 * you will need to call getsockopt() directly.)
5492 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5493 * header pulls in system headers that will define most of the
5494 * standard/portable socket options. For unusual socket protocols or
5495 * platform-dependent options, you may need to include additional
5498 * Note that even for socket options that are a single byte in size,
5499 * @value is still a pointer to a #gint variable, not a #guchar;
5500 * g_socket_get_option() will handle the conversion internally.
5502 * Returns: success or failure. On failure, @error will be set, and
5503 * the system error value (`errno` or WSAGetLastError()) will still
5504 * be set to the result of the getsockopt() call.
5509 g_socket_get_option (GSocket
*socket
,
5517 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
5520 size
= sizeof (gint
);
5521 if (getsockopt (socket
->priv
->fd
, level
, optname
, value
, &size
) != 0)
5523 int errsv
= get_socket_errno ();
5525 g_set_error_literal (error
,
5527 socket_io_error_from_errno (errsv
),
5528 socket_strerror (errsv
));
5530 /* Reset errno in case the caller wants to look at it */
5536 #if G_BYTE_ORDER == G_BIG_ENDIAN
5537 /* If the returned value is smaller than an int then we need to
5538 * slide it over into the low-order bytes of *value.
5540 if (size
!= sizeof (gint
))
5541 *value
= *value
>> (8 * (sizeof (gint
) - size
));
5548 * g_socket_set_option:
5549 * @socket: a #GSocket
5550 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5551 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5552 * @value: the value to set the option to
5553 * @error: #GError for error reporting, or %NULL to ignore.
5555 * Sets the value of an integer-valued option on @socket, as with
5556 * setsockopt(). (If you need to set a non-integer-valued option,
5557 * you will need to call setsockopt() directly.)
5559 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5560 * header pulls in system headers that will define most of the
5561 * standard/portable socket options. For unusual socket protocols or
5562 * platform-dependent options, you may need to include additional
5565 * Returns: success or failure. On failure, @error will be set, and
5566 * the system error value (`errno` or WSAGetLastError()) will still
5567 * be set to the result of the setsockopt() call.
5572 g_socket_set_option (GSocket
*socket
,
5580 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
5582 if (setsockopt (socket
->priv
->fd
, level
, optname
, &value
, sizeof (gint
)) == 0)
5585 #if !defined (__linux__) && !defined (G_OS_WIN32)
5586 /* Linux and Windows let you set a single-byte value from an int,
5587 * but most other platforms don't.
5589 if (errno
== EINVAL
&& value
>= SCHAR_MIN
&& value
<= CHAR_MAX
)
5591 #if G_BYTE_ORDER == G_BIG_ENDIAN
5592 value
= value
<< (8 * (sizeof (gint
) - 1));
5594 if (setsockopt (socket
->priv
->fd
, level
, optname
, &value
, 1) == 0)
5599 errsv
= get_socket_errno ();
5601 g_set_error_literal (error
,
5603 socket_io_error_from_errno (errsv
),
5604 socket_strerror (errsv
));