1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2008 Christian Kellner, Samuel Cormier-Iijima
4 * Copyright © 2009 Codethink Limited
5 * Copyright © 2009 Red Hat, Inc
6 * Copyright © 2015 Collabora, Ltd.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General
19 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 * Authors: Christian Kellner <gicmo@gnome.org>
22 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
23 * Ryan Lortie <desrt@desrt.ca>
24 * Alexander Larsson <alexl@redhat.com>
25 * Philip Withnall <philip.withnall@collabora.co.uk>
33 #include "glib-unix.h"
44 # include <sys/ioctl.h>
47 #ifdef HAVE_SYS_FILIO_H
48 # include <sys/filio.h>
55 #include "gcancellable.h"
56 #include "gdatagrambased.h"
57 #include "gioenumtypes.h"
58 #include "ginetaddress.h"
59 #include "ginitable.h"
63 #include "gnetworkingprivate.h"
64 #include "gsocketaddress.h"
65 #include "gsocketcontrolmessage.h"
66 #include "gcredentials.h"
67 #include "gcredentialsprivate.h"
71 /* For Windows XP runtime compatibility, but use the system's if_nametoindex() if available */
72 #include "gwin32networking.h"
77 * @short_description: Low-level socket object
79 * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
81 * A #GSocket is a low-level networking primitive. It is a more or less
82 * direct mapping of the BSD socket API in a portable GObject based API.
83 * It supports both the UNIX socket implementations and winsock2 on Windows.
85 * #GSocket is the platform independent base upon which the higher level
86 * network primitives are based. Applications are not typically meant to
87 * use it directly, but rather through classes like #GSocketClient,
88 * #GSocketService and #GSocketConnection. However there may be cases where
89 * direct use of #GSocket is useful.
91 * #GSocket implements the #GInitable interface, so if it is manually constructed
92 * by e.g. g_object_new() you must call g_initable_init() and check the
93 * results before using the object. This is done automatically in
94 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
97 * Sockets operate in two general modes, blocking or non-blocking. When
98 * in blocking mode all operations (which don’t take an explicit blocking
99 * parameter) block until the requested operation
100 * is finished or there is an error. In non-blocking mode all calls that
101 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
102 * To know when a call would successfully run you can call g_socket_condition_check(),
103 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
104 * attach it to a #GMainContext to get callbacks when I/O is possible.
105 * Note that all sockets are always set to non blocking mode in the system, and
106 * blocking mode is emulated in GSocket.
108 * When working in non-blocking mode applications should always be able to
109 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
110 * function said that I/O was possible. This can easily happen in case
111 * of a race condition in the application, but it can also happen for other
112 * reasons. For instance, on Windows a socket is always seen as writable
113 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
115 * #GSockets can be either connection oriented or datagram based.
116 * For connection oriented types you must first establish a connection by
117 * either connecting to an address or accepting a connection from another
118 * address. For connectionless socket types the target/source address is
119 * specified or received in each I/O operation.
121 * All socket file descriptors are set to be close-on-exec.
123 * Note that creating a #GSocket causes the signal %SIGPIPE to be
124 * ignored for the remainder of the program. If you are writing a
125 * command-line utility that uses #GSocket, you may need to take into
126 * account the fact that your program will not automatically be killed
127 * if it tries to write to %stdout after it has been closed.
129 * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
130 * a #GSocket concurrently from multiple threads, you must implement your own
136 static void g_socket_initable_iface_init (GInitableIface
*iface
);
137 static gboolean
g_socket_initable_init (GInitable
*initable
,
138 GCancellable
*cancellable
,
141 static void g_socket_datagram_based_iface_init (GDatagramBasedInterface
*iface
);
142 static gint
g_socket_datagram_based_receive_messages (GDatagramBased
*self
,
143 GInputMessage
*messages
,
147 GCancellable
*cancellable
,
149 static gint
g_socket_datagram_based_send_messages (GDatagramBased
*self
,
150 GOutputMessage
*messages
,
154 GCancellable
*cancellable
,
156 static GSource
*g_socket_datagram_based_create_source (GDatagramBased
*self
,
157 GIOCondition condition
,
158 GCancellable
*cancellable
);
159 static GIOCondition
g_socket_datagram_based_condition_check (GDatagramBased
*datagram_based
,
160 GIOCondition condition
);
161 static gboolean
g_socket_datagram_based_condition_wait (GDatagramBased
*datagram_based
,
162 GIOCondition condition
,
164 GCancellable
*cancellable
,
167 static GSocketAddress
*
168 cache_recv_address (GSocket
*socket
, struct sockaddr
*native
, int native_len
);
171 g_socket_receive_message_with_timeout (GSocket
*socket
,
172 GSocketAddress
**address
,
173 GInputVector
*vectors
,
175 GSocketControlMessage
***messages
,
179 GCancellable
*cancellable
,
182 g_socket_receive_messages_with_timeout (GSocket
*socket
,
183 GInputMessage
*messages
,
187 GCancellable
*cancellable
,
190 g_socket_send_message_with_timeout (GSocket
*socket
,
191 GSocketAddress
*address
,
192 GOutputVector
*vectors
,
194 GSocketControlMessage
**messages
,
198 GCancellable
*cancellable
,
201 g_socket_send_messages_with_timeout (GSocket
*socket
,
202 GOutputMessage
*messages
,
206 GCancellable
*cancellable
,
224 PROP_MULTICAST_LOOPBACK
,
228 /* Size of the receiver cache for g_socket_receive_from() */
229 #define RECV_ADDR_CACHE_SIZE 8
231 struct _GSocketPrivate
233 GSocketFamily family
;
235 GSocketProtocol protocol
;
239 GError
*construct_error
;
240 GSocketAddress
*remote_address
;
245 guint connected_read
: 1;
246 guint connected_write
: 1;
249 guint connect_pending
: 1;
253 DWORD waiting_result
;
257 GList
*requested_conditions
; /* list of requested GIOCondition * */
258 GMutex win32_source_lock
;
259 GCond win32_source_cond
;
263 GSocketAddress
*addr
;
264 struct sockaddr
*native
;
267 } recv_addr_cache
[RECV_ADDR_CACHE_SIZE
];
270 G_DEFINE_TYPE_WITH_CODE (GSocket
, g_socket
, G_TYPE_OBJECT
,
271 G_ADD_PRIVATE (GSocket
)
272 g_networking_init ();
273 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE
,
274 g_socket_initable_iface_init
);
275 G_IMPLEMENT_INTERFACE (G_TYPE_DATAGRAM_BASED
,
276 g_socket_datagram_based_iface_init
));
279 get_socket_errno (void)
284 return WSAGetLastError ();
289 socket_io_error_from_errno (int err
)
292 return g_io_error_from_win32_error (err
);
294 return g_io_error_from_errno (err
);
299 socket_strerror (int err
)
302 return g_strerror (err
);
307 msg
= g_win32_error_message (err
);
309 msg_ret
= g_intern_string (msg
);
316 /* Wrapper around g_set_error() to avoid doing excess work */
317 #define socket_set_error_lazy(err, errsv, fmt) \
319 GError **__err = (err); \
320 int __errsv = (errsv); \
324 int __code = socket_io_error_from_errno (__errsv); \
325 const char *__strerr = socket_strerror (__errsv); \
327 if (__code == G_IO_ERROR_WOULD_BLOCK) \
328 g_set_error_literal (__err, G_IO_ERROR, __code, __strerr); \
330 g_set_error (__err, G_IO_ERROR, __code, fmt, __strerr); \
335 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
337 _win32_unset_event_mask (GSocket
*socket
, int mask
)
339 g_mutex_lock (&socket
->priv
->win32_source_lock
);
340 socket
->priv
->current_events
&= ~mask
;
341 socket
->priv
->current_errors
&= ~mask
;
342 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
345 #define win32_unset_event_mask(_socket, _mask)
348 /* Windows has broken prototypes... */
350 #define getsockopt(sockfd, level, optname, optval, optlen) \
351 getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
352 #define setsockopt(sockfd, level, optname, optval, optlen) \
353 setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
354 #define getsockname(sockfd, addr, addrlen) \
355 getsockname (sockfd, addr, (int *)addrlen)
356 #define getpeername(sockfd, addr, addrlen) \
357 getpeername (sockfd, addr, (int *)addrlen)
358 #define recv(sockfd, buf, len, flags) \
359 recv (sockfd, (gpointer)buf, len, flags)
363 check_socket (GSocket
*socket
,
366 if (!socket
->priv
->inited
)
368 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_NOT_INITIALIZED
,
369 _("Invalid socket, not initialized"));
373 if (socket
->priv
->construct_error
)
375 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_INITIALIZED
,
376 _("Invalid socket, initialization failed due to: %s"),
377 socket
->priv
->construct_error
->message
);
381 if (socket
->priv
->closed
)
383 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_CLOSED
,
384 _("Socket is already closed"));
392 check_timeout (GSocket
*socket
,
395 if (socket
->priv
->timed_out
)
397 socket
->priv
->timed_out
= FALSE
;
398 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
,
399 _("Socket I/O timed out"));
407 g_socket_details_from_fd (GSocket
*socket
)
409 struct sockaddr_storage address
;
415 fd
= socket
->priv
->fd
;
416 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_TYPE
, &value
, NULL
))
418 errsv
= get_socket_errno ();
425 socket
->priv
->type
= G_SOCKET_TYPE_STREAM
;
429 socket
->priv
->type
= G_SOCKET_TYPE_DATAGRAM
;
433 socket
->priv
->type
= G_SOCKET_TYPE_SEQPACKET
;
437 socket
->priv
->type
= G_SOCKET_TYPE_INVALID
;
441 addrlen
= sizeof address
;
442 if (getsockname (fd
, (struct sockaddr
*) &address
, &addrlen
) != 0)
444 errsv
= get_socket_errno ();
450 g_assert (G_STRUCT_OFFSET (struct sockaddr
, sa_family
) +
451 sizeof address
.ss_family
<= addrlen
);
452 family
= address
.ss_family
;
456 /* On Solaris, this happens if the socket is not yet connected.
457 * But we can use SO_DOMAIN as a workaround there.
460 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_DOMAIN
, &family
, NULL
))
462 errsv
= get_socket_errno ();
466 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
474 case G_SOCKET_FAMILY_IPV4
:
475 case G_SOCKET_FAMILY_IPV6
:
476 socket
->priv
->family
= address
.ss_family
;
477 switch (socket
->priv
->type
)
479 case G_SOCKET_TYPE_STREAM
:
480 socket
->priv
->protocol
= G_SOCKET_PROTOCOL_TCP
;
483 case G_SOCKET_TYPE_DATAGRAM
:
484 socket
->priv
->protocol
= G_SOCKET_PROTOCOL_UDP
;
487 case G_SOCKET_TYPE_SEQPACKET
:
488 socket
->priv
->protocol
= G_SOCKET_PROTOCOL_SCTP
;
496 case G_SOCKET_FAMILY_UNIX
:
497 socket
->priv
->family
= G_SOCKET_FAMILY_UNIX
;
498 socket
->priv
->protocol
= G_SOCKET_PROTOCOL_DEFAULT
;
502 socket
->priv
->family
= G_SOCKET_FAMILY_INVALID
;
506 if (socket
->priv
->family
!= G_SOCKET_FAMILY_INVALID
)
508 addrlen
= sizeof address
;
509 if (getpeername (fd
, (struct sockaddr
*) &address
, &addrlen
) >= 0)
511 socket
->priv
->connected_read
= TRUE
;
512 socket
->priv
->connected_write
= TRUE
;
516 if (g_socket_get_option (socket
, SOL_SOCKET
, SO_KEEPALIVE
, &value
, NULL
))
518 socket
->priv
->keepalive
= !!value
;
522 /* Can't read, maybe not supported, assume FALSE */
523 socket
->priv
->keepalive
= FALSE
;
529 g_set_error (&socket
->priv
->construct_error
, G_IO_ERROR
,
530 socket_io_error_from_errno (errsv
),
531 _("creating GSocket from fd: %s"),
532 socket_strerror (errsv
));
535 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
537 g_socket (gint domain
,
545 fd
= socket (domain
, type
| SOCK_CLOEXEC
, protocol
);
549 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
550 if (fd
< 0 && (errno
== EINVAL
|| errno
== EPROTOTYPE
))
552 fd
= socket (domain
, type
, protocol
);
556 int errsv
= get_socket_errno ();
558 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
559 _("Unable to create socket: %s"), socket_strerror (errsv
));
568 /* We always want to set close-on-exec to protect users. If you
569 need to so some weird inheritance to exec you can re-enable this
570 using lower level hacks with g_socket_get_fd(). */
571 flags
= fcntl (fd
, F_GETFD
, 0);
573 (flags
& FD_CLOEXEC
) == 0)
576 fcntl (fd
, F_SETFD
, flags
);
585 g_socket_create_socket (GSocketFamily family
,
594 case G_SOCKET_TYPE_STREAM
:
595 native_type
= SOCK_STREAM
;
598 case G_SOCKET_TYPE_DATAGRAM
:
599 native_type
= SOCK_DGRAM
;
602 case G_SOCKET_TYPE_SEQPACKET
:
603 native_type
= SOCK_SEQPACKET
;
607 g_assert_not_reached ();
612 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_INVALID_ARGUMENT
,
613 _("Unable to create socket: %s"), _("Unknown family was specified"));
619 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_INVALID_ARGUMENT
,
620 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
624 return g_socket (family
, native_type
, protocol
, error
);
628 g_socket_constructed (GObject
*object
)
630 GSocket
*socket
= G_SOCKET (object
);
632 if (socket
->priv
->fd
>= 0)
633 /* create socket->priv info from the fd */
634 g_socket_details_from_fd (socket
);
637 /* create the fd from socket->priv info */
638 socket
->priv
->fd
= g_socket_create_socket (socket
->priv
->family
,
640 socket
->priv
->protocol
,
641 &socket
->priv
->construct_error
);
643 if (socket
->priv
->fd
!= -1)
646 GError
*error
= NULL
;
651 /* Always use native nonblocking sockets, as Windows sets sockets to
652 * nonblocking automatically in certain operations. This way we make
653 * things work the same on all platforms.
656 if (!g_unix_set_fd_nonblocking (socket
->priv
->fd
, TRUE
, &error
))
658 g_warning ("Error setting socket nonblocking: %s", error
->message
);
659 g_clear_error (&error
);
664 if (ioctlsocket (socket
->priv
->fd
, FIONBIO
, &arg
) == SOCKET_ERROR
)
666 int errsv
= get_socket_errno ();
667 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv
));
672 /* See note about SIGPIPE below. */
673 g_socket_set_option (socket
, SOL_SOCKET
, SO_NOSIGPIPE
, TRUE
, NULL
);
679 g_socket_get_property (GObject
*object
,
684 GSocket
*socket
= G_SOCKET (object
);
685 GSocketAddress
*address
;
690 g_value_set_enum (value
, socket
->priv
->family
);
694 g_value_set_enum (value
, socket
->priv
->type
);
698 g_value_set_enum (value
, socket
->priv
->protocol
);
702 g_value_set_int (value
, socket
->priv
->fd
);
706 g_value_set_boolean (value
, socket
->priv
->blocking
);
709 case PROP_LISTEN_BACKLOG
:
710 g_value_set_int (value
, socket
->priv
->listen_backlog
);
714 g_value_set_boolean (value
, socket
->priv
->keepalive
);
717 case PROP_LOCAL_ADDRESS
:
718 address
= g_socket_get_local_address (socket
, NULL
);
719 g_value_take_object (value
, address
);
722 case PROP_REMOTE_ADDRESS
:
723 address
= g_socket_get_remote_address (socket
, NULL
);
724 g_value_take_object (value
, address
);
728 g_value_set_uint (value
, socket
->priv
->timeout
);
732 g_value_set_uint (value
, g_socket_get_ttl (socket
));
736 g_value_set_boolean (value
, g_socket_get_broadcast (socket
));
739 case PROP_MULTICAST_LOOPBACK
:
740 g_value_set_boolean (value
, g_socket_get_multicast_loopback (socket
));
743 case PROP_MULTICAST_TTL
:
744 g_value_set_uint (value
, g_socket_get_multicast_ttl (socket
));
748 G_OBJECT_WARN_INVALID_PROPERTY_ID (object
, prop_id
, pspec
);
753 g_socket_set_property (GObject
*object
,
758 GSocket
*socket
= G_SOCKET (object
);
763 socket
->priv
->family
= g_value_get_enum (value
);
767 socket
->priv
->type
= g_value_get_enum (value
);
771 socket
->priv
->protocol
= g_value_get_enum (value
);
775 socket
->priv
->fd
= g_value_get_int (value
);
779 g_socket_set_blocking (socket
, g_value_get_boolean (value
));
782 case PROP_LISTEN_BACKLOG
:
783 g_socket_set_listen_backlog (socket
, g_value_get_int (value
));
787 g_socket_set_keepalive (socket
, g_value_get_boolean (value
));
791 g_socket_set_timeout (socket
, g_value_get_uint (value
));
795 g_socket_set_ttl (socket
, g_value_get_uint (value
));
799 g_socket_set_broadcast (socket
, g_value_get_boolean (value
));
802 case PROP_MULTICAST_LOOPBACK
:
803 g_socket_set_multicast_loopback (socket
, g_value_get_boolean (value
));
806 case PROP_MULTICAST_TTL
:
807 g_socket_set_multicast_ttl (socket
, g_value_get_uint (value
));
811 G_OBJECT_WARN_INVALID_PROPERTY_ID (object
, prop_id
, pspec
);
816 g_socket_finalize (GObject
*object
)
818 GSocket
*socket
= G_SOCKET (object
);
821 g_clear_error (&socket
->priv
->construct_error
);
823 if (socket
->priv
->fd
!= -1 &&
824 !socket
->priv
->closed
)
825 g_socket_close (socket
, NULL
);
827 if (socket
->priv
->remote_address
)
828 g_object_unref (socket
->priv
->remote_address
);
831 if (socket
->priv
->event
!= WSA_INVALID_EVENT
)
833 WSACloseEvent (socket
->priv
->event
);
834 socket
->priv
->event
= WSA_INVALID_EVENT
;
837 g_assert (socket
->priv
->requested_conditions
== NULL
);
838 g_mutex_clear (&socket
->priv
->win32_source_lock
);
839 g_cond_clear (&socket
->priv
->win32_source_cond
);
842 for (i
= 0; i
< RECV_ADDR_CACHE_SIZE
; i
++)
844 if (socket
->priv
->recv_addr_cache
[i
].addr
)
846 g_object_unref (socket
->priv
->recv_addr_cache
[i
].addr
);
847 g_free (socket
->priv
->recv_addr_cache
[i
].native
);
851 if (G_OBJECT_CLASS (g_socket_parent_class
)->finalize
)
852 (*G_OBJECT_CLASS (g_socket_parent_class
)->finalize
) (object
);
856 g_socket_class_init (GSocketClass
*klass
)
858 GObjectClass
*gobject_class G_GNUC_UNUSED
= G_OBJECT_CLASS (klass
);
861 /* There is no portable, thread-safe way to avoid having the process
862 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
863 * forced to simply ignore the signal process-wide.
865 * Even if we ignore it though, gdb will still stop if the app
866 * receives a SIGPIPE, which can be confusing and annoying. So when
867 * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
868 * prevent the signal from occurring at all.
870 signal (SIGPIPE
, SIG_IGN
);
873 gobject_class
->finalize
= g_socket_finalize
;
874 gobject_class
->constructed
= g_socket_constructed
;
875 gobject_class
->set_property
= g_socket_set_property
;
876 gobject_class
->get_property
= g_socket_get_property
;
878 g_object_class_install_property (gobject_class
, PROP_FAMILY
,
879 g_param_spec_enum ("family",
881 P_("The sockets address family"),
882 G_TYPE_SOCKET_FAMILY
,
883 G_SOCKET_FAMILY_INVALID
,
884 G_PARAM_CONSTRUCT_ONLY
|
886 G_PARAM_STATIC_STRINGS
));
888 g_object_class_install_property (gobject_class
, PROP_TYPE
,
889 g_param_spec_enum ("type",
891 P_("The sockets type"),
893 G_SOCKET_TYPE_STREAM
,
894 G_PARAM_CONSTRUCT_ONLY
|
896 G_PARAM_STATIC_STRINGS
));
898 g_object_class_install_property (gobject_class
, PROP_PROTOCOL
,
899 g_param_spec_enum ("protocol",
900 P_("Socket protocol"),
901 P_("The id of the protocol to use, or -1 for unknown"),
902 G_TYPE_SOCKET_PROTOCOL
,
903 G_SOCKET_PROTOCOL_UNKNOWN
,
904 G_PARAM_CONSTRUCT_ONLY
|
906 G_PARAM_STATIC_STRINGS
));
908 g_object_class_install_property (gobject_class
, PROP_FD
,
909 g_param_spec_int ("fd",
910 P_("File descriptor"),
911 P_("The sockets file descriptor"),
915 G_PARAM_CONSTRUCT_ONLY
|
917 G_PARAM_STATIC_STRINGS
));
919 g_object_class_install_property (gobject_class
, PROP_BLOCKING
,
920 g_param_spec_boolean ("blocking",
922 P_("Whether or not I/O on this socket is blocking"),
925 G_PARAM_STATIC_STRINGS
));
927 g_object_class_install_property (gobject_class
, PROP_LISTEN_BACKLOG
,
928 g_param_spec_int ("listen-backlog",
929 P_("Listen backlog"),
930 P_("Outstanding connections in the listen queue"),
935 G_PARAM_STATIC_STRINGS
));
937 g_object_class_install_property (gobject_class
, PROP_KEEPALIVE
,
938 g_param_spec_boolean ("keepalive",
939 P_("Keep connection alive"),
940 P_("Keep connection alive by sending periodic pings"),
943 G_PARAM_STATIC_STRINGS
));
945 g_object_class_install_property (gobject_class
, PROP_LOCAL_ADDRESS
,
946 g_param_spec_object ("local-address",
948 P_("The local address the socket is bound to"),
949 G_TYPE_SOCKET_ADDRESS
,
951 G_PARAM_STATIC_STRINGS
));
953 g_object_class_install_property (gobject_class
, PROP_REMOTE_ADDRESS
,
954 g_param_spec_object ("remote-address",
955 P_("Remote address"),
956 P_("The remote address the socket is connected to"),
957 G_TYPE_SOCKET_ADDRESS
,
959 G_PARAM_STATIC_STRINGS
));
964 * The timeout in seconds on socket I/O
968 g_object_class_install_property (gobject_class
, PROP_TIMEOUT
,
969 g_param_spec_uint ("timeout",
971 P_("The timeout in seconds on socket I/O"),
976 G_PARAM_STATIC_STRINGS
));
981 * Whether the socket should allow sending to broadcast addresses.
985 g_object_class_install_property (gobject_class
, PROP_BROADCAST
,
986 g_param_spec_boolean ("broadcast",
988 P_("Whether to allow sending to broadcast addresses"),
991 G_PARAM_STATIC_STRINGS
));
996 * Time-to-live for outgoing unicast packets
1000 g_object_class_install_property (gobject_class
, PROP_TTL
,
1001 g_param_spec_uint ("ttl",
1003 P_("Time-to-live of outgoing unicast packets"),
1006 G_PARAM_STATIC_STRINGS
));
1009 * GSocket:multicast-loopback:
1011 * Whether outgoing multicast packets loop back to the local host.
1015 g_object_class_install_property (gobject_class
, PROP_MULTICAST_LOOPBACK
,
1016 g_param_spec_boolean ("multicast-loopback",
1017 P_("Multicast loopback"),
1018 P_("Whether outgoing multicast packets loop back to the local host"),
1021 G_PARAM_STATIC_STRINGS
));
1024 * GSocket:multicast-ttl:
1026 * Time-to-live out outgoing multicast packets
1030 g_object_class_install_property (gobject_class
, PROP_MULTICAST_TTL
,
1031 g_param_spec_uint ("multicast-ttl",
1032 P_("Multicast TTL"),
1033 P_("Time-to-live of outgoing multicast packets"),
1036 G_PARAM_STATIC_STRINGS
));
1040 g_socket_initable_iface_init (GInitableIface
*iface
)
1042 iface
->init
= g_socket_initable_init
;
1046 g_socket_datagram_based_iface_init (GDatagramBasedInterface
*iface
)
1048 iface
->receive_messages
= g_socket_datagram_based_receive_messages
;
1049 iface
->send_messages
= g_socket_datagram_based_send_messages
;
1050 iface
->create_source
= g_socket_datagram_based_create_source
;
1051 iface
->condition_check
= g_socket_datagram_based_condition_check
;
1052 iface
->condition_wait
= g_socket_datagram_based_condition_wait
;
1056 g_socket_init (GSocket
*socket
)
1058 socket
->priv
= g_socket_get_instance_private (socket
);
1060 socket
->priv
->fd
= -1;
1061 socket
->priv
->blocking
= TRUE
;
1062 socket
->priv
->listen_backlog
= 10;
1063 socket
->priv
->construct_error
= NULL
;
1065 socket
->priv
->event
= WSA_INVALID_EVENT
;
1066 g_mutex_init (&socket
->priv
->win32_source_lock
);
1067 g_cond_init (&socket
->priv
->win32_source_cond
);
1072 g_socket_initable_init (GInitable
*initable
,
1073 GCancellable
*cancellable
,
1078 g_return_val_if_fail (G_IS_SOCKET (initable
), FALSE
);
1080 socket
= G_SOCKET (initable
);
1082 if (cancellable
!= NULL
)
1084 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
1085 _("Cancellable initialization not supported"));
1089 socket
->priv
->inited
= TRUE
;
1091 if (socket
->priv
->construct_error
)
1094 *error
= g_error_copy (socket
->priv
->construct_error
);
1103 check_datagram_based (GDatagramBased
*self
,
1106 switch (g_socket_get_socket_type (G_SOCKET (self
)))
1108 case G_SOCKET_TYPE_INVALID
:
1109 case G_SOCKET_TYPE_STREAM
:
1110 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
1111 _("Cannot use datagram operations on a non-datagram "
1114 case G_SOCKET_TYPE_DATAGRAM
:
1115 case G_SOCKET_TYPE_SEQPACKET
:
1120 /* Due to us sharing #GSocketSource with the #GSocket implementation, it is
1121 * pretty tricky to split out #GSocket:timeout so that it does not affect
1122 * #GDatagramBased operations (but still affects #GSocket operations). It is
1123 * not worth that effort — just disallow it and require the user to specify
1124 * timeouts on a per-operation basis. */
1125 if (g_socket_get_timeout (G_SOCKET (self
)) != 0)
1127 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
1128 _("Cannot use datagram operations on a socket with a "
1137 g_socket_datagram_based_receive_messages (GDatagramBased
*self
,
1138 GInputMessage
*messages
,
1142 GCancellable
*cancellable
,
1145 if (!check_datagram_based (self
, error
))
1148 return g_socket_receive_messages_with_timeout (G_SOCKET (self
), messages
,
1149 num_messages
, flags
, timeout
,
1150 cancellable
, error
);
1154 g_socket_datagram_based_send_messages (GDatagramBased
*self
,
1155 GOutputMessage
*messages
,
1159 GCancellable
*cancellable
,
1162 if (!check_datagram_based (self
, error
))
1165 return g_socket_send_messages_with_timeout (G_SOCKET (self
), messages
,
1166 num_messages
, flags
, timeout
,
1167 cancellable
, error
);
1171 g_socket_datagram_based_create_source (GDatagramBased
*self
,
1172 GIOCondition condition
,
1173 GCancellable
*cancellable
)
1175 if (!check_datagram_based (self
, NULL
))
1178 return g_socket_create_source (G_SOCKET (self
), condition
, cancellable
);
1182 g_socket_datagram_based_condition_check (GDatagramBased
*datagram_based
,
1183 GIOCondition condition
)
1185 if (!check_datagram_based (datagram_based
, NULL
))
1188 return g_socket_condition_check (G_SOCKET (datagram_based
), condition
);
1192 g_socket_datagram_based_condition_wait (GDatagramBased
*datagram_based
,
1193 GIOCondition condition
,
1195 GCancellable
*cancellable
,
1198 if (!check_datagram_based (datagram_based
, error
))
1201 return g_socket_condition_timed_wait (G_SOCKET (datagram_based
), condition
,
1202 timeout
, cancellable
, error
);
1207 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1208 * @type: the socket type to use.
1209 * @protocol: the id of the protocol to use, or 0 for default.
1210 * @error: #GError for error reporting, or %NULL to ignore.
1212 * Creates a new #GSocket with the defined family, type and protocol.
1213 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1214 * for the family and type is used.
1216 * The @protocol is a family and type specific int that specifies what
1217 * kind of protocol to use. #GSocketProtocol lists several common ones.
1218 * Many families only support one protocol, and use 0 for this, others
1219 * support several and using 0 means to use the default protocol for
1220 * the family and type.
1222 * The protocol id is passed directly to the operating
1223 * system, so you can use protocols not listed in #GSocketProtocol if you
1224 * know the protocol number used for it.
1226 * Returns: a #GSocket or %NULL on error.
1227 * Free the returned object with g_object_unref().
1232 g_socket_new (GSocketFamily family
,
1234 GSocketProtocol protocol
,
1237 return G_SOCKET (g_initable_new (G_TYPE_SOCKET
,
1241 "protocol", protocol
,
1246 * g_socket_new_from_fd:
1247 * @fd: a native socket file descriptor.
1248 * @error: #GError for error reporting, or %NULL to ignore.
1250 * Creates a new #GSocket from a native file descriptor
1251 * or winsock SOCKET handle.
1253 * This reads all the settings from the file descriptor so that
1254 * all properties should work. Note that the file descriptor
1255 * will be set to non-blocking mode, independent on the blocking
1256 * mode of the #GSocket.
1258 * On success, the returned #GSocket takes ownership of @fd. On failure, the
1259 * caller must close @fd themselves.
1261 * Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
1262 * descriptor. Instead, a GError will be set with code %G_IO_ERROR_FAILED
1264 * Returns: a #GSocket or %NULL on error.
1265 * Free the returned object with g_object_unref().
1270 g_socket_new_from_fd (gint fd
,
1273 return G_SOCKET (g_initable_new (G_TYPE_SOCKET
,
1280 * g_socket_set_blocking:
1281 * @socket: a #GSocket.
1282 * @blocking: Whether to use blocking I/O or not.
1284 * Sets the blocking mode of the socket. In blocking mode
1285 * all operations (which don’t take an explicit blocking parameter) block until
1286 * they succeed or there is an error. In
1287 * non-blocking mode all functions return results immediately or
1288 * with a %G_IO_ERROR_WOULD_BLOCK error.
1290 * All sockets are created in blocking mode. However, note that the
1291 * platform level socket is always non-blocking, and blocking mode
1292 * is a GSocket level feature.
1297 g_socket_set_blocking (GSocket
*socket
,
1300 g_return_if_fail (G_IS_SOCKET (socket
));
1302 blocking
= !!blocking
;
1304 if (socket
->priv
->blocking
== blocking
)
1307 socket
->priv
->blocking
= blocking
;
1308 g_object_notify (G_OBJECT (socket
), "blocking");
1312 * g_socket_get_blocking:
1313 * @socket: a #GSocket.
1315 * Gets the blocking mode of the socket. For details on blocking I/O,
1316 * see g_socket_set_blocking().
1318 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1323 g_socket_get_blocking (GSocket
*socket
)
1325 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
1327 return socket
->priv
->blocking
;
1331 * g_socket_set_keepalive:
1332 * @socket: a #GSocket.
1333 * @keepalive: Value for the keepalive flag
1335 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1336 * this flag is set on a socket, the system will attempt to verify that the
1337 * remote socket endpoint is still present if a sufficiently long period of
1338 * time passes with no data being exchanged. If the system is unable to
1339 * verify the presence of the remote endpoint, it will automatically close
1342 * This option is only functional on certain kinds of sockets. (Notably,
1343 * %G_SOCKET_PROTOCOL_TCP sockets.)
1345 * The exact time between pings is system- and protocol-dependent, but will
1346 * normally be at least two hours. Most commonly, you would set this flag
1347 * on a server socket if you want to allow clients to remain idle for long
1348 * periods of time, but also want to ensure that connections are eventually
1349 * garbage-collected if clients crash or become unreachable.
1354 g_socket_set_keepalive (GSocket
*socket
,
1357 GError
*error
= NULL
;
1359 g_return_if_fail (G_IS_SOCKET (socket
));
1361 keepalive
= !!keepalive
;
1362 if (socket
->priv
->keepalive
== keepalive
)
1365 if (!g_socket_set_option (socket
, SOL_SOCKET
, SO_KEEPALIVE
,
1368 g_warning ("error setting keepalive: %s", error
->message
);
1369 g_error_free (error
);
1373 socket
->priv
->keepalive
= keepalive
;
1374 g_object_notify (G_OBJECT (socket
), "keepalive");
1378 * g_socket_get_keepalive:
1379 * @socket: a #GSocket.
1381 * Gets the keepalive mode of the socket. For details on this,
1382 * see g_socket_set_keepalive().
1384 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1389 g_socket_get_keepalive (GSocket
*socket
)
1391 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
1393 return socket
->priv
->keepalive
;
1397 * g_socket_get_listen_backlog:
1398 * @socket: a #GSocket.
1400 * Gets the listen backlog setting of the socket. For details on this,
1401 * see g_socket_set_listen_backlog().
1403 * Returns: the maximum number of pending connections.
1408 g_socket_get_listen_backlog (GSocket
*socket
)
1410 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
1412 return socket
->priv
->listen_backlog
;
1416 * g_socket_set_listen_backlog:
1417 * @socket: a #GSocket.
1418 * @backlog: the maximum number of pending connections.
1420 * Sets the maximum number of outstanding connections allowed
1421 * when listening on this socket. If more clients than this are
1422 * connecting to the socket and the application is not handling them
1423 * on time then the new connections will be refused.
1425 * Note that this must be called before g_socket_listen() and has no
1426 * effect if called after that.
1431 g_socket_set_listen_backlog (GSocket
*socket
,
1434 g_return_if_fail (G_IS_SOCKET (socket
));
1435 g_return_if_fail (!socket
->priv
->listening
);
1437 if (backlog
!= socket
->priv
->listen_backlog
)
1439 socket
->priv
->listen_backlog
= backlog
;
1440 g_object_notify (G_OBJECT (socket
), "listen-backlog");
1445 * g_socket_get_timeout:
1446 * @socket: a #GSocket.
1448 * Gets the timeout setting of the socket. For details on this, see
1449 * g_socket_set_timeout().
1451 * Returns: the timeout in seconds
1456 g_socket_get_timeout (GSocket
*socket
)
1458 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
1460 return socket
->priv
->timeout
;
1464 * g_socket_set_timeout:
1465 * @socket: a #GSocket.
1466 * @timeout: the timeout for @socket, in seconds, or 0 for none
1468 * Sets the time in seconds after which I/O operations on @socket will
1469 * time out if they have not yet completed.
1471 * On a blocking socket, this means that any blocking #GSocket
1472 * operation will time out after @timeout seconds of inactivity,
1473 * returning %G_IO_ERROR_TIMED_OUT.
1475 * On a non-blocking socket, calls to g_socket_condition_wait() will
1476 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1477 * created with g_socket_create_source() will trigger after
1478 * @timeout seconds of inactivity, with the requested condition
1479 * set, at which point calling g_socket_receive(), g_socket_send(),
1480 * g_socket_check_connect_result(), etc, will fail with
1481 * %G_IO_ERROR_TIMED_OUT.
1483 * If @timeout is 0 (the default), operations will never time out
1486 * Note that if an I/O operation is interrupted by a signal, this may
1487 * cause the timeout to be reset.
1492 g_socket_set_timeout (GSocket
*socket
,
1495 g_return_if_fail (G_IS_SOCKET (socket
));
1497 if (timeout
!= socket
->priv
->timeout
)
1499 socket
->priv
->timeout
= timeout
;
1500 g_object_notify (G_OBJECT (socket
), "timeout");
1506 * @socket: a #GSocket.
1508 * Gets the unicast time-to-live setting on @socket; see
1509 * g_socket_set_ttl() for more details.
1511 * Returns: the time-to-live setting on @socket
1516 g_socket_get_ttl (GSocket
*socket
)
1518 GError
*error
= NULL
;
1521 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
1523 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1525 g_socket_get_option (socket
, IPPROTO_IP
, IP_TTL
,
1528 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1530 g_socket_get_option (socket
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
,
1534 g_return_val_if_reached (0);
1538 g_warning ("error getting unicast ttl: %s", error
->message
);
1539 g_error_free (error
);
1548 * @socket: a #GSocket.
1549 * @ttl: the time-to-live value for all unicast packets on @socket
1551 * Sets the time-to-live for outgoing unicast packets on @socket.
1552 * By default the platform-specific default value is used.
1557 g_socket_set_ttl (GSocket
*socket
,
1560 GError
*error
= NULL
;
1562 g_return_if_fail (G_IS_SOCKET (socket
));
1564 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1566 g_socket_set_option (socket
, IPPROTO_IP
, IP_TTL
,
1569 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1571 g_socket_set_option (socket
, IPPROTO_IP
, IP_TTL
,
1573 g_socket_set_option (socket
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
,
1577 g_return_if_reached ();
1581 g_warning ("error setting unicast ttl: %s", error
->message
);
1582 g_error_free (error
);
1586 g_object_notify (G_OBJECT (socket
), "ttl");
1590 * g_socket_get_broadcast:
1591 * @socket: a #GSocket.
1593 * Gets the broadcast setting on @socket; if %TRUE,
1594 * it is possible to send packets to broadcast
1597 * Returns: the broadcast setting on @socket
1602 g_socket_get_broadcast (GSocket
*socket
)
1604 GError
*error
= NULL
;
1607 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
1609 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_BROADCAST
,
1612 g_warning ("error getting broadcast: %s", error
->message
);
1613 g_error_free (error
);
1621 * g_socket_set_broadcast:
1622 * @socket: a #GSocket.
1623 * @broadcast: whether @socket should allow sending to broadcast
1626 * Sets whether @socket should allow sending to broadcast addresses.
1627 * This is %FALSE by default.
1632 g_socket_set_broadcast (GSocket
*socket
,
1635 GError
*error
= NULL
;
1637 g_return_if_fail (G_IS_SOCKET (socket
));
1639 broadcast
= !!broadcast
;
1641 if (!g_socket_set_option (socket
, SOL_SOCKET
, SO_BROADCAST
,
1644 g_warning ("error setting broadcast: %s", error
->message
);
1645 g_error_free (error
);
1649 g_object_notify (G_OBJECT (socket
), "broadcast");
1653 * g_socket_get_multicast_loopback:
1654 * @socket: a #GSocket.
1656 * Gets the multicast loopback setting on @socket; if %TRUE (the
1657 * default), outgoing multicast packets will be looped back to
1658 * multicast listeners on the same host.
1660 * Returns: the multicast loopback setting on @socket
1665 g_socket_get_multicast_loopback (GSocket
*socket
)
1667 GError
*error
= NULL
;
1670 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
1672 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1674 g_socket_get_option (socket
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
1677 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1679 g_socket_get_option (socket
, IPPROTO_IPV6
, IPV6_MULTICAST_LOOP
,
1683 g_return_val_if_reached (FALSE
);
1687 g_warning ("error getting multicast loopback: %s", error
->message
);
1688 g_error_free (error
);
1696 * g_socket_set_multicast_loopback:
1697 * @socket: a #GSocket.
1698 * @loopback: whether @socket should receive messages sent to its
1699 * multicast groups from the local host
1701 * Sets whether outgoing multicast packets will be received by sockets
1702 * listening on that multicast address on the same host. This is %TRUE
1708 g_socket_set_multicast_loopback (GSocket
*socket
,
1711 GError
*error
= NULL
;
1713 g_return_if_fail (G_IS_SOCKET (socket
));
1715 loopback
= !!loopback
;
1717 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1719 g_socket_set_option (socket
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
1722 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1724 g_socket_set_option (socket
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
1726 g_socket_set_option (socket
, IPPROTO_IPV6
, IPV6_MULTICAST_LOOP
,
1730 g_return_if_reached ();
1734 g_warning ("error setting multicast loopback: %s", error
->message
);
1735 g_error_free (error
);
1739 g_object_notify (G_OBJECT (socket
), "multicast-loopback");
1743 * g_socket_get_multicast_ttl:
1744 * @socket: a #GSocket.
1746 * Gets the multicast time-to-live setting on @socket; see
1747 * g_socket_set_multicast_ttl() for more details.
1749 * Returns: the multicast time-to-live setting on @socket
1754 g_socket_get_multicast_ttl (GSocket
*socket
)
1756 GError
*error
= NULL
;
1759 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
1761 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1763 g_socket_get_option (socket
, IPPROTO_IP
, IP_MULTICAST_TTL
,
1766 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1768 g_socket_get_option (socket
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
,
1772 g_return_val_if_reached (FALSE
);
1776 g_warning ("error getting multicast ttl: %s", error
->message
);
1777 g_error_free (error
);
1785 * g_socket_set_multicast_ttl:
1786 * @socket: a #GSocket.
1787 * @ttl: the time-to-live value for all multicast datagrams on @socket
1789 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1790 * By default, this is 1, meaning that multicast packets will not leave
1791 * the local network.
1796 g_socket_set_multicast_ttl (GSocket
*socket
,
1799 GError
*error
= NULL
;
1801 g_return_if_fail (G_IS_SOCKET (socket
));
1803 if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV4
)
1805 g_socket_set_option (socket
, IPPROTO_IP
, IP_MULTICAST_TTL
,
1808 else if (socket
->priv
->family
== G_SOCKET_FAMILY_IPV6
)
1810 g_socket_set_option (socket
, IPPROTO_IP
, IP_MULTICAST_TTL
,
1812 g_socket_set_option (socket
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
,
1816 g_return_if_reached ();
1820 g_warning ("error setting multicast ttl: %s", error
->message
);
1821 g_error_free (error
);
1825 g_object_notify (G_OBJECT (socket
), "multicast-ttl");
1829 * g_socket_get_family:
1830 * @socket: a #GSocket.
1832 * Gets the socket family of the socket.
1834 * Returns: a #GSocketFamily
1839 g_socket_get_family (GSocket
*socket
)
1841 g_return_val_if_fail (G_IS_SOCKET (socket
), G_SOCKET_FAMILY_INVALID
);
1843 return socket
->priv
->family
;
1847 * g_socket_get_socket_type:
1848 * @socket: a #GSocket.
1850 * Gets the socket type of the socket.
1852 * Returns: a #GSocketType
1857 g_socket_get_socket_type (GSocket
*socket
)
1859 g_return_val_if_fail (G_IS_SOCKET (socket
), G_SOCKET_TYPE_INVALID
);
1861 return socket
->priv
->type
;
1865 * g_socket_get_protocol:
1866 * @socket: a #GSocket.
1868 * Gets the socket protocol id the socket was created with.
1869 * In case the protocol is unknown, -1 is returned.
1871 * Returns: a protocol id, or -1 if unknown
1876 g_socket_get_protocol (GSocket
*socket
)
1878 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
1880 return socket
->priv
->protocol
;
1885 * @socket: a #GSocket.
1887 * Returns the underlying OS socket object. On unix this
1888 * is a socket file descriptor, and on Windows this is
1889 * a Winsock2 SOCKET handle. This may be useful for
1890 * doing platform specific or otherwise unusual operations
1893 * Returns: the file descriptor of the socket.
1898 g_socket_get_fd (GSocket
*socket
)
1900 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
1902 return socket
->priv
->fd
;
1906 * g_socket_get_local_address:
1907 * @socket: a #GSocket.
1908 * @error: #GError for error reporting, or %NULL to ignore.
1910 * Try to get the local address of a bound socket. This is only
1911 * useful if the socket has been bound to a local address,
1912 * either explicitly or implicitly when connecting.
1914 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1915 * Free the returned object with g_object_unref().
1920 g_socket_get_local_address (GSocket
*socket
,
1923 struct sockaddr_storage buffer
;
1924 guint len
= sizeof (buffer
);
1926 g_return_val_if_fail (G_IS_SOCKET (socket
), NULL
);
1928 if (getsockname (socket
->priv
->fd
, (struct sockaddr
*) &buffer
, &len
) < 0)
1930 int errsv
= get_socket_errno ();
1931 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
1932 _("could not get local address: %s"), socket_strerror (errsv
));
1936 return g_socket_address_new_from_native (&buffer
, len
);
1940 * g_socket_get_remote_address:
1941 * @socket: a #GSocket.
1942 * @error: #GError for error reporting, or %NULL to ignore.
1944 * Try to get the remove address of a connected socket. This is only
1945 * useful for connection oriented sockets that have been connected.
1947 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1948 * Free the returned object with g_object_unref().
1953 g_socket_get_remote_address (GSocket
*socket
,
1956 struct sockaddr_storage buffer
;
1957 guint len
= sizeof (buffer
);
1959 g_return_val_if_fail (G_IS_SOCKET (socket
), NULL
);
1961 if (socket
->priv
->connect_pending
)
1963 if (!g_socket_check_connect_result (socket
, error
))
1966 socket
->priv
->connect_pending
= FALSE
;
1969 if (!socket
->priv
->remote_address
)
1971 if (getpeername (socket
->priv
->fd
, (struct sockaddr
*) &buffer
, &len
) < 0)
1973 int errsv
= get_socket_errno ();
1974 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
1975 _("could not get remote address: %s"), socket_strerror (errsv
));
1979 socket
->priv
->remote_address
= g_socket_address_new_from_native (&buffer
, len
);
1982 return g_object_ref (socket
->priv
->remote_address
);
1986 * g_socket_is_connected:
1987 * @socket: a #GSocket.
1989 * Check whether the socket is connected. This is only useful for
1990 * connection-oriented sockets.
1992 * If using g_socket_shutdown(), this function will return %TRUE until the
1993 * socket has been shut down for reading and writing. If you do a non-blocking
1994 * connect, this function will not return %TRUE until after you call
1995 * g_socket_check_connect_result().
1997 * Returns: %TRUE if socket is connected, %FALSE otherwise.
2002 g_socket_is_connected (GSocket
*socket
)
2004 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2006 return (socket
->priv
->connected_read
|| socket
->priv
->connected_write
);
2011 * @socket: a #GSocket.
2012 * @error: #GError for error reporting, or %NULL to ignore.
2014 * Marks the socket as a server socket, i.e. a socket that is used
2015 * to accept incoming requests using g_socket_accept().
2017 * Before calling this the socket must be bound to a local address using
2020 * To set the maximum amount of outstanding clients, use
2021 * g_socket_set_listen_backlog().
2023 * Returns: %TRUE on success, %FALSE on error.
2028 g_socket_listen (GSocket
*socket
,
2031 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2033 if (!check_socket (socket
, error
))
2036 if (listen (socket
->priv
->fd
, socket
->priv
->listen_backlog
) < 0)
2038 int errsv
= get_socket_errno ();
2040 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
2041 _("could not listen: %s"), socket_strerror (errsv
));
2045 socket
->priv
->listening
= TRUE
;
2052 * @socket: a #GSocket.
2053 * @address: a #GSocketAddress specifying the local address.
2054 * @allow_reuse: whether to allow reusing this address
2055 * @error: #GError for error reporting, or %NULL to ignore.
2057 * When a socket is created it is attached to an address family, but it
2058 * doesn't have an address in this family. g_socket_bind() assigns the
2059 * address (sometimes called name) of the socket.
2061 * It is generally required to bind to a local address before you can
2062 * receive connections. (See g_socket_listen() and g_socket_accept() ).
2063 * In certain situations, you may also want to bind a socket that will be
2064 * used to initiate connections, though this is not normally required.
2066 * If @socket is a TCP socket, then @allow_reuse controls the setting
2067 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
2068 * server sockets (sockets that you will eventually call
2069 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
2070 * set this flag on a server socket may cause g_socket_bind() to return
2071 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
2072 * immediately restarted.)
2074 * If @socket is a UDP socket, then @allow_reuse determines whether or
2075 * not other UDP sockets can be bound to the same address at the same
2076 * time. In particular, you can have several UDP sockets bound to the
2077 * same address, and they will all receive all of the multicast and
2078 * broadcast packets sent to that address. (The behavior of unicast
2079 * UDP packets to an address with multiple listeners is not defined.)
2081 * Returns: %TRUE on success, %FALSE on error.
2086 g_socket_bind (GSocket
*socket
,
2087 GSocketAddress
*address
,
2088 gboolean reuse_address
,
2091 struct sockaddr_storage addr
;
2092 gboolean so_reuseaddr
;
2094 gboolean so_reuseport
;
2097 g_return_val_if_fail (G_IS_SOCKET (socket
) && G_IS_SOCKET_ADDRESS (address
), FALSE
);
2099 if (!check_socket (socket
, error
))
2102 if (!g_socket_address_to_native (address
, &addr
, sizeof addr
, error
))
2105 /* On Windows, SO_REUSEADDR has the semantics we want for UDP
2106 * sockets, but has nasty side effects we don't want for TCP
2109 * On other platforms, we set SO_REUSEPORT, if it exists, for
2110 * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
2111 * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
2112 * the desired semantics on UDP (as it does on Linux, although
2113 * Linux has SO_REUSEPORT too as of 3.9).
2117 so_reuseaddr
= reuse_address
&& (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
);
2119 so_reuseaddr
= !!reuse_address
;
2123 so_reuseport
= reuse_address
&& (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
);
2126 /* Ignore errors here, the only likely error is "not supported", and
2127 * this is a "best effort" thing mainly.
2129 g_socket_set_option (socket
, SOL_SOCKET
, SO_REUSEADDR
, so_reuseaddr
, NULL
);
2131 g_socket_set_option (socket
, SOL_SOCKET
, SO_REUSEPORT
, so_reuseport
, NULL
);
2134 if (bind (socket
->priv
->fd
, (struct sockaddr
*) &addr
,
2135 g_socket_address_get_native_size (address
)) < 0)
2137 int errsv
= get_socket_errno ();
2139 G_IO_ERROR
, socket_io_error_from_errno (errsv
),
2140 _("Error binding to address: %s"), socket_strerror (errsv
));
2147 #if !defined(HAVE_IF_NAMETOINDEX) && defined(G_OS_WIN32)
2149 if_nametoindex (const gchar
*iface
)
2151 PIP_ADAPTER_ADDRESSES addresses
= NULL
, p
;
2152 gulong addresses_len
= 0;
2156 if (ws2funcs
.pIfNameToIndex
!= NULL
)
2157 return ws2funcs
.pIfNameToIndex (iface
);
2159 res
= GetAdaptersAddresses (AF_UNSPEC
, 0, NULL
, NULL
, &addresses_len
);
2160 if (res
!= NO_ERROR
&& res
!= ERROR_BUFFER_OVERFLOW
)
2162 if (res
== ERROR_NO_DATA
)
2169 addresses
= g_malloc (addresses_len
);
2170 res
= GetAdaptersAddresses (AF_UNSPEC
, 0, NULL
, addresses
, &addresses_len
);
2172 if (res
!= NO_ERROR
)
2175 if (res
== ERROR_NO_DATA
)
2185 if (strcmp (p
->AdapterName
, iface
) == 0)
2201 #define HAVE_IF_NAMETOINDEX 1
2205 g_socket_multicast_group_operation (GSocket
*socket
,
2206 GInetAddress
*group
,
2207 gboolean source_specific
,
2209 gboolean join_group
,
2212 const guint8
*native_addr
;
2213 gint optname
, result
;
2215 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2216 g_return_val_if_fail (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
, FALSE
);
2217 g_return_val_if_fail (G_IS_INET_ADDRESS (group
), FALSE
);
2219 if (!check_socket (socket
, error
))
2222 native_addr
= g_inet_address_to_bytes (group
);
2223 if (g_inet_address_get_family (group
) == G_SOCKET_FAMILY_IPV4
)
2225 #ifdef HAVE_IP_MREQN
2226 struct ip_mreqn mc_req
;
2228 struct ip_mreq mc_req
;
2231 memset (&mc_req
, 0, sizeof (mc_req
));
2232 memcpy (&mc_req
.imr_multiaddr
, native_addr
, sizeof (struct in_addr
));
2234 #ifdef HAVE_IP_MREQN
2236 mc_req
.imr_ifindex
= if_nametoindex (iface
);
2238 mc_req
.imr_ifindex
= 0; /* Pick any. */
2239 #elif defined(G_OS_WIN32)
2241 mc_req
.imr_interface
.s_addr
= g_htonl (if_nametoindex (iface
));
2243 mc_req
.imr_interface
.s_addr
= g_htonl (INADDR_ANY
);
2245 mc_req
.imr_interface
.s_addr
= g_htonl (INADDR_ANY
);
2248 if (source_specific
)
2250 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2251 optname
= join_group
? IP_ADD_SOURCE_MEMBERSHIP
: IP_DROP_SOURCE_MEMBERSHIP
;
2253 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
2255 _("Error joining multicast group: %s") :
2256 _("Error leaving multicast group: %s"),
2257 _("No support for source-specific multicast"));
2262 optname
= join_group
? IP_ADD_MEMBERSHIP
: IP_DROP_MEMBERSHIP
;
2263 result
= setsockopt (socket
->priv
->fd
, IPPROTO_IP
, optname
,
2264 &mc_req
, sizeof (mc_req
));
2266 else if (g_inet_address_get_family (group
) == G_SOCKET_FAMILY_IPV6
)
2268 struct ipv6_mreq mc_req_ipv6
;
2270 memset (&mc_req_ipv6
, 0, sizeof (mc_req_ipv6
));
2271 memcpy (&mc_req_ipv6
.ipv6mr_multiaddr
, native_addr
, sizeof (struct in6_addr
));
2272 #ifdef HAVE_IF_NAMETOINDEX
2274 mc_req_ipv6
.ipv6mr_interface
= if_nametoindex (iface
);
2277 mc_req_ipv6
.ipv6mr_interface
= 0;
2279 optname
= join_group
? IPV6_JOIN_GROUP
: IPV6_LEAVE_GROUP
;
2280 result
= setsockopt (socket
->priv
->fd
, IPPROTO_IPV6
, optname
,
2281 &mc_req_ipv6
, sizeof (mc_req_ipv6
));
2284 g_return_val_if_reached (FALSE
);
2288 int errsv
= get_socket_errno ();
2290 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
2292 _("Error joining multicast group: %s") :
2293 _("Error leaving multicast group: %s"),
2294 socket_strerror (errsv
));
2302 * g_socket_join_multicast_group:
2303 * @socket: a #GSocket.
2304 * @group: a #GInetAddress specifying the group address to join.
2305 * @iface: (nullable): Name of the interface to use, or %NULL
2306 * @source_specific: %TRUE if source-specific multicast should be used
2307 * @error: #GError for error reporting, or %NULL to ignore.
2309 * Registers @socket to receive multicast messages sent to @group.
2310 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2311 * been bound to an appropriate interface and port with
2314 * If @iface is %NULL, the system will automatically pick an interface
2315 * to bind to based on @group.
2317 * If @source_specific is %TRUE, source-specific multicast as defined
2318 * in RFC 4604 is used. Note that on older platforms this may fail
2319 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2321 * Returns: %TRUE on success, %FALSE on error.
2326 g_socket_join_multicast_group (GSocket
*socket
,
2327 GInetAddress
*group
,
2328 gboolean source_specific
,
2332 return g_socket_multicast_group_operation (socket
, group
, source_specific
, iface
, TRUE
, error
);
2336 * g_socket_leave_multicast_group:
2337 * @socket: a #GSocket.
2338 * @group: a #GInetAddress specifying the group address to leave.
2339 * @iface: (nullable): Interface used
2340 * @source_specific: %TRUE if source-specific multicast was used
2341 * @error: #GError for error reporting, or %NULL to ignore.
2343 * Removes @socket from the multicast group defined by @group, @iface,
2344 * and @source_specific (which must all have the same values they had
2345 * when you joined the group).
2347 * @socket remains bound to its address and port, and can still receive
2348 * unicast messages after calling this.
2350 * Returns: %TRUE on success, %FALSE on error.
2355 g_socket_leave_multicast_group (GSocket
*socket
,
2356 GInetAddress
*group
,
2357 gboolean source_specific
,
2361 return g_socket_multicast_group_operation (socket
, group
, source_specific
, iface
, FALSE
, error
);
2365 * g_socket_speaks_ipv4:
2366 * @socket: a #GSocket
2368 * Checks if a socket is capable of speaking IPv4.
2370 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2371 * and under some combinations of circumstances IPv6 sockets are also
2372 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2375 * No other types of sockets are currently considered as being capable
2378 * Returns: %TRUE if this socket can be used with IPv4.
2383 g_socket_speaks_ipv4 (GSocket
*socket
)
2385 switch (socket
->priv
->family
)
2387 case G_SOCKET_FAMILY_IPV4
:
2390 case G_SOCKET_FAMILY_IPV6
:
2391 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2395 if (!g_socket_get_option (socket
,
2396 IPPROTO_IPV6
, IPV6_V6ONLY
,
2413 * @socket: a #GSocket.
2414 * @cancellable: (nullable): a %GCancellable or %NULL
2415 * @error: #GError for error reporting, or %NULL to ignore.
2417 * Accept incoming connections on a connection-based socket. This removes
2418 * the first outstanding connection request from the listening socket and
2419 * creates a #GSocket object for it.
2421 * The @socket must be bound to a local address with g_socket_bind() and
2422 * must be listening for incoming connections (g_socket_listen()).
2424 * If there are no outstanding connections then the operation will block
2425 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2426 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2428 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2429 * Free the returned object with g_object_unref().
2434 g_socket_accept (GSocket
*socket
,
2435 GCancellable
*cancellable
,
2438 GSocket
*new_socket
;
2441 g_return_val_if_fail (G_IS_SOCKET (socket
), NULL
);
2443 if (!check_socket (socket
, error
))
2446 if (!check_timeout (socket
, error
))
2451 win32_unset_event_mask (socket
, FD_ACCEPT
);
2453 if ((ret
= accept (socket
->priv
->fd
, NULL
, 0)) < 0)
2455 int errsv
= get_socket_errno ();
2460 #ifdef WSAEWOULDBLOCK
2461 if (errsv
== WSAEWOULDBLOCK
)
2463 if (errsv
== EWOULDBLOCK
||
2467 if (socket
->priv
->blocking
)
2469 if (!g_socket_condition_wait (socket
,
2470 G_IO_IN
, cancellable
, error
))
2477 socket_set_error_lazy (error
, errsv
, _("Error accepting connection: %s"));
2485 /* The socket inherits the accepting sockets event mask and even object,
2486 we need to remove that */
2487 WSAEventSelect (ret
, NULL
, 0);
2493 /* We always want to set close-on-exec to protect users. If you
2494 need to so some weird inheritance to exec you can re-enable this
2495 using lower level hacks with g_socket_get_fd(). */
2496 flags
= fcntl (ret
, F_GETFD
, 0);
2498 (flags
& FD_CLOEXEC
) == 0)
2500 flags
|= FD_CLOEXEC
;
2501 fcntl (ret
, F_SETFD
, flags
);
2506 new_socket
= g_socket_new_from_fd (ret
, error
);
2507 if (new_socket
== NULL
)
2516 new_socket
->priv
->protocol
= socket
->priv
->protocol
;
2523 * @socket: a #GSocket.
2524 * @address: a #GSocketAddress specifying the remote address.
2525 * @cancellable: (nullable): a %GCancellable or %NULL
2526 * @error: #GError for error reporting, or %NULL to ignore.
2528 * Connect the socket to the specified remote address.
2530 * For connection oriented socket this generally means we attempt to make
2531 * a connection to the @address. For a connection-less socket it sets
2532 * the default address for g_socket_send() and discards all incoming datagrams
2533 * from other sources.
2535 * Generally connection oriented sockets can only connect once, but
2536 * connection-less sockets can connect multiple times to change the
2539 * If the connect call needs to do network I/O it will block, unless
2540 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2541 * and the user can be notified of the connection finishing by waiting
2542 * for the G_IO_OUT condition. The result of the connection must then be
2543 * checked with g_socket_check_connect_result().
2545 * Returns: %TRUE if connected, %FALSE on error.
2550 g_socket_connect (GSocket
*socket
,
2551 GSocketAddress
*address
,
2552 GCancellable
*cancellable
,
2555 struct sockaddr_storage buffer
;
2557 g_return_val_if_fail (G_IS_SOCKET (socket
) && G_IS_SOCKET_ADDRESS (address
), FALSE
);
2559 if (!check_socket (socket
, error
))
2562 if (!g_socket_address_to_native (address
, &buffer
, sizeof buffer
, error
))
2565 if (socket
->priv
->remote_address
)
2566 g_object_unref (socket
->priv
->remote_address
);
2567 socket
->priv
->remote_address
= g_object_ref (address
);
2571 win32_unset_event_mask (socket
, FD_CONNECT
);
2573 if (connect (socket
->priv
->fd
, (struct sockaddr
*) &buffer
,
2574 g_socket_address_get_native_size (address
)) < 0)
2576 int errsv
= get_socket_errno ();
2582 if (errsv
== EINPROGRESS
)
2584 if (errsv
== WSAEWOULDBLOCK
)
2587 if (socket
->priv
->blocking
)
2589 if (g_socket_condition_wait (socket
, G_IO_OUT
, cancellable
, error
))
2591 if (g_socket_check_connect_result (socket
, error
))
2597 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_PENDING
,
2598 _("Connection in progress"));
2599 socket
->priv
->connect_pending
= TRUE
;
2603 g_set_error_literal (error
, G_IO_ERROR
,
2604 socket_io_error_from_errno (errsv
),
2605 socket_strerror (errsv
));
2612 socket
->priv
->connected_read
= TRUE
;
2613 socket
->priv
->connected_write
= TRUE
;
2619 * g_socket_check_connect_result:
2620 * @socket: a #GSocket
2621 * @error: #GError for error reporting, or %NULL to ignore.
2623 * Checks and resets the pending connect error for the socket.
2624 * This is used to check for errors when g_socket_connect() is
2625 * used in non-blocking mode.
2627 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2632 g_socket_check_connect_result (GSocket
*socket
,
2637 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
2639 if (!check_socket (socket
, error
))
2642 if (!check_timeout (socket
, error
))
2645 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_ERROR
, &value
, error
))
2647 g_prefix_error (error
, _("Unable to get pending error: "));
2653 g_set_error_literal (error
, G_IO_ERROR
, socket_io_error_from_errno (value
),
2654 socket_strerror (value
));
2655 if (socket
->priv
->remote_address
)
2657 g_object_unref (socket
->priv
->remote_address
);
2658 socket
->priv
->remote_address
= NULL
;
2663 socket
->priv
->connected_read
= TRUE
;
2664 socket
->priv
->connected_write
= TRUE
;
2670 * g_socket_get_available_bytes:
2671 * @socket: a #GSocket
2673 * Get the amount of data pending in the OS input buffer, without blocking.
2675 * If @socket is a UDP or SCTP socket, this will return the size of
2676 * just the next packet, even if additional packets are buffered after
2679 * Note that on Windows, this function is rather inefficient in the
2680 * UDP case, and so if you know any plausible upper bound on the size
2681 * of the incoming packet, it is better to just do a
2682 * g_socket_receive() with a buffer of that size, rather than calling
2683 * g_socket_get_available_bytes() first and then doing a receive of
2684 * exactly the right size.
2686 * Returns: the number of bytes that can be read from the socket
2687 * without blocking or truncating, or -1 on error.
2692 g_socket_get_available_bytes (GSocket
*socket
)
2695 const gint bufsize
= 64 * 1024;
2696 static guchar
*buf
= NULL
;
2702 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
2704 #if defined (SO_NREAD)
2705 if (!g_socket_get_option (socket
, SOL_SOCKET
, SO_NREAD
, &avail
, NULL
))
2707 #elif !defined (G_OS_WIN32)
2708 if (ioctl (socket
->priv
->fd
, FIONREAD
, &avail
) < 0)
2711 if (socket
->priv
->type
== G_SOCKET_TYPE_DATAGRAM
)
2713 if (G_UNLIKELY (g_once_init_enter (&buf
)))
2714 g_once_init_leave (&buf
, g_malloc (bufsize
));
2716 avail
= recv (socket
->priv
->fd
, buf
, bufsize
, MSG_PEEK
);
2717 if (avail
== -1 && get_socket_errno () == WSAEWOULDBLOCK
)
2722 if (ioctlsocket (socket
->priv
->fd
, FIONREAD
, &avail
) < 0)
2730 /* Block on a timed wait for @condition until (@start_time + @timeout).
2731 * Return %G_IO_ERROR_TIMED_OUT if the timeout is reached; otherwise %TRUE.
2734 block_on_timeout (GSocket
*socket
,
2735 GIOCondition condition
,
2738 GCancellable
*cancellable
,
2741 gint64 wait_timeout
= -1;
2743 g_return_val_if_fail (timeout
!= 0, TRUE
);
2745 /* check if we've timed out or how much time to wait at most */
2748 gint64 elapsed
= g_get_monotonic_time () - start_time
;
2750 if (elapsed
>= timeout
)
2752 g_set_error_literal (error
,
2753 G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
,
2754 _("Socket I/O timed out"));
2758 wait_timeout
= timeout
- elapsed
;
2761 return g_socket_condition_timed_wait (socket
, condition
, wait_timeout
,
2762 cancellable
, error
);
2766 g_socket_receive_with_timeout (GSocket
*socket
,
2770 GCancellable
*cancellable
,
2776 g_return_val_if_fail (G_IS_SOCKET (socket
) && buffer
!= NULL
, -1);
2778 start_time
= g_get_monotonic_time ();
2780 if (!check_socket (socket
, error
))
2783 if (!check_timeout (socket
, error
))
2786 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
2791 win32_unset_event_mask (socket
, FD_READ
);
2793 if ((ret
= recv (socket
->priv
->fd
, buffer
, size
, 0)) < 0)
2795 int errsv
= get_socket_errno ();
2800 #ifdef WSAEWOULDBLOCK
2801 if (errsv
== WSAEWOULDBLOCK
)
2803 if (errsv
== EWOULDBLOCK
||
2809 if (!block_on_timeout (socket
, G_IO_IN
, timeout
, start_time
,
2810 cancellable
, error
))
2817 socket_set_error_lazy (error
, errsv
, _("Error receiving data: %s"));
2829 * @socket: a #GSocket
2830 * @buffer: (array length=size) (element-type guint8): a buffer to
2831 * read data into (which should be at least @size bytes long).
2832 * @size: the number of bytes you want to read from the socket
2833 * @cancellable: (nullable): a %GCancellable or %NULL
2834 * @error: #GError for error reporting, or %NULL to ignore.
2836 * Receive data (up to @size bytes) from a socket. This is mainly used by
2837 * connection-oriented sockets; it is identical to g_socket_receive_from()
2838 * with @address set to %NULL.
2840 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2841 * g_socket_receive() will always read either 0 or 1 complete messages from
2842 * the socket. If the received message is too large to fit in @buffer, then
2843 * the data beyond @size bytes will be discarded, without any explicit
2844 * indication that this has occurred.
2846 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2847 * number of bytes, up to @size. If more than @size bytes have been
2848 * received, the additional data will be returned in future calls to
2849 * g_socket_receive().
2851 * If the socket is in blocking mode the call will block until there
2852 * is some data to receive, the connection is closed, or there is an
2853 * error. If there is no data available and the socket is in
2854 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2855 * returned. To be notified when data is available, wait for the
2856 * %G_IO_IN condition.
2858 * On error -1 is returned and @error is set accordingly.
2860 * Returns: Number of bytes read, or 0 if the connection was closed by
2861 * the peer, or -1 on error
2866 g_socket_receive (GSocket
*socket
,
2869 GCancellable
*cancellable
,
2872 return g_socket_receive_with_timeout (socket
, (guint8
*) buffer
, size
,
2873 socket
->priv
->blocking
? -1 : 0,
2874 cancellable
, error
);
2878 * g_socket_receive_with_blocking:
2879 * @socket: a #GSocket
2880 * @buffer: (array length=size) (element-type guint8): a buffer to
2881 * read data into (which should be at least @size bytes long).
2882 * @size: the number of bytes you want to read from the socket
2883 * @blocking: whether to do blocking or non-blocking I/O
2884 * @cancellable: (nullable): a %GCancellable or %NULL
2885 * @error: #GError for error reporting, or %NULL to ignore.
2887 * This behaves exactly the same as g_socket_receive(), except that
2888 * the choice of blocking or non-blocking behavior is determined by
2889 * the @blocking argument rather than by @socket's properties.
2891 * Returns: Number of bytes read, or 0 if the connection was closed by
2892 * the peer, or -1 on error
2897 g_socket_receive_with_blocking (GSocket
*socket
,
2901 GCancellable
*cancellable
,
2904 return g_socket_receive_with_timeout (socket
, (guint8
*) buffer
, size
,
2905 blocking
? -1 : 0, cancellable
, error
);
2909 * g_socket_receive_from:
2910 * @socket: a #GSocket
2911 * @address: (out) (optional): a pointer to a #GSocketAddress
2913 * @buffer: (array length=size) (element-type guint8): a buffer to
2914 * read data into (which should be at least @size bytes long).
2915 * @size: the number of bytes you want to read from the socket
2916 * @cancellable: (nullable): a %GCancellable or %NULL
2917 * @error: #GError for error reporting, or %NULL to ignore.
2919 * Receive data (up to @size bytes) from a socket.
2921 * If @address is non-%NULL then @address will be set equal to the
2922 * source address of the received packet.
2923 * @address is owned by the caller.
2925 * See g_socket_receive() for additional information.
2927 * Returns: Number of bytes read, or 0 if the connection was closed by
2928 * the peer, or -1 on error
2933 g_socket_receive_from (GSocket
*socket
,
2934 GSocketAddress
**address
,
2937 GCancellable
*cancellable
,
2945 return g_socket_receive_message (socket
,
2953 /* See the comment about SIGPIPE above. */
2955 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2957 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2961 g_socket_send_with_timeout (GSocket
*socket
,
2962 const guint8
*buffer
,
2965 GCancellable
*cancellable
,
2971 g_return_val_if_fail (G_IS_SOCKET (socket
) && buffer
!= NULL
, -1);
2973 start_time
= g_get_monotonic_time ();
2975 if (!check_socket (socket
, error
))
2978 if (!check_timeout (socket
, error
))
2981 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
2986 win32_unset_event_mask (socket
, FD_WRITE
);
2988 if ((ret
= send (socket
->priv
->fd
, buffer
, size
, G_SOCKET_DEFAULT_SEND_FLAGS
)) < 0)
2990 int errsv
= get_socket_errno ();
2995 #ifdef WSAEWOULDBLOCK
2996 if (errsv
== WSAEWOULDBLOCK
)
2998 if (errsv
== EWOULDBLOCK
||
3004 if (!block_on_timeout (socket
, G_IO_OUT
, timeout
, start_time
,
3005 cancellable
, error
))
3012 socket_set_error_lazy (error
, errsv
, _("Error sending data: %s"));
3023 * @socket: a #GSocket
3024 * @buffer: (array length=size) (element-type guint8): the buffer
3025 * containing the data to send.
3026 * @size: the number of bytes to send
3027 * @cancellable: (nullable): a %GCancellable or %NULL
3028 * @error: #GError for error reporting, or %NULL to ignore.
3030 * Tries to send @size bytes from @buffer on the socket. This is
3031 * mainly used by connection-oriented sockets; it is identical to
3032 * g_socket_send_to() with @address set to %NULL.
3034 * If the socket is in blocking mode the call will block until there is
3035 * space for the data in the socket queue. If there is no space available
3036 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3037 * will be returned. To be notified when space is available, wait for the
3038 * %G_IO_OUT condition. Note though that you may still receive
3039 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3040 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3041 * very common due to the way the underlying APIs work.)
3043 * On error -1 is returned and @error is set accordingly.
3045 * Returns: Number of bytes written (which may be less than @size), or -1
3051 g_socket_send (GSocket
*socket
,
3052 const gchar
*buffer
,
3054 GCancellable
*cancellable
,
3057 return g_socket_send_with_blocking (socket
, buffer
, size
,
3058 socket
->priv
->blocking
,
3059 cancellable
, error
);
3063 * g_socket_send_with_blocking:
3064 * @socket: a #GSocket
3065 * @buffer: (array length=size) (element-type guint8): the buffer
3066 * containing the data to send.
3067 * @size: the number of bytes to send
3068 * @blocking: whether to do blocking or non-blocking I/O
3069 * @cancellable: (nullable): a %GCancellable or %NULL
3070 * @error: #GError for error reporting, or %NULL to ignore.
3072 * This behaves exactly the same as g_socket_send(), except that
3073 * the choice of blocking or non-blocking behavior is determined by
3074 * the @blocking argument rather than by @socket's properties.
3076 * Returns: Number of bytes written (which may be less than @size), or -1
3082 g_socket_send_with_blocking (GSocket
*socket
,
3083 const gchar
*buffer
,
3086 GCancellable
*cancellable
,
3089 return g_socket_send_with_timeout (socket
, (const guint8
*) buffer
, size
,
3090 blocking
? -1 : 0, cancellable
, error
);
3095 * @socket: a #GSocket
3096 * @address: (nullable): a #GSocketAddress, or %NULL
3097 * @buffer: (array length=size) (element-type guint8): the buffer
3098 * containing the data to send.
3099 * @size: the number of bytes to send
3100 * @cancellable: (nullable): a %GCancellable or %NULL
3101 * @error: #GError for error reporting, or %NULL to ignore.
3103 * Tries to send @size bytes from @buffer to @address. If @address is
3104 * %NULL then the message is sent to the default receiver (set by
3105 * g_socket_connect()).
3107 * See g_socket_send() for additional information.
3109 * Returns: Number of bytes written (which may be less than @size), or -1
3115 g_socket_send_to (GSocket
*socket
,
3116 GSocketAddress
*address
,
3117 const gchar
*buffer
,
3119 GCancellable
*cancellable
,
3127 return g_socket_send_message (socket
,
3137 * g_socket_shutdown:
3138 * @socket: a #GSocket
3139 * @shutdown_read: whether to shut down the read side
3140 * @shutdown_write: whether to shut down the write side
3141 * @error: #GError for error reporting, or %NULL to ignore.
3143 * Shut down part or all of a full-duplex connection.
3145 * If @shutdown_read is %TRUE then the receiving side of the connection
3146 * is shut down, and further reading is disallowed.
3148 * If @shutdown_write is %TRUE then the sending side of the connection
3149 * is shut down, and further writing is disallowed.
3151 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
3153 * One example where it is useful to shut down only one side of a connection is
3154 * graceful disconnect for TCP connections where you close the sending side,
3155 * then wait for the other side to close the connection, thus ensuring that the
3156 * other side saw all sent data.
3158 * Returns: %TRUE on success, %FALSE on error
3163 g_socket_shutdown (GSocket
*socket
,
3164 gboolean shutdown_read
,
3165 gboolean shutdown_write
,
3170 g_return_val_if_fail (G_IS_SOCKET (socket
), TRUE
);
3172 if (!check_socket (socket
, error
))
3176 if (!shutdown_read
&& !shutdown_write
)
3180 if (shutdown_read
&& shutdown_write
)
3182 else if (shutdown_read
)
3187 if (shutdown_read
&& shutdown_write
)
3189 else if (shutdown_read
)
3195 if (shutdown (socket
->priv
->fd
, how
) != 0)
3197 int errsv
= get_socket_errno ();
3198 g_set_error (error
, G_IO_ERROR
, socket_io_error_from_errno (errsv
),
3199 _("Unable to shutdown socket: %s"), socket_strerror (errsv
));
3204 socket
->priv
->connected_read
= FALSE
;
3206 socket
->priv
->connected_write
= FALSE
;
3213 * @socket: a #GSocket
3214 * @error: #GError for error reporting, or %NULL to ignore.
3216 * Closes the socket, shutting down any active connection.
3218 * Closing a socket does not wait for all outstanding I/O operations
3219 * to finish, so the caller should not rely on them to be guaranteed
3220 * to complete even if the close returns with no error.
3222 * Once the socket is closed, all other operations will return
3223 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
3226 * Sockets will be automatically closed when the last reference
3227 * is dropped, but you might want to call this function to make sure
3228 * resources are released as early as possible.
3230 * Beware that due to the way that TCP works, it is possible for
3231 * recently-sent data to be lost if either you close a socket while the
3232 * %G_IO_IN condition is set, or else if the remote connection tries to
3233 * send something to you after you close the socket but before it has
3234 * finished reading all of the data you sent. There is no easy generic
3235 * way to avoid this problem; the easiest fix is to design the network
3236 * protocol such that the client will never send data "out of turn".
3237 * Another solution is for the server to half-close the connection by
3238 * calling g_socket_shutdown() with only the @shutdown_write flag set,
3239 * and then wait for the client to notice this and close its side of the
3240 * connection, after which the server can safely call g_socket_close().
3241 * (This is what #GTcpConnection does if you call
3242 * g_tcp_connection_set_graceful_disconnect(). But of course, this
3243 * only works if the client will close its connection after the server
3246 * Returns: %TRUE on success, %FALSE on error
3251 g_socket_close (GSocket
*socket
,
3256 g_return_val_if_fail (G_IS_SOCKET (socket
), TRUE
);
3258 if (socket
->priv
->closed
)
3259 return TRUE
; /* Multiple close not an error */
3261 if (!check_socket (socket
, error
))
3267 res
= closesocket (socket
->priv
->fd
);
3269 res
= close (socket
->priv
->fd
);
3273 int errsv
= get_socket_errno ();
3278 g_set_error (error
, G_IO_ERROR
,
3279 socket_io_error_from_errno (errsv
),
3280 _("Error closing socket: %s"),
3281 socket_strerror (errsv
));
3287 socket
->priv
->fd
= -1;
3288 socket
->priv
->connected_read
= FALSE
;
3289 socket
->priv
->connected_write
= FALSE
;
3290 socket
->priv
->closed
= TRUE
;
3291 if (socket
->priv
->remote_address
)
3293 g_object_unref (socket
->priv
->remote_address
);
3294 socket
->priv
->remote_address
= NULL
;
3301 * g_socket_is_closed:
3302 * @socket: a #GSocket
3304 * Checks whether a socket is closed.
3306 * Returns: %TRUE if socket is closed, %FALSE otherwise
3311 g_socket_is_closed (GSocket
*socket
)
3313 return socket
->priv
->closed
;
3317 /* Broken source, used on errors */
3319 broken_dispatch (GSource
*source
,
3320 GSourceFunc callback
,
3326 static GSourceFuncs broken_funcs
=
3335 network_events_for_condition (GIOCondition condition
)
3339 if (condition
& G_IO_IN
)
3340 event_mask
|= (FD_READ
| FD_ACCEPT
);
3341 if (condition
& G_IO_OUT
)
3342 event_mask
|= (FD_WRITE
| FD_CONNECT
);
3343 event_mask
|= FD_CLOSE
;
3349 ensure_event (GSocket
*socket
)
3351 if (socket
->priv
->event
== WSA_INVALID_EVENT
)
3352 socket
->priv
->event
= WSACreateEvent();
3356 update_select_events (GSocket
*socket
)
3363 ensure_event (socket
);
3366 for (l
= socket
->priv
->requested_conditions
; l
!= NULL
; l
= l
->next
)
3369 event_mask
|= network_events_for_condition (*ptr
);
3372 if (event_mask
!= socket
->priv
->selected_events
)
3374 /* If no events selected, disable event so we can unset
3377 if (event_mask
== 0)
3380 event
= socket
->priv
->event
;
3382 if (WSAEventSelect (socket
->priv
->fd
, event
, event_mask
) == 0)
3383 socket
->priv
->selected_events
= event_mask
;
3388 add_condition_watch (GSocket
*socket
,
3389 GIOCondition
*condition
)
3391 g_mutex_lock (&socket
->priv
->win32_source_lock
);
3392 g_assert (g_list_find (socket
->priv
->requested_conditions
, condition
) == NULL
);
3394 socket
->priv
->requested_conditions
=
3395 g_list_prepend (socket
->priv
->requested_conditions
, condition
);
3397 update_select_events (socket
);
3398 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
3402 remove_condition_watch (GSocket
*socket
,
3403 GIOCondition
*condition
)
3405 g_mutex_lock (&socket
->priv
->win32_source_lock
);
3406 g_assert (g_list_find (socket
->priv
->requested_conditions
, condition
) != NULL
);
3408 socket
->priv
->requested_conditions
=
3409 g_list_remove (socket
->priv
->requested_conditions
, condition
);
3411 update_select_events (socket
);
3412 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
3416 update_condition_unlocked (GSocket
*socket
)
3418 WSANETWORKEVENTS events
;
3419 GIOCondition condition
;
3421 if (WSAEnumNetworkEvents (socket
->priv
->fd
,
3422 socket
->priv
->event
,
3425 socket
->priv
->current_events
|= events
.lNetworkEvents
;
3426 if (events
.lNetworkEvents
& FD_WRITE
&&
3427 events
.iErrorCode
[FD_WRITE_BIT
] != 0)
3428 socket
->priv
->current_errors
|= FD_WRITE
;
3429 if (events
.lNetworkEvents
& FD_CONNECT
&&
3430 events
.iErrorCode
[FD_CONNECT_BIT
] != 0)
3431 socket
->priv
->current_errors
|= FD_CONNECT
;
3435 if (socket
->priv
->current_events
& (FD_READ
| FD_ACCEPT
))
3436 condition
|= G_IO_IN
;
3438 if (socket
->priv
->current_events
& FD_CLOSE
)
3440 int r
, errsv
, buffer
;
3442 r
= recv (socket
->priv
->fd
, &buffer
, sizeof (buffer
), MSG_PEEK
);
3444 errsv
= get_socket_errno ();
3447 (r
< 0 && errsv
== WSAENOTCONN
))
3448 condition
|= G_IO_IN
;
3450 (r
< 0 && (errsv
== WSAESHUTDOWN
|| errsv
== WSAECONNRESET
||
3451 errsv
== WSAECONNABORTED
|| errsv
== WSAENETRESET
)))
3452 condition
|= G_IO_HUP
;
3454 condition
|= G_IO_ERR
;
3457 if (socket
->priv
->closed
)
3458 condition
|= G_IO_HUP
;
3460 /* Never report both G_IO_OUT and HUP, these are
3461 mutually exclusive (can't write to a closed socket) */
3462 if ((condition
& G_IO_HUP
) == 0 &&
3463 socket
->priv
->current_events
& FD_WRITE
)
3465 if (socket
->priv
->current_errors
& FD_WRITE
)
3466 condition
|= G_IO_ERR
;
3468 condition
|= G_IO_OUT
;
3472 if (socket
->priv
->current_events
& FD_CONNECT
)
3474 if (socket
->priv
->current_errors
& FD_CONNECT
)
3475 condition
|= (G_IO_HUP
| G_IO_ERR
);
3477 condition
|= G_IO_OUT
;
3485 update_condition (GSocket
*socket
)
3488 g_mutex_lock (&socket
->priv
->win32_source_lock
);
3489 res
= update_condition_unlocked (socket
);
3490 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
3503 GIOCondition condition
;
3508 socket_source_prepare_win32 (GSource
*source
,
3511 GSocketSource
*socket_source
= (GSocketSource
*)source
;
3515 return (update_condition (socket_source
->socket
) & socket_source
->condition
) != 0;
3519 socket_source_check_win32 (GSource
*source
)
3523 return socket_source_prepare_win32 (source
, &timeout
);
3528 socket_source_dispatch (GSource
*source
,
3529 GSourceFunc callback
,
3532 GSocketSourceFunc func
= (GSocketSourceFunc
)callback
;
3533 GSocketSource
*socket_source
= (GSocketSource
*)source
;
3534 GSocket
*socket
= socket_source
->socket
;
3540 events
= update_condition (socket_source
->socket
);
3542 events
= g_source_query_unix_fd (source
, socket_source
->fd_tag
);
3545 timeout
= g_source_get_ready_time (source
);
3546 if (timeout
>= 0 && timeout
< g_source_get_time (source
))
3548 socket
->priv
->timed_out
= TRUE
;
3549 events
|= (G_IO_IN
| G_IO_OUT
);
3552 ret
= (*func
) (socket
, events
& socket_source
->condition
, user_data
);
3554 if (socket
->priv
->timeout
)
3555 g_source_set_ready_time (source
, g_get_monotonic_time () + socket
->priv
->timeout
* 1000000);
3557 g_source_set_ready_time (source
, -1);
3563 socket_source_finalize (GSource
*source
)
3565 GSocketSource
*socket_source
= (GSocketSource
*)source
;
3568 socket
= socket_source
->socket
;
3571 remove_condition_watch (socket
, &socket_source
->condition
);
3574 g_object_unref (socket
);
3578 socket_source_closure_callback (GSocket
*socket
,
3579 GIOCondition condition
,
3582 GClosure
*closure
= data
;
3584 GValue params
[2] = { G_VALUE_INIT
, G_VALUE_INIT
};
3585 GValue result_value
= G_VALUE_INIT
;
3588 g_value_init (&result_value
, G_TYPE_BOOLEAN
);
3590 g_value_init (¶ms
[0], G_TYPE_SOCKET
);
3591 g_value_set_object (¶ms
[0], socket
);
3592 g_value_init (¶ms
[1], G_TYPE_IO_CONDITION
);
3593 g_value_set_flags (¶ms
[1], condition
);
3595 g_closure_invoke (closure
, &result_value
, 2, params
, NULL
);
3597 result
= g_value_get_boolean (&result_value
);
3598 g_value_unset (&result_value
);
3599 g_value_unset (¶ms
[0]);
3600 g_value_unset (¶ms
[1]);
3605 static GSourceFuncs socket_source_funcs
=
3608 socket_source_prepare_win32
,
3609 socket_source_check_win32
,
3611 NULL
, NULL
, /* check, prepare */
3613 socket_source_dispatch
,
3614 socket_source_finalize
,
3615 (GSourceFunc
)socket_source_closure_callback
,
3619 socket_source_new (GSocket
*socket
,
3620 GIOCondition condition
,
3621 GCancellable
*cancellable
)
3624 GSocketSource
*socket_source
;
3627 ensure_event (socket
);
3629 if (socket
->priv
->event
== WSA_INVALID_EVENT
)
3631 g_warning ("Failed to create WSAEvent");
3632 return g_source_new (&broken_funcs
, sizeof (GSource
));
3636 condition
|= G_IO_HUP
| G_IO_ERR
| G_IO_NVAL
;
3638 source
= g_source_new (&socket_source_funcs
, sizeof (GSocketSource
));
3639 g_source_set_name (source
, "GSocket");
3640 socket_source
= (GSocketSource
*)source
;
3642 socket_source
->socket
= g_object_ref (socket
);
3643 socket_source
->condition
= condition
;
3647 GSource
*cancellable_source
;
3649 cancellable_source
= g_cancellable_source_new (cancellable
);
3650 g_source_add_child_source (source
, cancellable_source
);
3651 g_source_set_dummy_callback (cancellable_source
);
3652 g_source_unref (cancellable_source
);
3656 add_condition_watch (socket
, &socket_source
->condition
);
3657 socket_source
->pollfd
.fd
= (gintptr
) socket
->priv
->event
;
3658 socket_source
->pollfd
.events
= condition
;
3659 socket_source
->pollfd
.revents
= 0;
3660 g_source_add_poll (source
, &socket_source
->pollfd
);
3662 socket_source
->fd_tag
= g_source_add_unix_fd (source
, socket
->priv
->fd
, condition
);
3665 if (socket
->priv
->timeout
)
3666 g_source_set_ready_time (source
, g_get_monotonic_time () + socket
->priv
->timeout
* 1000000);
3668 g_source_set_ready_time (source
, -1);
3674 * g_socket_create_source: (skip)
3675 * @socket: a #GSocket
3676 * @condition: a #GIOCondition mask to monitor
3677 * @cancellable: (nullable): a %GCancellable or %NULL
3679 * Creates a #GSource that can be attached to a %GMainContext to monitor
3680 * for the availability of the specified @condition on the socket. The #GSource
3681 * keeps a reference to the @socket.
3683 * The callback on the source is of the #GSocketSourceFunc type.
3685 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3686 * these conditions will always be reported output if they are true.
3688 * @cancellable if not %NULL can be used to cancel the source, which will
3689 * cause the source to trigger, reporting the current condition (which
3690 * is likely 0 unless cancellation happened at the same time as a
3691 * condition change). You can check for this in the callback using
3692 * g_cancellable_is_cancelled().
3694 * If @socket has a timeout set, and it is reached before @condition
3695 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3696 * %G_IO_OUT depending on @condition. However, @socket will have been
3697 * marked as having had a timeout, and so the next #GSocket I/O method
3698 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3700 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3705 g_socket_create_source (GSocket
*socket
,
3706 GIOCondition condition
,
3707 GCancellable
*cancellable
)
3709 g_return_val_if_fail (G_IS_SOCKET (socket
) && (cancellable
== NULL
|| G_IS_CANCELLABLE (cancellable
)), NULL
);
3711 return socket_source_new (socket
, condition
, cancellable
);
3715 * g_socket_condition_check:
3716 * @socket: a #GSocket
3717 * @condition: a #GIOCondition mask to check
3719 * Checks on the readiness of @socket to perform operations.
3720 * The operations specified in @condition are checked for and masked
3721 * against the currently-satisfied conditions on @socket. The result
3724 * Note that on Windows, it is possible for an operation to return
3725 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3726 * g_socket_condition_check() has claimed that the socket is ready for
3727 * writing. Rather than calling g_socket_condition_check() and then
3728 * writing to the socket if it succeeds, it is generally better to
3729 * simply try writing to the socket right away, and try again later if
3730 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3732 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3733 * these conditions will always be set in the output if they are true.
3735 * This call never blocks.
3737 * Returns: the @GIOCondition mask of the current state
3742 g_socket_condition_check (GSocket
*socket
,
3743 GIOCondition condition
)
3745 g_return_val_if_fail (G_IS_SOCKET (socket
), 0);
3747 if (!check_socket (socket
, NULL
))
3752 GIOCondition current_condition
;
3754 condition
|= G_IO_ERR
| G_IO_HUP
;
3756 add_condition_watch (socket
, &condition
);
3757 current_condition
= update_condition (socket
);
3758 remove_condition_watch (socket
, &condition
);
3759 return condition
& current_condition
;
3765 poll_fd
.fd
= socket
->priv
->fd
;
3766 poll_fd
.events
= condition
;
3767 poll_fd
.revents
= 0;
3770 result
= g_poll (&poll_fd
, 1, 0);
3771 while (result
== -1 && get_socket_errno () == EINTR
);
3773 return poll_fd
.revents
;
3779 * g_socket_condition_wait:
3780 * @socket: a #GSocket
3781 * @condition: a #GIOCondition mask to wait for
3782 * @cancellable: (nullable): a #GCancellable, or %NULL
3783 * @error: a #GError pointer, or %NULL
3785 * Waits for @condition to become true on @socket. When the condition
3786 * is met, %TRUE is returned.
3788 * If @cancellable is cancelled before the condition is met, or if the
3789 * socket has a timeout set and it is reached before the condition is
3790 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3791 * the appropriate value (%G_IO_ERROR_CANCELLED or
3792 * %G_IO_ERROR_TIMED_OUT).
3794 * See also g_socket_condition_timed_wait().
3796 * Returns: %TRUE if the condition was met, %FALSE otherwise
3801 g_socket_condition_wait (GSocket
*socket
,
3802 GIOCondition condition
,
3803 GCancellable
*cancellable
,
3806 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
3808 return g_socket_condition_timed_wait (socket
, condition
, -1,
3809 cancellable
, error
);
3813 * g_socket_condition_timed_wait:
3814 * @socket: a #GSocket
3815 * @condition: a #GIOCondition mask to wait for
3816 * @timeout: the maximum time (in microseconds) to wait, or -1
3817 * @cancellable: (nullable): a #GCancellable, or %NULL
3818 * @error: a #GError pointer, or %NULL
3820 * Waits for up to @timeout microseconds for @condition to become true
3821 * on @socket. If the condition is met, %TRUE is returned.
3823 * If @cancellable is cancelled before the condition is met, or if
3824 * @timeout (or the socket's #GSocket:timeout) is reached before the
3825 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3826 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3827 * %G_IO_ERROR_TIMED_OUT).
3829 * If you don't want a timeout, use g_socket_condition_wait().
3830 * (Alternatively, you can pass -1 for @timeout.)
3832 * Note that although @timeout is in microseconds for consistency with
3833 * other GLib APIs, this function actually only has millisecond
3834 * resolution, and the behavior is undefined if @timeout is not an
3835 * exact number of milliseconds.
3837 * Returns: %TRUE if the condition was met, %FALSE otherwise
3842 g_socket_condition_timed_wait (GSocket
*socket
,
3843 GIOCondition condition
,
3845 GCancellable
*cancellable
,
3850 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
3852 if (!check_socket (socket
, error
))
3855 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
3858 if (socket
->priv
->timeout
&&
3859 (timeout
< 0 || socket
->priv
->timeout
< timeout
/ G_USEC_PER_SEC
))
3860 timeout
= socket
->priv
->timeout
* 1000;
3861 else if (timeout
!= -1)
3862 timeout
= timeout
/ 1000;
3864 start_time
= g_get_monotonic_time ();
3868 GIOCondition current_condition
;
3874 /* Always check these */
3875 condition
|= G_IO_ERR
| G_IO_HUP
;
3877 add_condition_watch (socket
, &condition
);
3880 events
[num_events
++] = socket
->priv
->event
;
3882 if (g_cancellable_make_pollfd (cancellable
, &cancel_fd
))
3883 events
[num_events
++] = (WSAEVENT
)cancel_fd
.fd
;
3886 timeout
= WSA_INFINITE
;
3888 g_mutex_lock (&socket
->priv
->win32_source_lock
);
3889 current_condition
= update_condition_unlocked (socket
);
3890 while ((condition
& current_condition
) == 0)
3892 if (!socket
->priv
->waiting
)
3894 socket
->priv
->waiting
= TRUE
;
3895 socket
->priv
->waiting_result
= 0;
3896 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
3898 res
= WSAWaitForMultipleEvents (num_events
, events
, FALSE
, timeout
, FALSE
);
3900 g_mutex_lock (&socket
->priv
->win32_source_lock
);
3901 socket
->priv
->waiting
= FALSE
;
3902 socket
->priv
->waiting_result
= res
;
3903 g_cond_broadcast (&socket
->priv
->win32_source_cond
);
3907 if (timeout
!= WSA_INFINITE
)
3909 if (!g_cond_wait_until (&socket
->priv
->win32_source_cond
, &socket
->priv
->win32_source_lock
, timeout
))
3911 res
= WSA_WAIT_TIMEOUT
;
3916 res
= socket
->priv
->waiting_result
;
3921 g_cond_wait (&socket
->priv
->win32_source_cond
, &socket
->priv
->win32_source_lock
);
3922 res
= socket
->priv
->waiting_result
;
3926 if (res
== WSA_WAIT_FAILED
)
3928 int errsv
= get_socket_errno ();
3930 g_set_error (error
, G_IO_ERROR
,
3931 socket_io_error_from_errno (errsv
),
3932 _("Waiting for socket condition: %s"),
3933 socket_strerror (errsv
));
3936 else if (res
== WSA_WAIT_TIMEOUT
)
3938 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
,
3939 _("Socket I/O timed out"));
3943 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
3946 current_condition
= update_condition_unlocked (socket
);
3948 if (timeout
!= WSA_INFINITE
)
3950 timeout
-= (g_get_monotonic_time () - start_time
) * 1000;
3955 g_mutex_unlock (&socket
->priv
->win32_source_lock
);
3956 remove_condition_watch (socket
, &condition
);
3958 g_cancellable_release_fd (cancellable
);
3960 return (condition
& current_condition
) != 0;
3968 poll_fd
[0].fd
= socket
->priv
->fd
;
3969 poll_fd
[0].events
= condition
;
3972 if (g_cancellable_make_pollfd (cancellable
, &poll_fd
[1]))
3977 result
= g_poll (poll_fd
, num
, timeout
);
3978 if (result
!= -1 || errno
!= EINTR
)
3983 timeout
-= (g_get_monotonic_time () - start_time
) / 1000;
3990 g_cancellable_release_fd (cancellable
);
3994 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
,
3995 _("Socket I/O timed out"));
3999 return !g_cancellable_set_error_if_cancelled (cancellable
, error
);
4006 /* Unfortunately these have to be macros rather than inline functions due to
4007 * using alloca(). */
4008 #define output_message_to_msghdr(message, prev_message, msg, prev_msg, error) \
4010 const GOutputMessage *_message = (message); \
4011 const GOutputMessage *_prev_message = (prev_message); \
4012 struct msghdr *_msg = (msg); \
4013 const struct msghdr *_prev_msg = (prev_msg); \
4014 GError **_error = (error); \
4016 _msg->msg_flags = 0; \
4019 if (_prev_message != NULL && _prev_message->address == _message->address) \
4021 _msg->msg_name = _prev_msg->msg_name; \
4022 _msg->msg_namelen = _prev_msg->msg_namelen; \
4024 else if (_message->address != NULL) \
4026 _msg->msg_namelen = g_socket_address_get_native_size (_message->address); \
4027 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4028 if (!g_socket_address_to_native (_message->address, _msg->msg_name, \
4029 _msg->msg_namelen, _error)) \
4034 _msg->msg_name = NULL; \
4035 _msg->msg_namelen = 0; \
4040 /* this entire expression will be evaluated at compile time */ \
4041 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4042 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4043 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4044 G_STRUCT_OFFSET (GOutputVector, buffer) && \
4045 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4046 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4047 G_STRUCT_OFFSET (GOutputVector, size)) \
4048 /* ABI is compatible */ \
4050 _msg->msg_iov = (struct iovec *) _message->vectors; \
4051 _msg->msg_iovlen = _message->num_vectors; \
4054 /* ABI is incompatible */ \
4058 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4059 for (i = 0; i < _message->num_vectors; i++) \
4061 _msg->msg_iov[i].iov_base = (void *) _message->vectors[i].buffer; \
4062 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4064 _msg->msg_iovlen = _message->num_vectors; \
4070 struct cmsghdr *cmsg; \
4073 _msg->msg_controllen = 0; \
4074 for (i = 0; i < _message->num_control_messages; i++) \
4075 _msg->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (_message->control_messages[i])); \
4077 if (_msg->msg_controllen == 0) \
4078 _msg->msg_control = NULL; \
4081 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4082 memset (_msg->msg_control, '\0', _msg->msg_controllen); \
4085 cmsg = CMSG_FIRSTHDR (_msg); \
4086 for (i = 0; i < _message->num_control_messages; i++) \
4088 cmsg->cmsg_level = g_socket_control_message_get_level (_message->control_messages[i]); \
4089 cmsg->cmsg_type = g_socket_control_message_get_msg_type (_message->control_messages[i]); \
4090 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (_message->control_messages[i])); \
4091 g_socket_control_message_serialize (_message->control_messages[i], \
4092 CMSG_DATA (cmsg)); \
4093 cmsg = CMSG_NXTHDR (_msg, cmsg); \
4095 g_assert (cmsg == NULL); \
4099 #define input_message_to_msghdr(message, msg) \
4101 const GInputMessage *_message = (message); \
4102 struct msghdr *_msg = (msg); \
4105 if (_message->address) \
4107 _msg->msg_namelen = sizeof (struct sockaddr_storage); \
4108 _msg->msg_name = g_alloca (_msg->msg_namelen); \
4112 _msg->msg_name = NULL; \
4113 _msg->msg_namelen = 0; \
4117 /* this entire expression will be evaluated at compile time */ \
4118 if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4119 sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4120 G_STRUCT_OFFSET (struct iovec, iov_base) == \
4121 G_STRUCT_OFFSET (GInputVector, buffer) && \
4122 sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4123 G_STRUCT_OFFSET (struct iovec, iov_len) == \
4124 G_STRUCT_OFFSET (GInputVector, size)) \
4125 /* ABI is compatible */ \
4127 _msg->msg_iov = (struct iovec *) _message->vectors; \
4128 _msg->msg_iovlen = _message->num_vectors; \
4131 /* ABI is incompatible */ \
4135 _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4136 for (i = 0; i < _message->num_vectors; i++) \
4138 _msg->msg_iov[i].iov_base = _message->vectors[i].buffer; \
4139 _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4141 _msg->msg_iovlen = _message->num_vectors; \
4145 if (_message->control_messages == NULL) \
4147 _msg->msg_controllen = 0; \
4148 _msg->msg_control = NULL; \
4152 _msg->msg_controllen = 2048; \
4153 _msg->msg_control = g_alloca (_msg->msg_controllen); \
4157 _msg->msg_flags = _message->flags; \
4161 input_message_from_msghdr (const struct msghdr
*msg
,
4162 GInputMessage
*message
,
4165 /* decode address */
4166 if (message
->address
!= NULL
)
4168 *message
->address
= cache_recv_address (socket
, msg
->msg_name
,
4172 /* decode control messages */
4174 GPtrArray
*my_messages
= NULL
;
4175 struct cmsghdr
*cmsg
;
4177 if (msg
->msg_controllen
>= sizeof (struct cmsghdr
))
4179 g_assert (message
->control_messages
!= NULL
);
4180 for (cmsg
= CMSG_FIRSTHDR (msg
);
4182 cmsg
= CMSG_NXTHDR ((struct msghdr
*) msg
, cmsg
))
4184 GSocketControlMessage
*control_message
;
4186 control_message
= g_socket_control_message_deserialize (cmsg
->cmsg_level
,
4188 cmsg
->cmsg_len
- ((char *)CMSG_DATA (cmsg
) - (char *)cmsg
),
4190 if (control_message
== NULL
)
4191 /* We've already spewed about the problem in the
4192 deserialization code, so just continue */
4195 if (my_messages
== NULL
)
4196 my_messages
= g_ptr_array_new ();
4197 g_ptr_array_add (my_messages
, control_message
);
4201 if (message
->num_control_messages
)
4202 *message
->num_control_messages
= my_messages
!= NULL
? my_messages
->len
: 0;
4204 if (message
->control_messages
)
4206 if (my_messages
== NULL
)
4208 *message
->control_messages
= NULL
;
4212 g_ptr_array_add (my_messages
, NULL
);
4213 *message
->control_messages
= (GSocketControlMessage
**) g_ptr_array_free (my_messages
, FALSE
);
4218 g_assert (my_messages
== NULL
);
4222 /* capture the flags */
4223 message
->flags
= msg
->msg_flags
;
4228 * g_socket_send_message:
4229 * @socket: a #GSocket
4230 * @address: (nullable): a #GSocketAddress, or %NULL
4231 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4232 * @num_vectors: the number of elements in @vectors, or -1
4233 * @messages: (array length=num_messages) (nullable): a pointer to an
4234 * array of #GSocketControlMessages, or %NULL.
4235 * @num_messages: number of elements in @messages, or -1.
4236 * @flags: an int containing #GSocketMsgFlags flags
4237 * @cancellable: (nullable): a %GCancellable or %NULL
4238 * @error: #GError for error reporting, or %NULL to ignore.
4240 * Send data to @address on @socket. For sending multiple messages see
4241 * g_socket_send_messages(); for easier use, see
4242 * g_socket_send() and g_socket_send_to().
4244 * If @address is %NULL then the message is sent to the default receiver
4245 * (set by g_socket_connect()).
4247 * @vectors must point to an array of #GOutputVector structs and
4248 * @num_vectors must be the length of this array. (If @num_vectors is -1,
4249 * then @vectors is assumed to be terminated by a #GOutputVector with a
4250 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
4251 * that the sent data will be gathered from. Using multiple
4252 * #GOutputVectors is more memory-efficient than manually copying
4253 * data from multiple sources into a single buffer, and more
4254 * network-efficient than making multiple calls to g_socket_send().
4256 * @messages, if non-%NULL, is taken to point to an array of @num_messages
4257 * #GSocketControlMessage instances. These correspond to the control
4258 * messages to be sent on the socket.
4259 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
4262 * @flags modify how the message is sent. The commonly available arguments
4263 * for this are available in the #GSocketMsgFlags enum, but the
4264 * values there are the same as the system values, and the flags
4265 * are passed in as-is, so you can pass in system-specific flags too.
4267 * If the socket is in blocking mode the call will block until there is
4268 * space for the data in the socket queue. If there is no space available
4269 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4270 * will be returned. To be notified when space is available, wait for the
4271 * %G_IO_OUT condition. Note though that you may still receive
4272 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4273 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4274 * very common due to the way the underlying APIs work.)
4276 * On error -1 is returned and @error is set accordingly.
4278 * Returns: Number of bytes written (which may be less than @size), or -1
4284 g_socket_send_message (GSocket
*socket
,
4285 GSocketAddress
*address
,
4286 GOutputVector
*vectors
,
4288 GSocketControlMessage
**messages
,
4291 GCancellable
*cancellable
,
4294 return g_socket_send_message_with_timeout (socket
, address
,
4295 vectors
, num_vectors
,
4296 messages
, num_messages
, flags
,
4297 socket
->priv
->blocking
? -1 : 0,
4298 cancellable
, error
);
4302 g_socket_send_message_with_timeout (GSocket
*socket
,
4303 GSocketAddress
*address
,
4304 GOutputVector
*vectors
,
4306 GSocketControlMessage
**messages
,
4310 GCancellable
*cancellable
,
4313 GOutputVector one_vector
;
4317 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
4318 g_return_val_if_fail (address
== NULL
|| G_IS_SOCKET_ADDRESS (address
), -1);
4319 g_return_val_if_fail (num_vectors
== 0 || vectors
!= NULL
, -1);
4320 g_return_val_if_fail (num_messages
== 0 || messages
!= NULL
, -1);
4321 g_return_val_if_fail (cancellable
== NULL
|| G_IS_CANCELLABLE (cancellable
), -1);
4322 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, -1);
4324 start_time
= g_get_monotonic_time ();
4326 if (!check_socket (socket
, error
))
4329 if (!check_timeout (socket
, error
))
4332 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
4335 if (num_vectors
== -1)
4337 for (num_vectors
= 0;
4338 vectors
[num_vectors
].buffer
!= NULL
;
4343 if (num_messages
== -1)
4345 for (num_messages
= 0;
4346 messages
!= NULL
&& messages
[num_messages
] != NULL
;
4351 if (num_vectors
== 0)
4355 one_vector
.buffer
= &zero
;
4356 one_vector
.size
= 1;
4358 vectors
= &one_vector
;
4363 GOutputMessage output_message
;
4366 GError
*child_error
= NULL
;
4368 output_message
.address
= address
;
4369 output_message
.vectors
= vectors
;
4370 output_message
.num_vectors
= num_vectors
;
4371 output_message
.bytes_sent
= 0;
4372 output_message
.control_messages
= messages
;
4373 output_message
.num_control_messages
= num_messages
;
4375 output_message_to_msghdr (&output_message
, NULL
, &msg
, NULL
, &child_error
);
4377 if (child_error
!= NULL
)
4379 g_propagate_error (error
, child_error
);
4385 result
= sendmsg (socket
->priv
->fd
, &msg
, flags
| G_SOCKET_DEFAULT_SEND_FLAGS
);
4388 int errsv
= get_socket_errno ();
4394 (errsv
== EWOULDBLOCK
||
4397 if (!block_on_timeout (socket
, G_IO_OUT
, timeout
, start_time
,
4398 cancellable
, error
))
4404 socket_set_error_lazy (error
, errsv
, _("Error sending message: %s"));
4414 struct sockaddr_storage addr
;
4421 /* Win32 doesn't support control messages.
4422 Actually this is possible for raw and datagram sockets
4423 via WSASendMessage on Vista or later, but that doesn't
4425 if (num_messages
!= 0)
4427 g_set_error_literal (error
, G_IO_ERROR
, G_IO_ERROR_NOT_SUPPORTED
,
4428 _("GSocketControlMessage not supported on Windows"));
4433 bufs
= g_newa (WSABUF
, num_vectors
);
4434 for (i
= 0; i
< num_vectors
; i
++)
4436 bufs
[i
].buf
= (char *)vectors
[i
].buffer
;
4437 bufs
[i
].len
= (gulong
)vectors
[i
].size
;
4441 addrlen
= 0; /* Avoid warning */
4444 addrlen
= g_socket_address_get_native_size (address
);
4445 if (!g_socket_address_to_native (address
, &addr
, sizeof addr
, error
))
4451 win32_unset_event_mask (socket
, FD_WRITE
);
4454 result
= WSASendTo (socket
->priv
->fd
,
4457 (const struct sockaddr
*)&addr
, addrlen
,
4460 result
= WSASend (socket
->priv
->fd
,
4467 int errsv
= get_socket_errno ();
4469 if (errsv
== WSAEINTR
)
4472 if (errsv
== WSAEWOULDBLOCK
)
4476 if (!block_on_timeout (socket
, G_IO_OUT
, timeout
,
4477 start_time
, cancellable
, error
))
4484 socket_set_error_lazy (error
, errsv
, _("Error sending message: %s"));
4496 * g_socket_send_messages:
4497 * @socket: a #GSocket
4498 * @messages: (array length=num_messages): an array of #GOutputMessage structs
4499 * @num_messages: the number of elements in @messages
4500 * @flags: an int containing #GSocketMsgFlags flags
4501 * @cancellable: (nullable): a %GCancellable or %NULL
4502 * @error: #GError for error reporting, or %NULL to ignore.
4504 * Send multiple data messages from @socket in one go. This is the most
4505 * complicated and fully-featured version of this call. For easier use, see
4506 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
4508 * @messages must point to an array of #GOutputMessage structs and
4509 * @num_messages must be the length of this array. Each #GOutputMessage
4510 * contains an address to send the data to, and a pointer to an array of
4511 * #GOutputVector structs to describe the buffers that the data to be sent
4512 * for each message will be gathered from. Using multiple #GOutputVectors is
4513 * more memory-efficient than manually copying data from multiple sources
4514 * into a single buffer, and more network-efficient than making multiple
4515 * calls to g_socket_send(). Sending multiple messages in one go avoids the
4516 * overhead of making a lot of syscalls in scenarios where a lot of data
4517 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
4518 * or where the same data needs to be sent to multiple recipients.
4520 * @flags modify how the message is sent. The commonly available arguments
4521 * for this are available in the #GSocketMsgFlags enum, but the
4522 * values there are the same as the system values, and the flags
4523 * are passed in as-is, so you can pass in system-specific flags too.
4525 * If the socket is in blocking mode the call will block until there is
4526 * space for all the data in the socket queue. If there is no space available
4527 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4528 * will be returned if no data was written at all, otherwise the number of
4529 * messages sent will be returned. To be notified when space is available,
4530 * wait for the %G_IO_OUT condition. Note though that you may still receive
4531 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4532 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4533 * very common due to the way the underlying APIs work.)
4535 * On error -1 is returned and @error is set accordingly. An error will only
4536 * be returned if zero messages could be sent; otherwise the number of messages
4537 * successfully sent before the error will be returned.
4539 * Returns: number of messages sent, or -1 on error. Note that the number of
4540 * messages sent may be smaller than @num_messages if the socket is
4541 * non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
4542 * in which case the caller may re-try to send the remaining messages.
4547 g_socket_send_messages (GSocket
*socket
,
4548 GOutputMessage
*messages
,
4551 GCancellable
*cancellable
,
4554 return g_socket_send_messages_with_timeout (socket
, messages
, num_messages
,
4556 socket
->priv
->blocking
? -1 : 0,
4557 cancellable
, error
);
4561 g_socket_send_messages_with_timeout (GSocket
*socket
,
4562 GOutputMessage
*messages
,
4566 GCancellable
*cancellable
,
4571 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
4572 g_return_val_if_fail (num_messages
== 0 || messages
!= NULL
, -1);
4573 g_return_val_if_fail (cancellable
== NULL
|| G_IS_CANCELLABLE (cancellable
), -1);
4574 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, -1);
4576 start_time
= g_get_monotonic_time ();
4578 if (!check_socket (socket
, error
))
4581 if (!check_timeout (socket
, error
))
4584 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
4587 if (num_messages
== 0)
4590 #if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
4592 struct mmsghdr
*msgvec
;
4596 #define MAX_NUM_MESSAGES UIO_MAXIOV
4598 #define MAX_NUM_MESSAGES 1024
4601 if (num_messages
> MAX_NUM_MESSAGES
)
4602 num_messages
= MAX_NUM_MESSAGES
;
4604 msgvec
= g_newa (struct mmsghdr
, num_messages
);
4606 for (i
= 0; i
< num_messages
; ++i
)
4608 GOutputMessage
*msg
= &messages
[i
];
4609 struct msghdr
*msg_hdr
= &msgvec
[i
].msg_hdr
;
4610 GError
*child_error
= NULL
;
4612 msgvec
[i
].msg_len
= 0;
4614 output_message_to_msghdr (msg
, (i
> 0) ? &messages
[i
- 1] : NULL
,
4615 msg_hdr
, (i
> 0) ? &msgvec
[i
- 1].msg_hdr
: NULL
,
4618 if (child_error
!= NULL
)
4620 g_propagate_error (error
, child_error
);
4625 for (num_sent
= 0; num_sent
< num_messages
;)
4629 ret
= sendmmsg (socket
->priv
->fd
, msgvec
+ num_sent
, num_messages
- num_sent
,
4630 flags
| G_SOCKET_DEFAULT_SEND_FLAGS
);
4634 int errsv
= get_socket_errno ();
4640 (errsv
== EWOULDBLOCK
||
4643 if (!block_on_timeout (socket
, G_IO_OUT
, timeout
, start_time
,
4644 cancellable
, error
))
4648 g_clear_error (error
);
4658 /* If any messages were successfully sent, do not error. */
4662 socket_set_error_lazy (error
, errsv
, _("Error sending message: %s"));
4670 for (i
= 0; i
< num_sent
; ++i
)
4671 messages
[i
].bytes_sent
= msgvec
[i
].msg_len
;
4679 gint64 wait_timeout
;
4681 wait_timeout
= timeout
;
4683 for (i
= 0; i
< num_messages
; ++i
)
4685 GOutputMessage
*msg
= &messages
[i
];
4686 GError
*msg_error
= NULL
;
4688 result
= g_socket_send_message_with_timeout (socket
, msg
->address
,
4691 msg
->control_messages
,
4692 msg
->num_control_messages
,
4693 flags
, wait_timeout
,
4694 cancellable
, &msg_error
);
4696 /* check if we've timed out or how much time to wait at most */
4699 gint64 elapsed
= g_get_monotonic_time () - start_time
;
4700 wait_timeout
= MAX (timeout
- elapsed
, 1);
4705 /* if we couldn't send all messages, just return how many we did
4706 * manage to send, provided we managed to send at least one */
4709 g_error_free (msg_error
);
4714 g_propagate_error (error
, msg_error
);
4719 msg
->bytes_sent
= result
;
4727 static GSocketAddress
*
4728 cache_recv_address (GSocket
*socket
, struct sockaddr
*native
, int native_len
)
4730 GSocketAddress
*saddr
;
4732 guint64 oldest_time
= G_MAXUINT64
;
4733 gint oldest_index
= 0;
4735 if (native_len
<= 0)
4739 for (i
= 0; i
< RECV_ADDR_CACHE_SIZE
; i
++)
4741 GSocketAddress
*tmp
= socket
->priv
->recv_addr_cache
[i
].addr
;
4742 gpointer tmp_native
= socket
->priv
->recv_addr_cache
[i
].native
;
4743 gint tmp_native_len
= socket
->priv
->recv_addr_cache
[i
].native_len
;
4748 if (tmp_native_len
!= native_len
)
4751 if (memcmp (tmp_native
, native
, native_len
) == 0)
4753 saddr
= g_object_ref (tmp
);
4754 socket
->priv
->recv_addr_cache
[i
].last_used
= g_get_monotonic_time ();
4758 if (socket
->priv
->recv_addr_cache
[i
].last_used
< oldest_time
)
4760 oldest_time
= socket
->priv
->recv_addr_cache
[i
].last_used
;
4765 saddr
= g_socket_address_new_from_native (native
, native_len
);
4767 if (socket
->priv
->recv_addr_cache
[oldest_index
].addr
)
4769 g_object_unref (socket
->priv
->recv_addr_cache
[oldest_index
].addr
);
4770 g_free (socket
->priv
->recv_addr_cache
[oldest_index
].native
);
4773 socket
->priv
->recv_addr_cache
[oldest_index
].native
= g_memdup (native
, native_len
);
4774 socket
->priv
->recv_addr_cache
[oldest_index
].native_len
= native_len
;
4775 socket
->priv
->recv_addr_cache
[oldest_index
].addr
= g_object_ref (saddr
);
4776 socket
->priv
->recv_addr_cache
[oldest_index
].last_used
= g_get_monotonic_time ();
4782 g_socket_receive_message_with_timeout (GSocket
*socket
,
4783 GSocketAddress
**address
,
4784 GInputVector
*vectors
,
4786 GSocketControlMessage
***messages
,
4790 GCancellable
*cancellable
,
4793 GInputVector one_vector
;
4797 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
4799 start_time
= g_get_monotonic_time ();
4801 if (!check_socket (socket
, error
))
4804 if (!check_timeout (socket
, error
))
4807 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
4810 if (num_vectors
== -1)
4812 for (num_vectors
= 0;
4813 vectors
[num_vectors
].buffer
!= NULL
;
4818 if (num_vectors
== 0)
4820 one_vector
.buffer
= &one_byte
;
4821 one_vector
.size
= 1;
4823 vectors
= &one_vector
;
4828 GInputMessage input_message
;
4832 input_message
.address
= address
;
4833 input_message
.vectors
= vectors
;
4834 input_message
.num_vectors
= num_vectors
;
4835 input_message
.bytes_received
= 0;
4836 input_message
.flags
= (flags
!= NULL
) ? *flags
: 0;
4837 input_message
.control_messages
= messages
;
4838 input_message
.num_control_messages
= (guint
*) num_messages
;
4840 /* We always set the close-on-exec flag so we don't leak file
4841 * descriptors into child processes. Note that gunixfdmessage.c
4842 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4844 #ifdef MSG_CMSG_CLOEXEC
4845 input_message
.flags
|= MSG_CMSG_CLOEXEC
;
4848 input_message_to_msghdr (&input_message
, &msg
);
4853 result
= recvmsg (socket
->priv
->fd
, &msg
, msg
.msg_flags
);
4854 #ifdef MSG_CMSG_CLOEXEC
4855 if (result
< 0 && get_socket_errno () == EINVAL
)
4857 /* We must be running on an old kernel. Call without the flag. */
4858 msg
.msg_flags
&= ~(MSG_CMSG_CLOEXEC
);
4859 result
= recvmsg (socket
->priv
->fd
, &msg
, msg
.msg_flags
);
4865 int errsv
= get_socket_errno ();
4871 (errsv
== EWOULDBLOCK
||
4874 if (!block_on_timeout (socket
, G_IO_IN
, timeout
, start_time
,
4875 cancellable
, error
))
4881 socket_set_error_lazy (error
, errsv
, _("Error receiving message: %s"));
4887 input_message_from_msghdr (&msg
, &input_message
, socket
);
4890 *flags
= input_message
.flags
;
4896 struct sockaddr_storage addr
;
4898 DWORD bytes_received
;
4905 bufs
= g_newa (WSABUF
, num_vectors
);
4906 for (i
= 0; i
< num_vectors
; i
++)
4908 bufs
[i
].buf
= (char *)vectors
[i
].buffer
;
4909 bufs
[i
].len
= (gulong
)vectors
[i
].size
;
4921 win32_unset_event_mask (socket
, FD_READ
);
4923 addrlen
= sizeof addr
;
4925 result
= WSARecvFrom (socket
->priv
->fd
,
4927 &bytes_received
, &win_flags
,
4928 (struct sockaddr
*)&addr
, &addrlen
,
4931 result
= WSARecv (socket
->priv
->fd
,
4933 &bytes_received
, &win_flags
,
4937 int errsv
= get_socket_errno ();
4939 if (errsv
== WSAEINTR
)
4942 if (errsv
== WSAEWOULDBLOCK
)
4946 if (!block_on_timeout (socket
, G_IO_IN
, timeout
,
4947 start_time
, cancellable
, error
))
4954 socket_set_error_lazy (error
, errsv
, _("Error receiving message: %s"));
4960 /* decode address */
4961 if (address
!= NULL
)
4963 *address
= cache_recv_address (socket
, (struct sockaddr
*)&addr
, addrlen
);
4966 /* capture the flags */
4970 if (messages
!= NULL
)
4972 if (num_messages
!= NULL
)
4975 return bytes_received
;
4981 * g_socket_receive_messages:
4982 * @socket: a #GSocket
4983 * @messages: (array length=num_messages): an array of #GInputMessage structs
4984 * @num_messages: the number of elements in @messages
4985 * @flags: an int containing #GSocketMsgFlags flags for the overall operation
4986 * @cancellable: (nullable): a %GCancellable or %NULL
4987 * @error: #GError for error reporting, or %NULL to ignore
4989 * Receive multiple data messages from @socket in one go. This is the most
4990 * complicated and fully-featured version of this call. For easier use, see
4991 * g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
4993 * @messages must point to an array of #GInputMessage structs and
4994 * @num_messages must be the length of this array. Each #GInputMessage
4995 * contains a pointer to an array of #GInputVector structs describing the
4996 * buffers that the data received in each message will be written to. Using
4997 * multiple #GInputVectors is more memory-efficient than manually copying data
4998 * out of a single buffer to multiple sources, and more system-call-efficient
4999 * than making multiple calls to g_socket_receive(), such as in scenarios where
5000 * a lot of data packets need to be received (e.g. high-bandwidth video
5001 * streaming over RTP/UDP).
5003 * @flags modify how all messages are received. The commonly available
5004 * arguments for this are available in the #GSocketMsgFlags enum, but the
5005 * values there are the same as the system values, and the flags
5006 * are passed in as-is, so you can pass in system-specific flags too. These
5007 * flags affect the overall receive operation. Flags affecting individual
5008 * messages are returned in #GInputMessage.flags.
5010 * The other members of #GInputMessage are treated as described in its
5013 * If #GSocket:blocking is %TRUE the call will block until @num_messages have
5014 * been received, or the end of the stream is reached.
5016 * If #GSocket:blocking is %FALSE the call will return up to @num_messages
5017 * without blocking, or %G_IO_ERROR_WOULD_BLOCK if no messages are queued in the
5018 * operating system to be received.
5020 * In blocking mode, if #GSocket:timeout is positive and is reached before any
5021 * messages are received, %G_IO_ERROR_TIMED_OUT is returned, otherwise up to
5022 * @num_messages are returned. (Note: This is effectively the
5023 * behaviour of `MSG_WAITFORONE` with recvmmsg().)
5025 * To be notified when messages are available, wait for the
5026 * %G_IO_IN condition. Note though that you may still receive
5027 * %G_IO_ERROR_WOULD_BLOCK from g_socket_receive_messages() even if you were
5028 * previously notified of a %G_IO_IN condition.
5030 * If the remote peer closes the connection, any messages queued in the
5031 * operating system will be returned, and subsequent calls to
5032 * g_socket_receive_messages() will return 0 (with no error set).
5034 * On error -1 is returned and @error is set accordingly. An error will only
5035 * be returned if zero messages could be received; otherwise the number of
5036 * messages successfully received before the error will be returned.
5038 * Returns: number of messages received, or -1 on error. Note that the number
5039 * of messages received may be smaller than @num_messages if in non-blocking
5040 * mode, if the peer closed the connection, or if @num_messages
5041 * was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
5042 * to receive the remaining messages.
5047 g_socket_receive_messages (GSocket
*socket
,
5048 GInputMessage
*messages
,
5051 GCancellable
*cancellable
,
5054 if (!check_socket (socket
, error
) ||
5055 !check_timeout (socket
, error
))
5058 return g_socket_receive_messages_with_timeout (socket
, messages
, num_messages
,
5060 socket
->priv
->blocking
? -1 : 0,
5061 cancellable
, error
);
5065 g_socket_receive_messages_with_timeout (GSocket
*socket
,
5066 GInputMessage
*messages
,
5070 GCancellable
*cancellable
,
5075 g_return_val_if_fail (G_IS_SOCKET (socket
), -1);
5076 g_return_val_if_fail (num_messages
== 0 || messages
!= NULL
, -1);
5077 g_return_val_if_fail (cancellable
== NULL
||
5078 G_IS_CANCELLABLE (cancellable
), -1);
5079 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, -1);
5081 start_time
= g_get_monotonic_time ();
5083 if (!check_socket (socket
, error
))
5086 if (!check_timeout (socket
, error
))
5089 if (g_cancellable_set_error_if_cancelled (cancellable
, error
))
5092 if (num_messages
== 0)
5095 #if !defined (G_OS_WIN32) && defined (HAVE_RECVMMSG)
5097 struct mmsghdr
*msgvec
;
5098 guint i
, num_received
;
5101 #define MAX_NUM_MESSAGES UIO_MAXIOV
5103 #define MAX_NUM_MESSAGES 1024
5106 if (num_messages
> MAX_NUM_MESSAGES
)
5107 num_messages
= MAX_NUM_MESSAGES
;
5109 msgvec
= g_newa (struct mmsghdr
, num_messages
);
5111 for (i
= 0; i
< num_messages
; ++i
)
5113 GInputMessage
*msg
= &messages
[i
];
5114 struct msghdr
*msg_hdr
= &msgvec
[i
].msg_hdr
;
5116 input_message_to_msghdr (msg
, msg_hdr
);
5117 msgvec
[i
].msg_len
= 0;
5120 /* We always set the close-on-exec flag so we don't leak file
5121 * descriptors into child processes. Note that gunixfdmessage.c
5122 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5124 #ifdef MSG_CMSG_CLOEXEC
5125 flags
|= MSG_CMSG_CLOEXEC
;
5128 for (num_received
= 0; num_received
< num_messages
;)
5132 /* We operate in non-blocking mode and handle the timeout ourselves. */
5133 ret
= recvmmsg (socket
->priv
->fd
,
5134 msgvec
+ num_received
,
5135 num_messages
- num_received
,
5136 flags
| G_SOCKET_DEFAULT_SEND_FLAGS
, NULL
);
5137 #ifdef MSG_CMSG_CLOEXEC
5138 if (ret
< 0 && get_socket_errno () == EINVAL
)
5140 /* We must be running on an old kernel. Call without the flag. */
5141 flags
&= ~(MSG_CMSG_CLOEXEC
);
5142 ret
= recvmmsg (socket
->priv
->fd
,
5143 msgvec
+ num_received
,
5144 num_messages
- num_received
,
5145 flags
| G_SOCKET_DEFAULT_SEND_FLAGS
, NULL
);
5151 int errsv
= get_socket_errno ();
5157 (errsv
== EWOULDBLOCK
||
5160 if (!block_on_timeout (socket
, G_IO_IN
, timeout
, start_time
,
5161 cancellable
, error
))
5163 if (num_received
> 0)
5165 g_clear_error (error
);
5175 /* If any messages were successfully received, do not error. */
5176 if (num_received
> 0)
5179 socket_set_error_lazy (error
, errsv
,
5180 _("Error receiving message: %s"));
5190 num_received
+= ret
;
5193 for (i
= 0; i
< num_received
; ++i
)
5195 input_message_from_msghdr (&msgvec
[i
].msg_hdr
, &messages
[i
], socket
);
5196 messages
[i
].bytes_received
= msgvec
[i
].msg_len
;
5199 return num_received
;
5204 gint64 wait_timeout
;
5206 wait_timeout
= timeout
;
5208 for (i
= 0; i
< num_messages
; i
++)
5210 GInputMessage
*msg
= &messages
[i
];
5212 GError
*msg_error
= NULL
;
5214 msg
->flags
= flags
; /* in-out parameter */
5216 len
= g_socket_receive_message_with_timeout (socket
,
5220 msg
->control_messages
,
5221 (gint
*) msg
->num_control_messages
,
5227 /* check if we've timed out or how much time to wait at most */
5230 gint64 elapsed
= g_get_monotonic_time () - start_time
;
5231 wait_timeout
= MAX (timeout
- elapsed
, 1);
5235 msg
->bytes_received
= len
;
5238 (g_error_matches (msg_error
, G_IO_ERROR
, G_IO_ERROR_WOULD_BLOCK
) ||
5239 g_error_matches (msg_error
, G_IO_ERROR
, G_IO_ERROR_TIMED_OUT
)))
5241 g_clear_error (&msg_error
);
5245 if (msg_error
!= NULL
)
5247 g_propagate_error (error
, msg_error
);
5261 * g_socket_receive_message:
5262 * @socket: a #GSocket
5263 * @address: (out) (optional): a pointer to a #GSocketAddress
5265 * @vectors: (array length=num_vectors): an array of #GInputVector structs
5266 * @num_vectors: the number of elements in @vectors, or -1
5267 * @messages: (array length=num_messages) (out) (optional): a pointer which
5268 * may be filled with an array of #GSocketControlMessages, or %NULL
5269 * @num_messages: (out): a pointer which will be filled with the number of
5270 * elements in @messages, or %NULL
5271 * @flags: (inout): a pointer to an int containing #GSocketMsgFlags flags
5272 * @cancellable: a %GCancellable or %NULL
5273 * @error: a #GError pointer, or %NULL
5275 * Receive data from a socket. For receiving multiple messages, see
5276 * g_socket_receive_messages(); for easier use, see
5277 * g_socket_receive() and g_socket_receive_from().
5279 * If @address is non-%NULL then @address will be set equal to the
5280 * source address of the received packet.
5281 * @address is owned by the caller.
5283 * @vector must point to an array of #GInputVector structs and
5284 * @num_vectors must be the length of this array. These structs
5285 * describe the buffers that received data will be scattered into.
5286 * If @num_vectors is -1, then @vectors is assumed to be terminated
5287 * by a #GInputVector with a %NULL buffer pointer.
5289 * As a special case, if @num_vectors is 0 (in which case, @vectors
5290 * may of course be %NULL), then a single byte is received and
5291 * discarded. This is to facilitate the common practice of sending a
5292 * single '\0' byte for the purposes of transferring ancillary data.
5294 * @messages, if non-%NULL, will be set to point to a newly-allocated
5295 * array of #GSocketControlMessage instances or %NULL if no such
5296 * messages was received. These correspond to the control messages
5297 * received from the kernel, one #GSocketControlMessage per message
5298 * from the kernel. This array is %NULL-terminated and must be freed
5299 * by the caller using g_free() after calling g_object_unref() on each
5300 * element. If @messages is %NULL, any control messages received will
5303 * @num_messages, if non-%NULL, will be set to the number of control
5304 * messages received.
5306 * If both @messages and @num_messages are non-%NULL, then
5307 * @num_messages gives the number of #GSocketControlMessage instances
5308 * in @messages (ie: not including the %NULL terminator).
5310 * @flags is an in/out parameter. The commonly available arguments
5311 * for this are available in the #GSocketMsgFlags enum, but the
5312 * values there are the same as the system values, and the flags
5313 * are passed in as-is, so you can pass in system-specific flags too
5314 * (and g_socket_receive_message() may pass system-specific flags out).
5315 * Flags passed in to the parameter affect the receive operation; flags returned
5316 * out of it are relevant to the specific returned message.
5318 * As with g_socket_receive(), data may be discarded if @socket is
5319 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
5320 * provide enough buffer space to read a complete message. You can pass
5321 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
5322 * removing it from the receive queue, but there is no portable way to find
5323 * out the length of the message other than by reading it into a
5324 * sufficiently-large buffer.
5326 * If the socket is in blocking mode the call will block until there
5327 * is some data to receive, the connection is closed, or there is an
5328 * error. If there is no data available and the socket is in
5329 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
5330 * returned. To be notified when data is available, wait for the
5331 * %G_IO_IN condition.
5333 * On error -1 is returned and @error is set accordingly.
5335 * Returns: Number of bytes read, or 0 if the connection was closed by
5336 * the peer, or -1 on error
5341 g_socket_receive_message (GSocket
*socket
,
5342 GSocketAddress
**address
,
5343 GInputVector
*vectors
,
5345 GSocketControlMessage
***messages
,
5348 GCancellable
*cancellable
,
5351 return g_socket_receive_message_with_timeout (socket
, address
, vectors
,
5352 num_vectors
, messages
,
5353 num_messages
, flags
,
5354 socket
->priv
->blocking
? -1 : 0,
5355 cancellable
, error
);
5359 * g_socket_get_credentials:
5360 * @socket: a #GSocket.
5361 * @error: #GError for error reporting, or %NULL to ignore.
5363 * Returns the credentials of the foreign process connected to this
5364 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
5367 * If this operation isn't supported on the OS, the method fails with
5368 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
5369 * by reading the %SO_PEERCRED option on the underlying socket.
5371 * Other ways to obtain credentials from a foreign peer includes the
5372 * #GUnixCredentialsMessage type and
5373 * g_unix_connection_send_credentials() /
5374 * g_unix_connection_receive_credentials() functions.
5376 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
5377 * that must be freed with g_object_unref().
5382 g_socket_get_credentials (GSocket
*socket
,
5387 g_return_val_if_fail (G_IS_SOCKET (socket
), NULL
);
5388 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
5392 #if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
5396 guint8 native_creds_buf
[G_CREDENTIALS_NATIVE_SIZE
];
5397 socklen_t optlen
= sizeof (native_creds_buf
);
5399 if (getsockopt (socket
->priv
->fd
,
5405 ret
= g_credentials_new ();
5406 g_credentials_set_native (ret
,
5407 G_CREDENTIALS_NATIVE_TYPE
,
5411 #elif G_CREDENTIALS_USE_NETBSD_UNPCBID
5413 struct unpcbid cred
;
5414 socklen_t optlen
= sizeof (cred
);
5416 if (getsockopt (socket
->priv
->fd
,
5422 ret
= g_credentials_new ();
5423 g_credentials_set_native (ret
,
5424 G_CREDENTIALS_NATIVE_TYPE
,
5428 #elif G_CREDENTIALS_USE_SOLARIS_UCRED
5430 ucred_t
*ucred
= NULL
;
5432 if (getpeerucred (socket
->priv
->fd
, &ucred
) == 0)
5434 ret
= g_credentials_new ();
5435 g_credentials_set_native (ret
,
5436 G_CREDENTIALS_TYPE_SOLARIS_UCRED
,
5442 #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
5447 int errsv
= get_socket_errno ();
5451 socket_io_error_from_errno (errsv
),
5452 _("Unable to read socket credentials: %s"),
5453 socket_strerror (errsv
));
5458 g_set_error_literal (error
,
5460 G_IO_ERROR_NOT_SUPPORTED
,
5461 _("g_socket_get_credentials not implemented for this OS"));
5468 * g_socket_get_option:
5469 * @socket: a #GSocket
5470 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5471 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5472 * @value: (out): return location for the option value
5473 * @error: #GError for error reporting, or %NULL to ignore.
5475 * Gets the value of an integer-valued option on @socket, as with
5476 * getsockopt(). (If you need to fetch a non-integer-valued option,
5477 * you will need to call getsockopt() directly.)
5479 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5480 * header pulls in system headers that will define most of the
5481 * standard/portable socket options. For unusual socket protocols or
5482 * platform-dependent options, you may need to include additional
5485 * Note that even for socket options that are a single byte in size,
5486 * @value is still a pointer to a #gint variable, not a #guchar;
5487 * g_socket_get_option() will handle the conversion internally.
5489 * Returns: success or failure. On failure, @error will be set, and
5490 * the system error value (`errno` or WSAGetLastError()) will still
5491 * be set to the result of the getsockopt() call.
5496 g_socket_get_option (GSocket
*socket
,
5504 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
5507 size
= sizeof (gint
);
5508 if (getsockopt (socket
->priv
->fd
, level
, optname
, value
, &size
) != 0)
5510 int errsv
= get_socket_errno ();
5512 g_set_error_literal (error
,
5514 socket_io_error_from_errno (errsv
),
5515 socket_strerror (errsv
));
5517 /* Reset errno in case the caller wants to look at it */
5523 #if G_BYTE_ORDER == G_BIG_ENDIAN
5524 /* If the returned value is smaller than an int then we need to
5525 * slide it over into the low-order bytes of *value.
5527 if (size
!= sizeof (gint
))
5528 *value
= *value
>> (8 * (sizeof (gint
) - size
));
5535 * g_socket_set_option:
5536 * @socket: a #GSocket
5537 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
5538 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
5539 * @value: the value to set the option to
5540 * @error: #GError for error reporting, or %NULL to ignore.
5542 * Sets the value of an integer-valued option on @socket, as with
5543 * setsockopt(). (If you need to set a non-integer-valued option,
5544 * you will need to call setsockopt() directly.)
5546 * The [<gio/gnetworking.h>][gio-gnetworking.h]
5547 * header pulls in system headers that will define most of the
5548 * standard/portable socket options. For unusual socket protocols or
5549 * platform-dependent options, you may need to include additional
5552 * Returns: success or failure. On failure, @error will be set, and
5553 * the system error value (`errno` or WSAGetLastError()) will still
5554 * be set to the result of the setsockopt() call.
5559 g_socket_set_option (GSocket
*socket
,
5567 g_return_val_if_fail (G_IS_SOCKET (socket
), FALSE
);
5569 if (setsockopt (socket
->priv
->fd
, level
, optname
, &value
, sizeof (gint
)) == 0)
5572 #if !defined (__linux__) && !defined (G_OS_WIN32)
5573 /* Linux and Windows let you set a single-byte value from an int,
5574 * but most other platforms don't.
5576 if (errno
== EINVAL
&& value
>= SCHAR_MIN
&& value
<= CHAR_MAX
)
5578 #if G_BYTE_ORDER == G_BIG_ENDIAN
5579 value
= value
<< (8 * (sizeof (gint
) - 1));
5581 if (setsockopt (socket
->priv
->fd
, level
, optname
, &value
, 1) == 0)
5586 errsv
= get_socket_errno ();
5588 g_set_error_literal (error
,
5590 socket_io_error_from_errno (errsv
),
5591 socket_strerror (errsv
));