Gio.Socket¶
- Subclasses:
None
Methods¶
- Inherited:
GObject.Object (37), Gio.DatagramBased (5), Gio.Initable (2)
- Structs:
class |
|
class |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Virtual Methods¶
- Inherited:
Properties¶
Name |
Type |
Flags |
Short Description |
---|---|---|---|
r/w |
|||
r/w |
|||
r/w/co |
|||
r/w/co |
|||
r/w |
|||
r/w |
|||
r |
|||
r/w |
|||
r/w |
|||
r/w/co |
|||
r |
|||
r/w |
|||
r/w |
|||
r/w/co |
Signals¶
- Inherited:
Fields¶
- Inherited:
Name |
Type |
Access |
Description |
---|---|---|---|
parent_instance |
r |
Class Details¶
- class Gio.Socket(**kwargs)¶
- Bases:
- Abstract:
No
- Structure:
A
GSocket
is a low-level networking primitive. It is a more or less direct mapping of the BSD socket API in a portableGObject.Object
based API. It supports both the UNIX socket implementations and winsock2 on Windows.GSocket
is the platform independent base upon which the higher level network primitives are based. Applications are not typically meant to use it directly, but rather through classes like [class`Gio`.SocketClient], [class`Gio`.SocketService] and [class`Gio`.SocketConnection]. However there may be cases where direct use ofGSocket
is useful.GSocket
implements the [iface`Gio`.Initable] interface, so if it is manually constructed by e.g. [ctor`GObject`.Object.new] you must call [method`Gio`.Initable.init] and check the results before using the object. This is done automatically in [ctor`Gio`.Socket.new] and [ctor`Gio`.Socket.new_from_fd], so these functions can returnNULL
.Sockets operate in two general modes, blocking or non-blocking. When in blocking mode all operations (which don’t take an explicit blocking parameter) block until the requested operation is finished or there is an error. In non-blocking mode all calls that would block return immediately with a
G_IO_ERROR_WOULD_BLOCK
error. To know when a call would successfully run you can call [method`Gio`.Socket.condition_check], or [method`Gio`.Socket.condition_wait]. You can also use [method`Gio`.Socket.create_source] and attach it to a [type`GLib`.MainContext] to get callbacks when I/O is possible. Note that all sockets are always set to non blocking mode in the system, and blocking mode is emulated inGSocket
.When working in non-blocking mode applications should always be able to handle getting a
G_IO_ERROR_WOULD_BLOCK
error even when some other function said that I/O was possible. This can easily happen in case of a race condition in the application, but it can also happen for other reasons. For instance, on Windows a socket is always seen as writable until a write returnsG_IO_ERROR_WOULD_BLOCK
.``GSocket``s can be either connection oriented or datagram based. For connection oriented types you must first establish a connection by either connecting to an address or accepting a connection from another address. For connectionless socket types the target/source address is specified or received in each I/O operation.
All socket file descriptors are set to be close-on-exec.
Note that creating a
GSocket
causes the signalSIGPIPE
to be ignored for the remainder of the program. If you are writing a command-line utility that usesGSocket
, you may need to take into account the fact that your program will not automatically be killed if it tries to write tostdout
after it has been closed.Like most other APIs in GLib,
GSocket
is not inherently thread safe. To use aGSocket
concurrently from multiple threads, you must implement your own locking.- Nagle’s algorithm
Since GLib 2.80,
GSocket
will automatically set theTCP_NODELAY
option on allG_SOCKET_TYPE_STREAM
sockets. This disables Nagle’s algorithm as it typically does more harm than good on modern networks.If your application needs Nagle’s algorithm enabled, call [method`Gio`.Socket.set_option] after constructing a
GSocket
to enable it: ``c socket = g_socket_new (…, G_SOCKET_TYPE_STREAM, …); if (socket != NULL)- {
g_socket_set_option (socket, IPPROTO_TCP, TCP_NODELAY, FALSE, &local_error); // handle error if needed
}
New in version 2.22.
- classmethod new(family, type, protocol)[source]¶
- Parameters:
family (
Gio.SocketFamily
) – the socket family to use, e.g.Gio.SocketFamily.IPV4
.type (
Gio.SocketType
) – the socket type to use.protocol (
Gio.SocketProtocol
) – the id of the protocol to use, or 0 for default.
- Raises:
- Returns:
a
Gio.Socket
orNone
on error. Free the returned object withGObject.Object.unref
().- Return type:
Creates a new
Gio.Socket
with the defined family, type and protocol. If protocol is 0 (Gio.SocketProtocol.DEFAULT
) the default protocol type for the family and type is used.The protocol is a family and type specific int that specifies what kind of protocol to use.
Gio.SocketProtocol
lists several common ones. Many families only support one protocol, and use 0 for this, others support several and using 0 means to use the default protocol for the family and type.The protocol id is passed directly to the operating system, so you can use protocols not listed in
Gio.SocketProtocol
if you know the protocol number used for it.New in version 2.22.
- classmethod new_from_fd(fd)[source]¶
- Parameters:
fd (
int
) – a native socket file descriptor.- Raises:
- Returns:
a
Gio.Socket
orNone
on error. Free the returned object withGObject.Object.unref
().- Return type:
Creates a new
Gio.Socket
from a native file descriptor or winsock SOCKET handle.This reads all the settings from the file descriptor so that all properties should work. Note that the file descriptor will be set to non-blocking mode, independent on the blocking mode of the
Gio.Socket
.On success, the returned
Gio.Socket
takes ownership of fd. On failure, the caller must close fd themselves.Since GLib 2.46, it is no longer a fatal error to call this on a non-socket descriptor. Instead, a
GLib.Error
will be set with codeGio.IOErrorEnum.FAILED
New in version 2.22.
- accept(cancellable)[source]¶
- Parameters:
cancellable (
Gio.Cancellable
orNone
) – aGio.Cancellable
orNone
- Raises:
- Returns:
a new
Gio.Socket
, orNone
on error. Free the returned object withGObject.Object.unref
().- Return type:
Accept incoming connections on a connection-based socket. This removes the first outstanding connection request from the listening socket and creates a
Gio.Socket
object for it.The self must be bound to a local address with
Gio.Socket.bind
() and must be listening for incoming connections (Gio.Socket.listen
()).If there are no outstanding connections then the operation will block or return
Gio.IOErrorEnum.WOULD_BLOCK
if non-blocking I/O is enabled. To be notified of an incoming connection, wait for theGObject.IOCondition.IN
condition.New in version 2.22.
- bind(address, allow_reuse)[source]¶
- Parameters:
address (
Gio.SocketAddress
) – aGio.SocketAddress
specifying the local address.allow_reuse (
bool
) – whether to allow reusing this address
- Raises:
- Returns:
- Return type:
When a socket is created it is attached to an address family, but it doesn’t have an address in this family.
Gio.Socket.bind
() assigns the address (sometimes called name) of the socket.It is generally required to bind to a local address before you can receive connections. (See
Gio.Socket.listen
() andGio.Socket.accept
() ). In certain situations, you may also want to bind a socket that will be used to initiate connections, though this is not normally required.If self is a TCP socket, then allow_reuse controls the setting of the
SO_REUSEADDR
socket option; normally it should beTrue
for server sockets (sockets that you will eventually callGio.Socket.accept
() on), andFalse
for client sockets. (Failing to set this flag on a server socket may causeGio.Socket.bind
() to returnGio.IOErrorEnum.ADDRESS_IN_USE
if the server program is stopped and then immediately restarted.)If self is a UDP socket, then allow_reuse determines whether or not other UDP sockets can be bound to the same address at the same time. In particular, you can have several UDP sockets bound to the same address, and they will all receive all of the multicast and broadcast packets sent to that address. (The behavior of unicast UDP packets to an address with multiple listeners is not defined.)
New in version 2.22.
- check_connect_result()[source]¶
-
Checks and resets the pending connect error for the socket. This is used to check for errors when
Gio.Socket.connect
() is used in non-blocking mode.New in version 2.22.
- close()[source]¶
- Raises:
- Returns:
- Return type:
Closes the socket, shutting down any active connection.
Closing a socket does not wait for all outstanding I/O operations to finish, so the caller should not rely on them to be guaranteed to complete even if the close returns with no error.
Once the socket is closed, all other operations will return
Gio.IOErrorEnum.CLOSED
. Closing a socket multiple times will not return an error.Sockets will be automatically closed when the last reference is dropped, but you might want to call this function to make sure resources are released as early as possible.
Beware that due to the way that TCP works, it is possible for recently-sent data to be lost if either you close a socket while the
GObject.IOCondition.IN
condition is set, or else if the remote connection tries to send something to you after you close the socket but before it has finished reading all of the data you sent. There is no easy generic way to avoid this problem; the easiest fix is to design the network protocol such that the client will never send data “out of turn”. Another solution is for the server to half-close the connection by callingGio.Socket.shutdown
() with only the shutdown_write flag set, and then wait for the client to notice this and close its side of the connection, after which the server can safely callGio.Socket.close
(). (This is whatGio.TcpConnection
does if you callGio.TcpConnection.set_graceful_disconnect
(). But of course, this only works if the client will close its connection after the server does.)New in version 2.22.
- condition_check(condition)[source]¶
- Parameters:
condition (
GLib.IOCondition
) – aGObject.IOCondition
mask to check- Returns:
the GIOCondition mask of the current state
- Return type:
Checks on the readiness of self to perform operations. The operations specified in condition are checked for and masked against the currently-satisfied conditions on self. The result is returned.
Note that on Windows, it is possible for an operation to return
Gio.IOErrorEnum.WOULD_BLOCK
even immediately afterGio.Socket.condition_check
() has claimed that the socket is ready for writing. Rather than callingGio.Socket.condition_check
() and then writing to the socket if it succeeds, it is generally better to simply try writing to the socket right away, and try again later if the initial attempt returnsGio.IOErrorEnum.WOULD_BLOCK
.It is meaningless to specify
GObject.IOCondition.ERR
orGObject.IOCondition.HUP
in condition; these conditions will always be set in the output if they are true.This call never blocks.
New in version 2.22.
- condition_timed_wait(condition, timeout_us, cancellable)[source]¶
- Parameters:
condition (
GLib.IOCondition
) – aGObject.IOCondition
mask to wait fortimeout_us (
int
) – the maximum time (in microseconds) to wait, or -1cancellable (
Gio.Cancellable
orNone
) – aGio.Cancellable
, orNone
- Raises:
- Returns:
- Return type:
Waits for up to timeout_us microseconds for condition to become true on self. If the condition is met,
True
is returned.If cancellable is cancelled before the condition is met, or if timeout_us (or the socket’s
Gio.Socket
:timeout
) is reached before the condition is met, thenFalse
is returned and error, if non-None
, is set to the appropriate value (Gio.IOErrorEnum.CANCELLED
orGio.IOErrorEnum.TIMED_OUT
).If you don’t want a timeout, use
Gio.Socket.condition_wait
(). (Alternatively, you can pass -1 for timeout_us.)Note that although timeout_us is in microseconds for consistency with other GLib APIs, this function actually only has millisecond resolution, and the behavior is undefined if timeout_us is not an exact number of milliseconds.
New in version 2.32.
- condition_wait(condition, cancellable)[source]¶
- Parameters:
condition (
GLib.IOCondition
) – aGObject.IOCondition
mask to wait forcancellable (
Gio.Cancellable
orNone
) – aGio.Cancellable
, orNone
- Raises:
- Returns:
- Return type:
Waits for condition to become true on self. When the condition is met,
True
is returned.If cancellable is cancelled before the condition is met, or if the socket has a timeout set and it is reached before the condition is met, then
False
is returned and error, if non-None
, is set to the appropriate value (Gio.IOErrorEnum.CANCELLED
orGio.IOErrorEnum.TIMED_OUT
).See also
Gio.Socket.condition_timed_wait
().New in version 2.22.
- connect(address, cancellable)[source]¶
- Parameters:
address (
Gio.SocketAddress
) – aGio.SocketAddress
specifying the remote address.cancellable (
Gio.Cancellable
orNone
) – aGio.Cancellable
orNone
- Raises:
- Returns:
- Return type:
Connect the socket to the specified remote address.
For connection oriented socket this generally means we attempt to make a connection to the address. For a connection-less socket it sets the default address for
Gio.Socket.send
() and discards all incoming datagrams from other sources.Generally connection oriented sockets can only connect once, but connection-less sockets can connect multiple times to change the default address.
If the connect call needs to do network I/O it will block, unless non-blocking I/O is enabled. Then
Gio.IOErrorEnum.PENDING
is returned and the user can be notified of the connection finishing by waiting for theGObject.IOCondition.OUT
condition. The result of the connection must then be checked withGio.Socket.check_connect_result
().New in version 2.22.
- connection_factory_create_connection()[source]¶
- Returns:
- Return type:
Creates a
Gio.SocketConnection
subclass of the right type for self.New in version 2.22.
- get_available_bytes()[source]¶
- Returns:
the number of bytes that can be read from the socket without blocking or truncating, or -1 on error.
- Return type:
Get the amount of data pending in the OS input buffer, without blocking.
If self is a UDP or SCTP socket, this will return the size of just the next packet, even if additional packets are buffered after that one.
Note that on Windows, this function is rather inefficient in the UDP case, and so if you know any plausible upper bound on the size of the incoming packet, it is better to just do a
Gio.Socket.receive
() with a buffer of that size, rather than callingGio.Socket.get_available_bytes
() first and then doing a receive of exactly the right size.New in version 2.32.
- get_blocking()[source]¶
-
Gets the blocking mode of the socket. For details on blocking I/O, see
Gio.Socket.set_blocking
().New in version 2.22.
- get_broadcast()[source]¶
- Returns:
the broadcast setting on self
- Return type:
Gets the broadcast setting on self; if
True
, it is possible to send packets to broadcast addresses.New in version 2.32.
- get_credentials()[source]¶
- Raises:
- Returns:
None
if error is set, otherwise aGio.Credentials
object that must be freed withGObject.Object.unref
().- Return type:
Returns the credentials of the foreign process connected to this socket, if any (e.g. it is only supported for
Gio.SocketFamily.UNIX
sockets).If this operation isn’t supported on the OS, the method fails with the
Gio.IOErrorEnum.NOT_SUPPORTED
error. On Linux this is implemented by reading the %SO_PEERCRED option on the underlying socket.This method can be expected to be available on the following platforms:
Linux since GLib 2.26
OpenBSD since GLib 2.30
Solaris, Illumos and OpenSolaris since GLib 2.40
NetBSD since GLib 2.42
macOS, tvOS, iOS since GLib 2.66
Other ways to obtain credentials from a foreign peer includes the
Gio.UnixCredentialsMessage
type andGio.UnixConnection.send_credentials
() /Gio.UnixConnection.receive_credentials
() functions.New in version 2.26.
- get_family()[source]¶
- Returns:
- Return type:
Gets the socket family of the socket.
New in version 2.22.
- get_fd()[source]¶
- Returns:
the file descriptor of the socket.
- Return type:
Returns the underlying OS socket object. On unix this is a socket file descriptor, and on Windows this is a Winsock2 SOCKET handle. This may be useful for doing platform specific or otherwise unusual operations on the socket.
New in version 2.22.
- get_keepalive()[source]¶
-
Gets the keepalive mode of the socket. For details on this, see
Gio.Socket.set_keepalive
().New in version 2.22.
- get_listen_backlog()[source]¶
- Returns:
the maximum number of pending connections.
- Return type:
Gets the listen backlog setting of the socket. For details on this, see
Gio.Socket.set_listen_backlog
().New in version 2.22.
- get_local_address()[source]¶
- Raises:
- Returns:
a
Gio.SocketAddress
orNone
on error. Free the returned object withGObject.Object.unref
().- Return type:
Try to get the local address of a bound socket. This is only useful if the socket has been bound to a local address, either explicitly or implicitly when connecting.
New in version 2.22.
- get_multicast_loopback()[source]¶
- Returns:
the multicast loopback setting on self
- Return type:
Gets the multicast loopback setting on self; if
True
(the default), outgoing multicast packets will be looped back to multicast listeners on the same host.New in version 2.32.
- get_multicast_ttl()[source]¶
- Returns:
the multicast time-to-live setting on self
- Return type:
Gets the multicast time-to-live setting on self; see
Gio.Socket.set_multicast_ttl
() for more details.New in version 2.32.
- get_option(level, optname)[source]¶
- Parameters:
- Raises:
- Returns:
success or failure. On failure, error will be set, and the system error value (
errno
or WSAGetLastError()) will still be set to the result of the getsockopt() call.- value:
return location for the option value
- Return type:
Gets the value of an integer-valued option on self, as with getsockopt(). (If you need to fetch a non-integer-valued option, you will need to call getsockopt() directly.)
The ‘<gio/gnetworking.h> [gio-gnetworking.h]’ header pulls in system headers that will define most of the standard/portable socket options. For unusual socket protocols or platform-dependent options, you may need to include additional headers.
Note that even for socket options that are a single byte in size, value is still a pointer to a
int
variable, not a #guchar;Gio.Socket.get_option
() will handle the conversion internally.New in version 2.36.
- get_protocol()[source]¶
- Returns:
a protocol id, or -1 if unknown
- Return type:
Gets the socket protocol id the socket was created with. In case the protocol is unknown, -1 is returned.
New in version 2.22.
- get_remote_address()[source]¶
- Raises:
- Returns:
a
Gio.SocketAddress
orNone
on error. Free the returned object withGObject.Object.unref
().- Return type:
Try to get the remote address of a connected socket. This is only useful for connection oriented sockets that have been connected.
New in version 2.22.
- get_socket_type()[source]¶
- Returns:
- Return type:
Gets the socket type of the socket.
New in version 2.22.
- get_timeout()[source]¶
- Returns:
the timeout in seconds
- Return type:
Gets the timeout setting of the socket. For details on this, see
Gio.Socket.set_timeout
().New in version 2.26.
- get_ttl()[source]¶
- Returns:
the time-to-live setting on self
- Return type:
Gets the unicast time-to-live setting on self; see
Gio.Socket.set_ttl
() for more details.New in version 2.32.
- is_connected()[source]¶
-
Check whether the socket is connected. This is only useful for connection-oriented sockets.
If using
Gio.Socket.shutdown
(), this function will returnTrue
until the socket has been shut down for reading and writing. If you do a non-blocking connect, this function will not returnTrue
until after you callGio.Socket.check_connect_result
().New in version 2.22.
- join_multicast_group(group, source_specific, iface)[source]¶
- Parameters:
group (
Gio.InetAddress
) – aGio.InetAddress
specifying the group address to join.source_specific (
bool
) –True
if source-specific multicast should be used
- Raises:
- Returns:
- Return type:
Registers self to receive multicast messages sent to group. self must be a
Gio.SocketType.DATAGRAM
socket, and must have been bound to an appropriate interface and port withGio.Socket.bind
().If iface is
None
, the system will automatically pick an interface to bind to based on group.If source_specific is
True
, source-specific multicast as defined in RFC 4604 is used. Note that on older platforms this may fail with aGio.IOErrorEnum.NOT_SUPPORTED
error.To bind to a given source-specific multicast address, use
Gio.Socket.join_multicast_group_ssm
() instead.New in version 2.32.
- join_multicast_group_ssm(group, source_specific, iface)[source]¶
- Parameters:
group (
Gio.InetAddress
) – aGio.InetAddress
specifying the group address to join.source_specific (
Gio.InetAddress
orNone
) – aGio.InetAddress
specifying the source-specific multicast address orNone
to ignore.
- Raises:
- Returns:
- Return type:
Registers self to receive multicast messages sent to group. self must be a
Gio.SocketType.DATAGRAM
socket, and must have been bound to an appropriate interface and port withGio.Socket.bind
().If iface is
None
, the system will automatically pick an interface to bind to based on group.If source_specific is not
None
, use source-specific multicast as defined in RFC 4604. Note that on older platforms this may fail with aGio.IOErrorEnum.NOT_SUPPORTED
error.Note that this function can be called multiple times for the same group with different source_specific in order to receive multicast packets from more than one source.
New in version 2.56.
- leave_multicast_group(group, source_specific, iface)[source]¶
- Parameters:
group (
Gio.InetAddress
) – aGio.InetAddress
specifying the group address to leave.source_specific (
bool
) –True
if source-specific multicast was used
- Raises:
- Returns:
- Return type:
Removes self from the multicast group defined by group, iface, and source_specific (which must all have the same values they had when you joined the group).
self remains bound to its address and port, and can still receive unicast messages after calling this.
To unbind to a given source-specific multicast address, use
Gio.Socket.leave_multicast_group_ssm
() instead.New in version 2.32.
- leave_multicast_group_ssm(group, source_specific, iface)[source]¶
- Parameters:
group (
Gio.InetAddress
) – aGio.InetAddress
specifying the group address to leave.source_specific (
Gio.InetAddress
orNone
) – aGio.InetAddress
specifying the source-specific multicast address orNone
to ignore.
- Raises:
- Returns:
- Return type:
Removes self from the multicast group defined by group, iface, and source_specific (which must all have the same values they had when you joined the group).
self remains bound to its address and port, and can still receive unicast messages after calling this.
New in version 2.56.
- listen()[source]¶
- Raises:
- Returns:
- Return type:
Marks the socket as a server socket, i.e. a socket that is used to accept incoming requests using
Gio.Socket.accept
().Before calling this the socket must be bound to a local address using
Gio.Socket.bind
().To set the maximum amount of outstanding clients, use
Gio.Socket.set_listen_backlog
().New in version 2.22.
- receive(cancellable)[source]¶
- Parameters:
cancellable (
Gio.Cancellable
orNone
) – aGio.Cancellable
orNone
- Raises:
- Returns:
Number of bytes read, or 0 if the connection was closed by the peer, or -1 on error
- buffer:
a buffer to read data into (which should be at least size bytes long).
- Return type:
Receive data (up to size bytes) from a socket. This is mainly used by connection-oriented sockets; it is identical to
Gio.Socket.receive_from
() with address set toNone
.For
Gio.SocketType.DATAGRAM
andGio.SocketType.SEQPACKET
sockets,Gio.Socket.receive
() will always read either 0 or 1 complete messages from the socket. If the received message is too large to fit in buffer, then the data beyond size bytes will be discarded, without any explicit indication that this has occurred.For
Gio.SocketType.STREAM
sockets,Gio.Socket.receive
() can return any number of bytes, up to size. If more than size bytes have been received, the additional data will be returned in future calls toGio.Socket.receive
().If the socket is in blocking mode the call will block until there is some data to receive, the connection is closed, or there is an error. If there is no data available and the socket is in non-blocking mode, a
Gio.IOErrorEnum.WOULD_BLOCK
error will be returned. To be notified when data is available, wait for theGObject.IOCondition.IN
condition.On error -1 is returned and error is set accordingly.
New in version 2.22.
- receive_bytes(size, timeout_us, cancellable)[source]¶
- Parameters:
size (
int
) – the number of bytes you want to read from the sockettimeout_us (
int
) – the timeout to wait for, in microseconds, or-1
to block indefinitelycancellable (
Gio.Cancellable
orNone
) – aGio.Cancellable
, orNULL
- Raises:
- Returns:
a bytes buffer containing the received bytes, or
NULL
on error- Return type:
Receives data (up to size bytes) from a socket.
This function is a variant of [method`Gio`.Socket.receive] which returns a [struct`GLib`.Bytes] rather than a plain buffer.
Pass
-1
to timeout_us to block indefinitely until data is received (or the connection is closed, or there is an error). Pass0
to use the default timeout from [property`Gio`.Socket:timeout], or pass a positive number to wait for that many microseconds for data before returningG_IO_ERROR_TIMED_OUT
.New in version 2.80.
- receive_bytes_from(size, timeout_us, cancellable)[source]¶
- Parameters:
size (
int
) – the number of bytes you want to read from the sockettimeout_us (
int
) – the timeout to wait for, in microseconds, or-1
to block indefinitelycancellable (
Gio.Cancellable
orNone
) – aGio.Cancellable
, orNULL
- Raises:
- Returns:
a bytes buffer containing the received bytes, or
NULL
on error- address:
return location for a
Gio.SocketAddress
- Return type:
(
GLib.Bytes
, address:Gio.SocketAddress
)
Receive data (up to size bytes) from a socket.
This function is a variant of [method`Gio`.Socket.receive_from] which returns a [struct`GLib`.Bytes] rather than a plain buffer.
If address is non-
None
then address will be set equal to the source address of the received packet.The address is owned by the caller.
Pass
-1
to timeout_us to block indefinitely until data is received (or the connection is closed, or there is an error). Pass0
to use the default timeout from [property`Gio`.Socket:timeout], or pass a positive number to wait for that many microseconds for data before returningG_IO_ERROR_TIMED_OUT
.New in version 2.80.
- receive_from(cancellable)[source]¶
- Parameters:
cancellable (
Gio.Cancellable
orNone
) – aGio.Cancellable
orNone
- Raises:
- Returns:
Number of bytes read, or 0 if the connection was closed by the peer, or -1 on error
- address:
a pointer to a
Gio.SocketAddress
pointer, orNone
- buffer:
a buffer to read data into (which should be at least size bytes long).
- Return type:
(
int
, address:Gio.SocketAddress
, buffer:bytes
)
Receive data (up to size bytes) from a socket.
If address is non-
None
then address will be set equal to the source address of the received packet. address is owned by the caller.See
Gio.Socket.receive
() for additional information.New in version 2.22.
- receive_message(vectors, flags, cancellable)[source]¶
- Parameters:
vectors ([
Gio.InputVector
]) – an array ofGio.InputVector
structsflags (
int
) – a pointer to an int containingGio.SocketMsgFlags
flags, which may additionally contain other platform specific flagscancellable (
Gio.Cancellable
orNone
) – aGio.Cancellable
orNone
- Raises:
- Returns:
Number of bytes read, or 0 if the connection was closed by the peer, or -1 on error
- address:
a pointer to a
Gio.SocketAddress
pointer, orNone
- messages:
a pointer which may be filled with an array of
Gio.SocketControlMessages
, orNone
- flags:
a pointer to an int containing
Gio.SocketMsgFlags
flags, which may additionally contain other platform specific flags
- Return type:
(
int
, address:Gio.SocketAddress
, messages: [Gio.SocketControlMessage
], flags:int
)
Receive data from a socket. For receiving multiple messages, see
Gio.Socket.receive_messages
(); for easier use, seeGio.Socket.receive
() andGio.Socket.receive_from
().If address is non-
None
then address will be set equal to the source address of the received packet. address is owned by the caller.vector must point to an array of
Gio.InputVector
structs and num_vectors must be the length of this array. These structs describe the buffers that received data will be scattered into. If num_vectors is -1, then vectors is assumed to be terminated by aGio.InputVector
with aNone
buffer pointer.As a special case, if num_vectors is 0 (in which case, vectors may of course be
None
), then a single byte is received and discarded. This is to facilitate the common practice of sending a single ‘\0’ byte for the purposes of transferring ancillary data.messages, if non-
None
, will be set to point to a newly-allocated array ofGio.SocketControlMessage
instances orNone
if no such messages was received. These correspond to the control messages received from the kernel, oneGio.SocketControlMessage
per message from the kernel. This array isNone
-terminated and must be freed by the caller usingGLib.free
() after callingGObject.Object.unref
() on each element. If messages isNone
, any control messages received will be discarded.num_messages, if non-
None
, will be set to the number of control messages received.If both messages and num_messages are non-
None
, then num_messages gives the number ofGio.SocketControlMessage
instances in messages (ie: not including theNone
terminator).flags is an in/out parameter. The commonly available arguments for this are available in the
Gio.SocketMsgFlags
enum, but the values there are the same as the system values, and the flags are passed in as-is, so you can pass in system-specific flags too (andGio.Socket.receive_message
() may pass system-specific flags out). Flags passed in to the parameter affect the receive operation; flags returned out of it are relevant to the specific returned message.As with
Gio.Socket.receive
(), data may be discarded if self isGio.SocketType.DATAGRAM
orGio.SocketType.SEQPACKET
and you do not provide enough buffer space to read a complete message. You can passGio.SocketMsgFlags.PEEK
in flags to peek at the current message without removing it from the receive queue, but there is no portable way to find out the length of the message other than by reading it into a sufficiently-large buffer.If the socket is in blocking mode the call will block until there is some data to receive, the connection is closed, or there is an error. If there is no data available and the socket is in non-blocking mode, a
Gio.IOErrorEnum.WOULD_BLOCK
error will be returned. To be notified when data is available, wait for theGObject.IOCondition.IN
condition.On error -1 is returned and error is set accordingly.
New in version 2.22.
- receive_messages(messages, flags, cancellable)[source]¶
- Parameters:
messages ([
Gio.InputMessage
]) – an array ofGio.InputMessage
structsflags (
int
) – an int containingGio.SocketMsgFlags
flags for the overall operation, which may additionally contain other platform specific flagscancellable (
Gio.Cancellable
orNone
) – aGio.Cancellable
orNone
- Raises:
- Returns:
number of messages received, or -1 on error. Note that the number of messages received may be smaller than num_messages if in non-blocking mode, if the peer closed the connection, or if num_messages was larger than
UIO_MAXIOV
(1024), in which case the caller may re-try to receive the remaining messages.- Return type:
Receive multiple data messages from self in one go. This is the most complicated and fully-featured version of this call. For easier use, see
Gio.Socket.receive
(),Gio.Socket.receive_from
(), andGio.Socket.receive_message
().messages must point to an array of
Gio.InputMessage
structs and num_messages must be the length of this array. EachGio.InputMessage
contains a pointer to an array ofGio.InputVector
structs describing the buffers that the data received in each message will be written to. Using multipleGio.InputVectors
is more memory-efficient than manually copying data out of a single buffer to multiple sources, and more system-call-efficient than making multiple calls toGio.Socket.receive
(), such as in scenarios where a lot of data packets need to be received (e.g. high-bandwidth video streaming over RTP/UDP).flags modify how all messages are received. The commonly available arguments for this are available in the
Gio.SocketMsgFlags
enum, but the values there are the same as the system values, and the flags are passed in as-is, so you can pass in system-specific flags too. These flags affect the overall receive operation. Flags affecting individual messages are returned in Gio.InputMessage.flags.The other members of
Gio.InputMessage
are treated as described in its documentation.If
Gio.Socket
:blocking
isTrue
the call will block until num_messages have been received, or the end of the stream is reached.If
Gio.Socket
:blocking
isFalse
the call will return up to num_messages without blocking, orGio.IOErrorEnum.WOULD_BLOCK
if no messages are queued in the operating system to be received.In blocking mode, if
Gio.Socket
:timeout
is positive and is reached before any messages are received,Gio.IOErrorEnum.TIMED_OUT
is returned, otherwise up to num_messages are returned. (Note: This is effectively the behaviour ofMSG_WAITFORONE
with recvmmsg().)To be notified when messages are available, wait for the
GObject.IOCondition.IN
condition. Note though that you may still receiveGio.IOErrorEnum.WOULD_BLOCK
fromGio.Socket.receive_messages
() even if you were previously notified of aGObject.IOCondition.IN
condition.If the remote peer closes the connection, any messages queued in the operating system will be returned, and subsequent calls to
Gio.Socket.receive_messages
() will return 0 (with no error set).On error -1 is returned and error is set accordingly. An error will only be returned if zero messages could be received; otherwise the number of messages successfully received before the error will be returned.
New in version 2.48.
- receive_with_blocking(blocking, cancellable)[source]¶
- Parameters:
blocking (
bool
) – whether to do blocking or non-blocking I/Ocancellable (
Gio.Cancellable
orNone
) – aGio.Cancellable
orNone
- Raises:
- Returns:
Number of bytes read, or 0 if the connection was closed by the peer, or -1 on error
- buffer:
a buffer to read data into (which should be at least size bytes long).
- Return type:
This behaves exactly the same as
Gio.Socket.receive
(), except that the choice of blocking or non-blocking behavior is determined by the blocking argument rather than by self's properties.New in version 2.26.
- send(buffer, cancellable)[source]¶
- Parameters:
buffer (
bytes
) – the buffer containing the data to send.cancellable (
Gio.Cancellable
orNone
) – aGio.Cancellable
orNone
- Raises:
- Returns:
Number of bytes written (which may be less than size), or -1 on error
- Return type:
Tries to send size bytes from buffer on the socket. This is mainly used by connection-oriented sockets; it is identical to
Gio.Socket.send_to
() with address set toNone
.If the socket is in blocking mode the call will block until there is space for the data in the socket queue. If there is no space available and the socket is in non-blocking mode a
Gio.IOErrorEnum.WOULD_BLOCK
error will be returned. To be notified when space is available, wait for theGObject.IOCondition.OUT
condition. Note though that you may still receiveGio.IOErrorEnum.WOULD_BLOCK
fromGio.Socket.send
() even if you were previously notified of aGObject.IOCondition.OUT
condition. (On Windows in particular, this is very common due to the way the underlying APIs work.)On error -1 is returned and error is set accordingly.
New in version 2.22.
- send_message(address, vectors, messages, flags, cancellable)[source]¶
- Parameters:
address (
Gio.SocketAddress
orNone
) – aGio.SocketAddress
, orNone
vectors ([
Gio.OutputVector
]) – an array ofGio.OutputVector
structsmessages ([
Gio.SocketControlMessage
] orNone
) – a pointer to an array ofGio.SocketControlMessages
, orNone
.flags (
int
) – an int containingGio.SocketMsgFlags
flags, which may additionally contain other platform specific flagscancellable (
Gio.Cancellable
orNone
) – aGio.Cancellable
orNone
- Raises:
- Returns:
Number of bytes written (which may be less than size), or -1 on error
- Return type:
Send data to address on self. For sending multiple messages see
Gio.Socket.send_messages
(); for easier use, seeGio.Socket.send
() andGio.Socket.send_to
().If address is
None
then the message is sent to the default receiver (set byGio.Socket.connect
()).vectors must point to an array of
Gio.OutputVector
structs and num_vectors must be the length of this array. (If num_vectors is -1, then vectors is assumed to be terminated by aGio.OutputVector
with aNone
buffer pointer.) TheGio.OutputVector
structs describe the buffers that the sent data will be gathered from. Using multipleGio.OutputVectors
is more memory-efficient than manually copying data from multiple sources into a single buffer, and more network-efficient than making multiple calls toGio.Socket.send
().messages, if non-
None
, is taken to point to an array of num_messagesGio.SocketControlMessage
instances. These correspond to the control messages to be sent on the socket. If num_messages is -1 then messages is treated as aNone
-terminated array.flags modify how the message is sent. The commonly available arguments for this are available in the
Gio.SocketMsgFlags
enum, but the values there are the same as the system values, and the flags are passed in as-is, so you can pass in system-specific flags too.If the socket is in blocking mode the call will block until there is space for the data in the socket queue. If there is no space available and the socket is in non-blocking mode a
Gio.IOErrorEnum.WOULD_BLOCK
error will be returned. To be notified when space is available, wait for theGObject.IOCondition.OUT
condition. Note though that you may still receiveGio.IOErrorEnum.WOULD_BLOCK
fromGio.Socket.send
() even if you were previously notified of aGObject.IOCondition.OUT
condition. (On Windows in particular, this is very common due to the way the underlying APIs work.)The sum of the sizes of each
Gio.OutputVector
in vectors must not be greater thanGObject.G_MAXSSIZE
. If the message can be larger than this, then it is mandatory to use theGio.Socket.send_message_with_timeout
() function.On error -1 is returned and error is set accordingly.
New in version 2.22.
- send_message_with_timeout(address, vectors, messages, flags, timeout_us, cancellable)[source]¶
- Parameters:
address (
Gio.SocketAddress
orNone
) – aGio.SocketAddress
, orNone
vectors ([
Gio.OutputVector
]) – an array ofGio.OutputVector
structsmessages ([
Gio.SocketControlMessage
] orNone
) – a pointer to an array ofGio.SocketControlMessages
, orNone
.flags (
int
) – an int containingGio.SocketMsgFlags
flags, which may additionally contain other platform specific flagstimeout_us (
int
) – the maximum time (in microseconds) to wait, or -1cancellable (
Gio.Cancellable
orNone
) – aGio.Cancellable
orNone
- Raises:
- Returns:
Gio.PollableReturn.OK
if all data was successfully written,Gio.PollableReturn.WOULD_BLOCK
if the socket is currently not writable, orGio.PollableReturn.FAILED
if an error happened and error is set.- bytes_written:
location to store the number of bytes that were written to the socket
- Return type:
(
Gio.PollableReturn
, bytes_written:int
)
This behaves exactly the same as
Gio.Socket.send_message
(), except that the choice of timeout behavior is determined by the timeout_us argument rather than by self's properties.On error
Gio.PollableReturn.FAILED
is returned and error is set accordingly, or if the socket is currently not writableGio.PollableReturn.WOULD_BLOCK
is returned. bytes_written will contain 0 in both cases.New in version 2.60.
- send_messages(messages, flags, cancellable)[source]¶
- Parameters:
messages ([
Gio.OutputMessage
]) – an array ofGio.OutputMessage
structsflags (
int
) – an int containingGio.SocketMsgFlags
flags, which may additionally contain other platform specific flagscancellable (
Gio.Cancellable
orNone
) – aGio.Cancellable
orNone
- Raises:
- Returns:
number of messages sent, or -1 on error. Note that the number of messages sent may be smaller than num_messages if the socket is non-blocking or if num_messages was larger than UIO_MAXIOV (1024), in which case the caller may re-try to send the remaining messages.
- Return type:
Send multiple data messages from self in one go. This is the most complicated and fully-featured version of this call. For easier use, see
Gio.Socket.send
(),Gio.Socket.send_to
(), andGio.Socket.send_message
().messages must point to an array of
Gio.OutputMessage
structs and num_messages must be the length of this array. EachGio.OutputMessage
contains an address to send the data to, and a pointer to an array ofGio.OutputVector
structs to describe the buffers that the data to be sent for each message will be gathered from. Using multipleGio.OutputVectors
is more memory-efficient than manually copying data from multiple sources into a single buffer, and more network-efficient than making multiple calls toGio.Socket.send
(). Sending multiple messages in one go avoids the overhead of making a lot of syscalls in scenarios where a lot of data packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP), or where the same data needs to be sent to multiple recipients.flags modify how the message is sent. The commonly available arguments for this are available in the
Gio.SocketMsgFlags
enum, but the values there are the same as the system values, and the flags are passed in as-is, so you can pass in system-specific flags too.If the socket is in blocking mode the call will block until there is space for all the data in the socket queue. If there is no space available and the socket is in non-blocking mode a
Gio.IOErrorEnum.WOULD_BLOCK
error will be returned if no data was written at all, otherwise the number of messages sent will be returned. To be notified when space is available, wait for theGObject.IOCondition.OUT
condition. Note though that you may still receiveGio.IOErrorEnum.WOULD_BLOCK
fromGio.Socket.send
() even if you were previously notified of aGObject.IOCondition.OUT
condition. (On Windows in particular, this is very common due to the way the underlying APIs work.)On error -1 is returned and error is set accordingly. An error will only be returned if zero messages could be sent; otherwise the number of messages successfully sent before the error will be returned.
New in version 2.44.
- send_to(address, buffer, cancellable)[source]¶
- Parameters:
address (
Gio.SocketAddress
orNone
) – aGio.SocketAddress
, orNone
buffer (
bytes
) – the buffer containing the data to send.cancellable (
Gio.Cancellable
orNone
) – aGio.Cancellable
orNone
- Raises:
- Returns:
Number of bytes written (which may be less than size), or -1 on error
- Return type:
Tries to send size bytes from buffer to address. If address is
None
then the message is sent to the default receiver (set byGio.Socket.connect
()).See
Gio.Socket.send
() for additional information.New in version 2.22.
- send_with_blocking(buffer, blocking, cancellable)[source]¶
- Parameters:
buffer (
bytes
) – the buffer containing the data to send.blocking (
bool
) – whether to do blocking or non-blocking I/Ocancellable (
Gio.Cancellable
orNone
) – aGio.Cancellable
orNone
- Raises:
- Returns:
Number of bytes written (which may be less than size), or -1 on error
- Return type:
This behaves exactly the same as
Gio.Socket.send
(), except that the choice of blocking or non-blocking behavior is determined by the blocking argument rather than by self's properties.New in version 2.26.
- set_blocking(blocking)[source]¶
- Parameters:
blocking (
bool
) – Whether to use blocking I/O or not.
Sets the blocking mode of the socket. In blocking mode all operations (which don’t take an explicit blocking parameter) block until they succeed or there is an error. In non-blocking mode all functions return results immediately or with a
Gio.IOErrorEnum.WOULD_BLOCK
error.All sockets are created in blocking mode. However, note that the platform level socket is always non-blocking, and blocking mode is a
Gio.Socket
level feature.New in version 2.22.
- set_broadcast(broadcast)[source]¶
- Parameters:
broadcast (
bool
) – whether self should allow sending to broadcast addresses
Sets whether self should allow sending to broadcast addresses. This is
False
by default.New in version 2.32.
- set_keepalive(keepalive)[source]¶
- Parameters:
keepalive (
bool
) – Value for the keepalive flag
Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When this flag is set on a socket, the system will attempt to verify that the remote socket endpoint is still present if a sufficiently long period of time passes with no data being exchanged. If the system is unable to verify the presence of the remote endpoint, it will automatically close the connection.
This option is only functional on certain kinds of sockets. (Notably,
Gio.SocketProtocol.TCP
sockets.)The exact time between pings is system- and protocol-dependent, but will normally be at least two hours. Most commonly, you would set this flag on a server socket if you want to allow clients to remain idle for long periods of time, but also want to ensure that connections are eventually garbage-collected if clients crash or become unreachable.
New in version 2.22.
- set_listen_backlog(backlog)[source]¶
- Parameters:
backlog (
int
) – the maximum number of pending connections.
Sets the maximum number of outstanding connections allowed when listening on this socket. If more clients than this are connecting to the socket and the application is not handling them on time then the new connections will be refused.
Note that this must be called before
Gio.Socket.listen
() and has no effect if called after that.New in version 2.22.
- set_multicast_loopback(loopback)[source]¶
- Parameters:
loopback (
bool
) – whether self should receive messages sent to its multicast groups from the local host
Sets whether outgoing multicast packets will be received by sockets listening on that multicast address on the same host. This is
True
by default.New in version 2.32.
- set_multicast_ttl(ttl)[source]¶
- Parameters:
ttl (
int
) – the time-to-live value for all multicast datagrams on self
Sets the time-to-live for outgoing multicast datagrams on self. By default, this is 1, meaning that multicast packets will not leave the local network.
New in version 2.32.
- set_option(level, optname, value)[source]¶
- Parameters:
- Raises:
- Returns:
success or failure. On failure, error will be set, and the system error value (
errno
or WSAGetLastError()) will still be set to the result of the setsockopt() call.- Return type:
Sets the value of an integer-valued option on self, as with setsockopt(). (If you need to set a non-integer-valued option, you will need to call setsockopt() directly.)
The ‘<gio/gnetworking.h> [gio-gnetworking.h]’ header pulls in system headers that will define most of the standard/portable socket options. For unusual socket protocols or platform-dependent options, you may need to include additional headers.
New in version 2.36.
- set_timeout(timeout)[source]¶
- Parameters:
timeout (
int
) – the timeout for self, in seconds, or 0 for none
Sets the time in seconds after which I/O operations on self will time out if they have not yet completed.
On a blocking socket, this means that any blocking
Gio.Socket
operation will time out after timeout seconds of inactivity, returningGio.IOErrorEnum.TIMED_OUT
.On a non-blocking socket, calls to
Gio.Socket.condition_wait
() will also fail withGio.IOErrorEnum.TIMED_OUT
after the given time. Sources created with g_socket_create_source() will trigger after timeout seconds of inactivity, with the requested condition set, at which point callingGio.Socket.receive
(),Gio.Socket.send
(),Gio.Socket.check_connect_result
(), etc, will fail withGio.IOErrorEnum.TIMED_OUT
.If timeout is 0 (the default), operations will never time out on their own.
Note that if an I/O operation is interrupted by a signal, this may cause the timeout to be reset.
New in version 2.26.
- set_ttl(ttl)[source]¶
- Parameters:
ttl (
int
) – the time-to-live value for all unicast packets on self
Sets the time-to-live for outgoing unicast packets on self. By default the platform-specific default value is used.
New in version 2.32.
- shutdown(shutdown_read, shutdown_write)[source]¶
- Parameters:
- Raises:
- Returns:
- Return type:
Shut down part or all of a full-duplex connection.
If shutdown_read is
True
then the receiving side of the connection is shut down, and further reading is disallowed.If shutdown_write is
True
then the sending side of the connection is shut down, and further writing is disallowed.It is allowed for both shutdown_read and shutdown_write to be
True
.One example where it is useful to shut down only one side of a connection is graceful disconnect for TCP connections where you close the sending side, then wait for the other side to close the connection, thus ensuring that the other side saw all sent data.
New in version 2.22.
- speaks_ipv4()[source]¶
-
Checks if a socket is capable of speaking IPv4.
IPv4 sockets are capable of speaking IPv4. On some operating systems and under some combinations of circumstances IPv6 sockets are also capable of speaking IPv4. See RFC 3493 section 3.7 for more information.
No other types of sockets are currently considered as being capable of speaking IPv4.
New in version 2.22.
Property Details¶
- Gio.Socket.props.blocking¶
-
Whether I/O on this socket is blocking.
New in version 2.22.
- Gio.Socket.props.broadcast¶
-
Whether the socket should allow sending to broadcast addresses.
New in version 2.32.
- Gio.Socket.props.family¶
- Name:
family
- Type:
- Default Value:
- Flags:
The socket’s address family.
New in version 2.22.
- Gio.Socket.props.fd¶
- Name:
fd
- Type:
- Default Value:
-1
- Flags:
The socket’s file descriptor.
New in version 2.22.
- Gio.Socket.props.keepalive¶
-
Whether to keep the connection alive by sending periodic pings.
New in version 2.22.
- Gio.Socket.props.listen_backlog¶
-
The number of outstanding connections in the listen queue.
New in version 2.22.
- Gio.Socket.props.local_address¶
- Name:
local-address
- Type:
- Default Value:
- Flags:
The local address the socket is bound to.
New in version 2.22.
- Gio.Socket.props.multicast_loopback¶
-
Whether outgoing multicast packets loop back to the local host.
New in version 2.32.
- Gio.Socket.props.multicast_ttl¶
-
Time-to-live out outgoing multicast packets
New in version 2.32.
- Gio.Socket.props.protocol¶
- Name:
protocol
- Type:
- Default Value:
- Flags:
The ID of the protocol to use, or
-1
for unknown.New in version 2.22.
- Gio.Socket.props.remote_address¶
- Name:
remote-address
- Type:
- Default Value:
- Flags:
The remote address the socket is connected to.
New in version 2.22.
- Gio.Socket.props.timeout¶
-
The timeout in seconds on socket I/O
New in version 2.26.
- Gio.Socket.props.ttl¶
-
Time-to-live for outgoing unicast packets
New in version 2.32.
- Gio.Socket.props.type¶
- Name:
type
- Type:
- Default Value:
- Flags:
The socket’s type.
New in version 2.22.