Socket#
Added in version 2.22.
Superclasses: Object
Implemented Interfaces: DatagramBased, Initable
A GSocket is a low-level networking primitive. It is a more or less
direct mapping of the BSD socket API in a portable GObject 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 SocketClient,
SocketService and SocketConnection. However there may
be cases where direct use of GSocket is useful.
GSocket implements the Initable interface, so if it is manually
constructed by e.g. new you must call
init and check the results before using the object.
This is done automatically in new and
new_from_fd, so these functions can return NULL.
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
condition_check, or condition_wait.
You can also use create_source and attach it to a
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 in GSocket.
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 returns G_IO_ERROR_WOULD_BLOCK.
GSockets 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 signal SIGPIPE to be
ignored for the remainder of the program. If you are writing a
command-line utility that uses GSocket, you may need to take into
account the fact that your program will not automatically be killed
if it tries to write to stdout after it has been closed.
Like most other APIs in GLib, GSocket is not inherently thread safe. To use
a GSocket concurrently from multiple threads, you must implement your own
locking.
Nagle’s algorithm#
Since GLib 2.80, GSocket will automatically set the TCP_NODELAY option on
all G_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
set_option after constructing a GSocket to enable it:
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
}
Constructors#
- class Socket
- classmethod new(family: SocketFamily, type: SocketType, protocol: SocketProtocol) Socket#
Creates a new
Socketwith the defined family, type and protocol. Ifprotocolis 0 (DEFAULT) the default protocol type for the family and type is used.The
protocolis a family and type specific int that specifies what kind of protocol to use.SocketProtocollists 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
SocketProtocolif you know the protocol number used for it.Added in version 2.22.
- Parameters:
family – the socket family to use, e.g.
IPV4.type – the socket type to use.
protocol – the id of the protocol to use, or 0 for default.
- classmethod new_from_fd(fd: int) Socket#
Creates a new
Socketfrom 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
Socket.On success, the returned
Sockettakes ownership offd. On failure, the caller must closefdthemselves.Since GLib 2.46, it is no longer a fatal error to call this on a non-socket descriptor. Instead, a GError will be set with code
FAILEDAdded in version 2.22.
- Parameters:
fd – a native socket file descriptor.
Methods#
- class Socket
- accept(cancellable: Cancellable | None = None) Socket#
Accept incoming connections on a connection-based socket. This removes the first outstanding connection request from the listening socket and creates a
Socketobject for it.The
socketmust be bound to a local address withbind()and must be listening for incoming connections (listen()).If there are no outstanding connections then the operation will block or return
WOULD_BLOCKif non-blocking I/O is enabled. To be notified of an incoming connection, wait for the %G_IO_IN condition.Added in version 2.22.
- Parameters:
cancellable – a %GCancellable or
None
- bind(address: SocketAddress, allow_reuse: bool) bool#
When a socket is created it is attached to an address family, but it doesn’t have an address in this family.
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
listen()andaccept()). 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
socketis a TCP socket, thenallow_reusecontrols the setting of theSO_REUSEADDRsocket option; normally it should beTruefor server sockets (sockets that you will eventually callaccept()on), andFalsefor client sockets. (Failing to set this flag on a server socket may causebind()to returnADDRESS_IN_USEif the server program is stopped and then immediately restarted.)If
socketis a UDP socket, thenallow_reusedetermines 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.)Added in version 2.22.
- Parameters:
address – a
SocketAddressspecifying the local address.allow_reuse – whether to allow reusing this address
- check_connect_result() bool#
Checks and resets the pending connect error for the socket. This is used to check for errors when
connect()is used in non-blocking mode.Added in version 2.22.
- close() bool#
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
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 %G_IO_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 calling
shutdown()with only theshutdown_writeflag set, and then wait for the client to notice this and close its side of the connection, after which the server can safely callclose(). (This is whatTcpConnectiondoes if you callset_graceful_disconnect(). But of course, this only works if the client will close its connection after the server does.)Added in version 2.22.
- condition_check(condition: IOCondition) IOCondition#
Checks on the readiness of
socketto perform operations. The operations specified inconditionare checked for and masked against the currently-satisfied conditions onsocket. The result is returned.Note that on Windows, it is possible for an operation to return
WOULD_BLOCKeven immediately aftercondition_check()has claimed that the socket is ready for writing. Rather than callingcondition_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 returnsWOULD_BLOCK.It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition; these conditions will always be set in the output if they are true.
This call never blocks.
Added in version 2.22.
- Parameters:
condition – a
IOConditionmask to check
- condition_timed_wait(condition: IOCondition, timeout_us: int, cancellable: Cancellable | None = None) bool#
Waits for up to
timeout_usmicroseconds forconditionto become true onsocket. If the condition is met,Trueis returned.If
cancellableis cancelled before the condition is met, or iftimeout_us(or the socket’sSocket:timeout) is reached before the condition is met, thenFalseis returned anderror, if non-None, is set to the appropriate value (CANCELLEDorTIMED_OUT).If you don’t want a timeout, use
condition_wait(). (Alternatively, you can pass -1 fortimeout_us.)Note that although
timeout_usis in microseconds for consistency with other GLib APIs, this function actually only has millisecond resolution, and the behavior is undefined iftimeout_usis not an exact number of milliseconds.Added in version 2.32.
- Parameters:
condition – a
IOConditionmask to wait fortimeout_us – the maximum time (in microseconds) to wait, or -1
cancellable – a
Cancellable, orNone
- condition_wait(condition: IOCondition, cancellable: Cancellable | None = None) bool#
Waits for
conditionto become true onsocket. When the condition is met,Trueis returned.If
cancellableis cancelled before the condition is met, or if the socket has a timeout set and it is reached before the condition is met, thenFalseis returned anderror, if non-None, is set to the appropriate value (CANCELLEDorTIMED_OUT).See also
condition_timed_wait().Added in version 2.22.
- Parameters:
condition – a
IOConditionmask to wait forcancellable – a
Cancellable, orNone
- connect(address: SocketAddress, cancellable: Cancellable | None = None) bool#
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 forsend()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
PENDINGis returned and the user can be notified of the connection finishing by waiting for the G_IO_OUT condition. The result of the connection must then be checked withcheck_connect_result().Added in version 2.22.
- Parameters:
address – a
SocketAddressspecifying the remote address.cancellable – a %GCancellable or
None
- connection_factory_create_connection() SocketConnection#
Creates a
SocketConnectionsubclass of the right type forsocket.Added in version 2.22.
- get_available_bytes() int#
Get the amount of data pending in the OS input buffer, without blocking.
If
socketis 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
receive()with a buffer of that size, rather than callingget_available_bytes()first and then doing a receive of exactly the right size.Added in version 2.32.
- get_blocking() bool#
Gets the blocking mode of the socket. For details on blocking I/O, see
set_blocking().Added in version 2.22.
- get_broadcast() bool#
Gets the broadcast setting on
socket; ifTrue, it is possible to send packets to broadcast addresses.Added in version 2.32.
- get_credentials() Credentials#
Returns the credentials of the foreign process connected to this socket, if any (e.g. it is only supported for
UNIXsockets).If this operation isn’t supported on the OS, the method fails with the
NOT_SUPPORTEDerror. 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
UnixCredentialsMessagetype andsend_credentials()/receive_credentials()functions.Added in version 2.26.
- get_family() SocketFamily#
Gets the socket family of the socket.
Added in version 2.22.
- get_fd() int#
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.
Added in version 2.22.
- get_keepalive() bool#
Gets the keepalive mode of the socket. For details on this, see
set_keepalive().Added in version 2.22.
- get_listen_backlog() int#
Gets the listen backlog setting of the socket. For details on this, see
set_listen_backlog().Added in version 2.22.
- get_local_address() SocketAddress#
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.
Added in version 2.22.
- get_multicast_loopback() bool#
Gets the multicast loopback setting on
socket; ifTrue(the default), outgoing multicast packets will be looped back to multicast listeners on the same host.Added in version 2.32.
- get_multicast_ttl() int#
Gets the multicast time-to-live setting on
socket; seeset_multicast_ttl()for more details.Added in version 2.32.
- get_option(level: int, optname: int) tuple[bool, int]#
Gets the value of an integer-valued option on
socket, as with getsockopt(). (If you need to fetch a non-integer-valued option, you will need to call getsockopt() directly.)The
`<gio/gnetworking.h><networking.html>`__ 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,
valueis still a pointer to aintvariable, not aguint8;get_option()will handle the conversion internally.Added in version 2.36.
- Parameters:
level – the “API level” of the option (eg,
SOL_SOCKET)optname – the “name” of the option (eg,
SO_BROADCAST)
- get_protocol() SocketProtocol#
Gets the socket protocol id the socket was created with. In case the protocol is unknown, -1 is returned.
Added in version 2.22.
- get_remote_address() SocketAddress#
Try to get the remote address of a connected socket. This is only useful for connection oriented sockets that have been connected.
Added in version 2.22.
- get_socket_type() SocketType#
Gets the socket type of the socket.
Added in version 2.22.
- get_timeout() int#
Gets the timeout setting of the socket. For details on this, see
set_timeout().Added in version 2.26.
- get_ttl() int#
Gets the unicast time-to-live setting on
socket; seeset_ttl()for more details.Added in version 2.32.
- is_connected() bool#
Check whether the socket is connected. This is only useful for connection-oriented sockets.
If using
shutdown(), this function will returnTrueuntil the socket has been shut down for reading and writing. If you do a non-blocking connect, this function will not returnTrueuntil after you callcheck_connect_result().Added in version 2.22.
- join_multicast_group(group: InetAddress, source_specific: bool, iface: str | None = None) bool#
Registers
socketto receive multicast messages sent togroup.socketmust be aDATAGRAMsocket, and must have been bound to an appropriate interface and port withbind().If
ifaceisNone, the system will automatically pick an interface to bind to based ongroup.If
source_specificisTrue, source-specific multicast as defined in RFC 4604 is used. Note that on older platforms this may fail with aNOT_SUPPORTEDerror.To bind to a given source-specific multicast address, use
join_multicast_group_ssm()instead.Added in version 2.32.
- Parameters:
group – a
InetAddressspecifying the group address to join.source_specific –
Trueif source-specific multicast should be usediface – Name of the interface to use, or
None
- join_multicast_group_ssm(group: InetAddress, source_specific: InetAddress | None = None, iface: str | None = None) bool#
Registers
socketto receive multicast messages sent togroup.socketmust be aDATAGRAMsocket, and must have been bound to an appropriate interface and port withbind().If
ifaceisNone, the system will automatically pick an interface to bind to based ongroup.If
source_specificis notNone, use source-specific multicast as defined in RFC 4604. Note that on older platforms this may fail with aNOT_SUPPORTEDerror.Note that this function can be called multiple times for the same
groupwith differentsource_specificin order to receive multicast packets from more than one source.Added in version 2.56.
- Parameters:
group – a
InetAddressspecifying the group address to join.source_specific – a
InetAddressspecifying the source-specific multicast address orNoneto ignore.iface – Name of the interface to use, or
None
- leave_multicast_group(group: InetAddress, source_specific: bool, iface: str | None = None) bool#
Removes
socketfrom the multicast group defined bygroup,iface, andsource_specific(which must all have the same values they had when you joined the group).socketremains 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
leave_multicast_group_ssm()instead.Added in version 2.32.
- Parameters:
group – a
InetAddressspecifying the group address to leave.source_specific –
Trueif source-specific multicast was usediface – Interface used
- leave_multicast_group_ssm(group: InetAddress, source_specific: InetAddress | None = None, iface: str | None = None) bool#
Removes
socketfrom the multicast group defined bygroup,iface, andsource_specific(which must all have the same values they had when you joined the group).socketremains bound to its address and port, and can still receive unicast messages after calling this.Added in version 2.56.
- Parameters:
group – a
InetAddressspecifying the group address to leave.source_specific – a
InetAddressspecifying the source-specific multicast address orNoneto ignore.iface – Name of the interface to use, or
None
- listen() bool#
Marks the socket as a server socket, i.e. a socket that is used to accept incoming requests using
accept().Before calling this the socket must be bound to a local address using
bind().To set the maximum amount of outstanding clients, use
set_listen_backlog().Added in version 2.22.
- receive(cancellable: Cancellable | None = None) tuple[int, list[int]]#
Receive data (up to
sizebytes) from a socket. This is mainly used by connection-oriented sockets; it is identical toreceive_from()withaddressset toNone.For
DATAGRAMandSEQPACKETsockets,receive()will always read either 0 or 1 complete messages from the socket. If the received message is too large to fit inbuffer, then the data beyondsizebytes will be discarded, without any explicit indication that this has occurred.For
STREAMsockets,receive()can return any number of bytes, up tosize. If more thansizebytes have been received, the additional data will be returned in future calls toreceive().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
WOULD_BLOCKerror will be returned. To be notified when data is available, wait for the %G_IO_IN condition.On error -1 is returned and
erroris set accordingly.Added in version 2.22.
- Parameters:
cancellable – a %GCancellable or
None
- receive_bytes(size: int, timeout_us: int, cancellable: Cancellable | None = None) Bytes#
Receives data (up to
sizebytes) from a socket.This function is a variant of
receivewhich returns aBytesrather than a plain buffer.Pass
-1totimeout_usto block indefinitely until data is received (or the connection is closed, or there is an error). Pass0to use the default timeout fromtimeout, or pass a positive number to wait for that many microseconds for data before returningG_IO_ERROR_TIMED_OUT.Added in version 2.80.
- Parameters:
size – the number of bytes you want to read from the socket
timeout_us – the timeout to wait for, in microseconds, or
-1to block indefinitelycancellable – a %GCancellable, or
NULL
- receive_bytes_from(size: int, timeout_us: int, cancellable: Cancellable | None = None) tuple[Bytes, SocketAddress]#
Receive data (up to
sizebytes) from a socket.This function is a variant of
receive_fromwhich returns aBytesrather than a plain buffer.If
addressis non-Nonethenaddresswill be set equal to the source address of the received packet.The
addressis owned by the caller.Pass
-1totimeout_usto block indefinitely until data is received (or the connection is closed, or there is an error). Pass0to use the default timeout fromtimeout, or pass a positive number to wait for that many microseconds for data before returningG_IO_ERROR_TIMED_OUT.Added in version 2.80.
- Parameters:
size – the number of bytes you want to read from the socket
timeout_us – the timeout to wait for, in microseconds, or
-1to block indefinitelycancellable – a
Cancellable, orNULL
- receive_from(cancellable: Cancellable | None = None) tuple[int, SocketAddress, list[int]]#
Receive data (up to
sizebytes) from a socket.If
addressis non-Nonethenaddresswill be set equal to the source address of the received packet.addressis owned by the caller.See
receive()for additional information.Added in version 2.22.
- Parameters:
cancellable – a %GCancellable or
None
- receive_message(vectors: list[InputVector], flags: int, cancellable: Cancellable | None = None) tuple[int, SocketAddress, list[SocketControlMessage] | None, int]#
Receive data from a socket. For receiving multiple messages, see
receive_messages(); for easier use, seereceive()andreceive_from().If
addressis non-Nonethenaddresswill be set equal to the source address of the received packet.addressis owned by the caller.vectormust point to an array ofInputVectorstructs andnum_vectorsmust be the length of this array. These structs describe the buffers that received data will be scattered into. Ifnum_vectorsis -1, thenvectorsis assumed to be terminated by aInputVectorwith aNonebuffer pointer.As a special case, if
num_vectorsis 0 (in which case,vectorsmay of course beNone), 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 ofSocketControlMessageinstances orNoneif no such messages was received. These correspond to the control messages received from the kernel, oneSocketControlMessageper message from the kernel. This array isNone-terminated and must be freed by the caller usingfree()after callingunref()on each element. IfmessagesisNone, any control messages received will be discarded.num_messages, if non-None, will be set to the number of control messages received.If both
messagesandnum_messagesare non-None, thennum_messagesgives the number ofSocketControlMessageinstances inmessages(ie: not including theNoneterminator).flagsis an in/out parameter. The commonly available arguments for this are available in theGSocketMsgFlagsenum, 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 (andreceive_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
receive(), data may be discarded ifsocketisDATAGRAMorSEQPACKETand you do not provide enough buffer space to read a complete message. You can passPEEKinflagsto 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
WOULD_BLOCKerror will be returned. To be notified when data is available, wait for the %G_IO_IN condition.On error -1 is returned and
erroris set accordingly.Added in version 2.22.
- Parameters:
vectors – an array of
InputVectorstructsflags – a pointer to an int containing
GSocketMsgFlagsflags, which may additionally contain other platform specific flagscancellable – a %GCancellable or
None
- receive_messages(messages: list[InputMessage], flags: int, cancellable: Cancellable | None = None) int#
Receive multiple data messages from
socketin one go. This is the most complicated and fully-featured version of this call. For easier use, seereceive(),receive_from(), andreceive_message().messagesmust point to an array ofInputMessagestructs andnum_messagesmust be the length of this array. EachInputMessagecontains a pointer to an array ofInputVectorstructs describing the buffers that the data received in each message will be written to. Using multipleInputVectoris more memory-efficient than manually copying data out of a single buffer to multiple sources, and more system-call-efficient than making multiple calls toreceive(), such as in scenarios where a lot of data packets need to be received (e.g. high-bandwidth video streaming over RTP/UDP).flagsmodify how all messages are received. The commonly available arguments for this are available in theGSocketMsgFlagsenum, 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 inInputMessage.flags.The other members of
InputMessageare treated as described in its documentation.If
Socket:blocking isTruethe call will block untilnum_messageshave been received, or the end of the stream is reached.If
Socket:blocking isFalsethe call will return up tonum_messageswithout blocking, orWOULD_BLOCKif no messages are queued in the operating system to be received.In blocking mode, if
Socket:timeout is positive and is reached before any messages are received,TIMED_OUTis returned, otherwise up tonum_messagesare returned. (Note: This is effectively the behaviour ofMSG_WAITFORONEwith recvmmsg().)To be notified when messages are available, wait for the %G_IO_IN condition. Note though that you may still receive
WOULD_BLOCKfromreceive_messages()even if you were previously notified of a %G_IO_IN condition.If the remote peer closes the connection, any messages queued in the operating system will be returned, and subsequent calls to
receive_messages()will return 0 (with no error set).On error -1 is returned and
erroris 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.Added in version 2.48.
- Parameters:
messages – an array of
InputMessagestructsflags – an int containing
GSocketMsgFlagsflags for the overall operation, which may additionally contain other platform specific flagscancellable – a %GCancellable or
None
- receive_with_blocking(blocking: bool, cancellable: Cancellable | None = None) tuple[int, list[int]]#
This behaves exactly the same as
receive(), except that the choice of blocking or non-blocking behavior is determined by theblockingargument rather than bysocket's properties.Added in version 2.26.
- Parameters:
blocking – whether to do blocking or non-blocking I/O
cancellable – a %GCancellable or
None
- send(buffer: list[int], cancellable: Cancellable | None = None) int#
Tries to send
sizebytes frombufferon the socket. This is mainly used by connection-oriented sockets; it is identical tosend_to()withaddressset 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
WOULD_BLOCKerror will be returned. To be notified when space is available, wait for the %G_IO_OUT condition. Note though that you may still receiveWOULD_BLOCKfromsend()even if you were previously notified of a %G_IO_OUT condition. (On Windows in particular, this is very common due to the way the underlying APIs work.)On error -1 is returned and
erroris set accordingly.Added in version 2.22.
- Parameters:
buffer – the buffer containing the data to send.
cancellable – a %GCancellable or
None
- send_message(address: SocketAddress | None, vectors: list[OutputVector], messages: list[SocketControlMessage] | None, flags: int, cancellable: Cancellable | None = None) int#
Send data to
addressonsocket. For sending multiple messages seesend_messages(); for easier use, seesend()andsend_to().If
addressisNonethen the message is sent to the default receiver (set byconnect()).vectorsmust point to an array ofOutputVectorstructs andnum_vectorsmust be the length of this array. (Ifnum_vectorsis -1, thenvectorsis assumed to be terminated by aOutputVectorwith aNonebuffer pointer.) TheOutputVectorstructs describe the buffers that the sent data will be gathered from. Using multipleOutputVectoris more memory-efficient than manually copying data from multiple sources into a single buffer, and more network-efficient than making multiple calls tosend().messages, if non-None, is taken to point to an array ofnum_messagesSocketControlMessageinstances. These correspond to the control messages to be sent on the socket. Ifnum_messagesis -1 thenmessagesis treated as aNone-terminated array.flagsmodify how the message is sent. The commonly available arguments for this are available in theGSocketMsgFlagsenum, 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
WOULD_BLOCKerror will be returned. To be notified when space is available, wait for the %G_IO_OUT condition. Note though that you may still receiveWOULD_BLOCKfromsend()even if you were previously notified of a %G_IO_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
OutputVectorin vectors must not be greater than %G_MAXSSIZE. If the message can be larger than this, then it is mandatory to use thesend_message_with_timeout()function.On error -1 is returned and
erroris set accordingly.Added in version 2.22.
- Parameters:
address – a
SocketAddress, orNonevectors – an array of
OutputVectorstructsmessages – a pointer to an array of
SocketControlMessage, orNone.flags – an int containing
GSocketMsgFlagsflags, which may additionally contain other platform specific flagscancellable – a %GCancellable or
None
- send_message_with_timeout(address: SocketAddress | None, vectors: list[OutputVector], messages: list[SocketControlMessage] | None, flags: int, timeout_us: int, cancellable: Cancellable | None = None) tuple[PollableReturn, int]#
This behaves exactly the same as
send_message(), except that the choice of timeout behavior is determined by thetimeout_usargument rather than bysocket's properties.On error
FAILEDis returned anderroris set accordingly, or if the socket is currently not writableWOULD_BLOCKis returned.bytes_writtenwill contain 0 in both cases.Added in version 2.60.
- Parameters:
address – a
SocketAddress, orNonevectors – an array of
OutputVectorstructsmessages – a pointer to an array of
SocketControlMessage, orNone.flags – an int containing
GSocketMsgFlagsflags, which may additionally contain other platform specific flagstimeout_us – the maximum time (in microseconds) to wait, or -1
cancellable – a %GCancellable or
None
- send_messages(messages: list[OutputMessage], flags: int, cancellable: Cancellable | None = None) int#
Send multiple data messages from
socketin one go. This is the most complicated and fully-featured version of this call. For easier use, seesend(),send_to(), andsend_message().messagesmust point to an array ofOutputMessagestructs andnum_messagesmust be the length of this array. EachOutputMessagecontains an address to send the data to, and a pointer to an array ofOutputVectorstructs to describe the buffers that the data to be sent for each message will be gathered from. Using multipleOutputVectoris more memory-efficient than manually copying data from multiple sources into a single buffer, and more network-efficient than making multiple calls tosend(). 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.flagsmodify how the message is sent. The commonly available arguments for this are available in theGSocketMsgFlagsenum, 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
WOULD_BLOCKerror 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 the %G_IO_OUT condition. Note though that you may still receiveWOULD_BLOCKfromsend()even if you were previously notified of a %G_IO_OUT condition. (On Windows in particular, this is very common due to the way the underlying APIs work.)On error -1 is returned and
erroris 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.Added in version 2.44.
- Parameters:
messages – an array of
OutputMessagestructsflags – an int containing
GSocketMsgFlagsflags, which may additionally contain other platform specific flagscancellable – a %GCancellable or
None
- send_to(address: SocketAddress | None, buffer: list[int], cancellable: Cancellable | None = None) int#
Tries to send
sizebytes frombuffertoaddress. IfaddressisNonethen the message is sent to the default receiver (set byconnect()).See
send()for additional information.Added in version 2.22.
- Parameters:
address – a
SocketAddress, orNonebuffer – the buffer containing the data to send.
cancellable – a %GCancellable or
None
- send_with_blocking(buffer: list[int], blocking: bool, cancellable: Cancellable | None = None) int#
This behaves exactly the same as
send(), except that the choice of blocking or non-blocking behavior is determined by theblockingargument rather than bysocket's properties.Added in version 2.26.
- Parameters:
buffer – the buffer containing the data to send.
blocking – whether to do blocking or non-blocking I/O
cancellable – a %GCancellable or
None
- set_blocking(blocking: bool) None#
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
WOULD_BLOCKerror.All sockets are created in blocking mode. However, note that the platform level socket is always non-blocking, and blocking mode is a GSocket level feature.
Added in version 2.22.
- Parameters:
blocking – Whether to use blocking I/O or not.
- set_broadcast(broadcast: bool) None#
Sets whether
socketshould allow sending to broadcast addresses. This isFalseby default.Added in version 2.32.
- Parameters:
broadcast – whether
socketshould allow sending to broadcast addresses
- set_keepalive(keepalive: bool) None#
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,
TCPsockets.)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.
Added in version 2.22.
- Parameters:
keepalive – Value for the keepalive flag
- set_listen_backlog(backlog: int) None#
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
listen()and has no effect if called after that.Added in version 2.22.
- Parameters:
backlog – the maximum number of pending connections.
- set_multicast_loopback(loopback: bool) None#
Sets whether outgoing multicast packets will be received by sockets listening on that multicast address on the same host. This is
Trueby default.Added in version 2.32.
- Parameters:
loopback – whether
socketshould receive messages sent to its multicast groups from the local host
- set_multicast_ttl(ttl: int) None#
Sets the time-to-live for outgoing multicast datagrams on
socket. By default, this is 1, meaning that multicast packets will not leave the local network.Added in version 2.32.
- Parameters:
ttl – the time-to-live value for all multicast datagrams on
socket
- set_option(level: int, optname: int, value: int) bool#
Sets the value of an integer-valued option on
socket, as with setsockopt(). (If you need to set a non-integer-valued option, you will need to call setsockopt() directly.)The
`<gio/gnetworking.h><networking.html>`__ 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.Added in version 2.36.
- Parameters:
level – the “API level” of the option (eg,
SOL_SOCKET)optname – the “name” of the option (eg,
SO_BROADCAST)value – the value to set the option to
- set_timeout(timeout: int) None#
Sets the time in seconds after which I/O operations on
socketwill time out if they have not yet completed.On a blocking socket, this means that any blocking
Socketoperation will time out aftertimeoutseconds of inactivity, returningTIMED_OUT.On a non-blocking socket, calls to
condition_wait()will also fail withTIMED_OUTafter the given time. Sources created withcreate_source()will trigger aftertimeoutseconds of inactivity, with the requested condition set, at which point callingreceive(),send(),check_connect_result(), etc, will fail withTIMED_OUT.If
timeoutis 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.
Added in version 2.26.
- Parameters:
timeout – the timeout for
socket, in seconds, or 0 for none
- set_ttl(ttl: int) None#
Sets the time-to-live for outgoing unicast packets on
socket. By default the platform-specific default value is used.Added in version 2.32.
- Parameters:
ttl – the time-to-live value for all unicast packets on
socket
- shutdown(shutdown_read: bool, shutdown_write: bool) bool#
Shut down part or all of a full-duplex connection.
If
shutdown_readisTruethen the receiving side of the connection is shut down, and further reading is disallowed.If
shutdown_writeisTruethen the sending side of the connection is shut down, and further writing is disallowed.It is allowed for both
shutdown_readandshutdown_writeto beTrue.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.
Added in version 2.22.
- Parameters:
shutdown_read – whether to shut down the read side
shutdown_write – whether to shut down the write side
- speaks_ipv4() bool#
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.
Added in version 2.22.
Properties#
- class Socket
-
- props.family: SocketFamily#
The type of the None singleton.
Added in version 2.22.
- props.local_address: SocketAddress#
The type of the None singleton.
Added in version 2.22.
- props.protocol: SocketProtocol#
The type of the None singleton.
Added in version 2.22.
- props.remote_address: SocketAddress#
The type of the None singleton.
Added in version 2.22.
- props.type: SocketType#
The type of the None singleton.
Added in version 2.22.