gio.socket

Module for [Socket] class

Types 3

A gio.socket.Socket 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.

gio.socket.Socket 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 gio.socket_client.SocketClient, gio.socket_service.SocketService and gio.socket_connection.SocketConnection. However there may be cases where direct use of gio.socket.Socket is useful.

gio.socket.Socket implements the gio.initable.Initable interface, so if it is manually constructed by e.g. gobject.object.ObjectWrap.new_ you must call gio.initable.Initable.init_ and check the results before using the object. This is done automatically in gio.socket.Socket.new_ and gio.socket.Socket.newFromFd, 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 gio.types.IOErrorEnum.WouldBlock error. To know when a call would successfully run you can call gio.socket.Socket.conditionCheck, or gio.socket.Socket.conditionWait. You can also use gio.socket.Socket.createSource and attach it to a glib.main_context.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 gio.socket.Socket.

When working in non-blocking mode applications should always be able to handle getting a gio.types.IOErrorEnum.WouldBlock 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 gio.types.IOErrorEnum.WouldBlock.

gio.socket.Sockets 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 gio.socket.Socket causes the signal SIGPIPE to be ignored for the remainder of the program. If you are writing a command-line utility that uses gio.socket.Socket, 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, gio.socket.Socket is not inherently thread safe. To use a gio.socket.Socket concurrently from multiple threads, you must implement your own locking.

Nagle’s algorithm

Since GLib 2.80, gio.socket.Socket will automatically set the TCP_NODELAY option on all gio.types.SocketType.Stream sockets. This disables 27s_algorithm">Nagle’s algorithm as it typically does more harm than good on modern networks.

If your application needs Nagle’s algorithm enabled, call gio.socket.Socket.setOption after constructing a gio.socket.Socket 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
  }

Methods
GType _getGType() static nothrow
GType _gType() @property nothrow
Socket self() nothrowReturns `this`, for use in `with` statements.
SocketGidBuilder builder() static nothrowGet builder for [gio.socket.Socket] Returns: New builder object
bool blocking() @property nothrowGet `blocking` property. Returns: Whether I/O on this socket is blocking.
void blocking(bool propval) @property nothrowSet `blocking` property. Params: propval = Whether I/O on this socket is blocking.
bool broadcast() @property nothrowGet `broadcast` property. Returns: Whether the socket should allow sending to broadcast addresses.
void broadcast(bool propval) @property nothrowSet `broadcast` property. Params: propval = Whether the socket should allow sending to broadcast addresses.
gio.types.SocketFamily family() @property nothrowGet `family` property. Returns: The socket’s address family.
int fd() @property nothrowGet `fd` property. Returns: The socket’s file descriptor.
bool keepalive() @property nothrowGet `keepalive` property. Returns: Whether to keep the connection alive by sending periodic pings.
void keepalive(bool propval) @property nothrowSet `keepalive` property. Params: propval = Whether to keep the connection alive by sending periodic pings.
int listenBacklog() @property nothrowGet `listenBacklog` property. Returns: The number of outstanding connections in the listen queue.
void listenBacklog(int propval) @property nothrowSet `listenBacklog` property. Params: propval = The number of outstanding connections in the listen queue.
gio.socket_address.SocketAddress localAddress() @property nothrowGet `localAddress` property. Returns: The local address the socket is bound to.
bool multicastLoopback() @property nothrowGet `multicastLoopback` property. Returns: Whether outgoing multicast packets loop back to the local host.
void multicastLoopback(bool propval) @property nothrowSet `multicastLoopback` property. Params: propval = Whether outgoing multicast packets loop back to the local host.
uint multicastTtl() @property nothrowGet `multicastTtl` property. Returns: Time-to-live out outgoing multicast packets
void multicastTtl(uint propval) @property nothrowSet `multicastTtl` property. Params: propval = Time-to-live out outgoing multicast packets
gio.types.SocketProtocol protocol() @property nothrowGet `protocol` property. Returns: The ID of the protocol to use, or `-1` for unknown.
gio.socket_address.SocketAddress remoteAddress() @property nothrowGet `remoteAddress` property. Returns: The remote address the socket is connected to.
uint timeout() @property nothrowGet `timeout` property. Returns: The timeout in seconds on socket I/O
void timeout(uint propval) @property nothrowSet `timeout` property. Params: propval = The timeout in seconds on socket I/O
uint ttl() @property nothrowGet `ttl` property. Returns: Time-to-live for outgoing unicast packets
void ttl(uint propval) @property nothrowSet `ttl` property. Params: propval = Time-to-live for outgoing unicast packets
gio.types.SocketType type() @property nothrowGet `type` property. Returns: The socket’s type.
gio.socket.Socket newFromFd(int fd) staticCreates a new #GSocket from a native file descriptor or winsock SOCKET handle.
gio.socket.Socket accept(gio.cancellable.Cancellable cancellable = null)Accept incoming connections on a connection-based socket. This removes the first outstanding connection request from the listening socket and creates a #GSocket object for it.
bool bind(gio.socket_address.SocketAddress address, bool allowReuse)When a socket is created it is attached to an address family, but it doesn't have an address in this family. [gio.socket.Socket.bind] assigns the address (sometimes called name) of the socket.
bool checkConnectResult()Checks and resets the pending connect error for the socket. This is used to check for errors when [gio.socket.Socket.connect] is used in non-blocking mode. Returns: true if no error, false otherwis...
bool close()Closes the socket, shutting down any active connection.
glib.types.IOCondition conditionCheck(glib.types.IOCondition condition) nothrowChecks on the readiness of socket to perform operations. The operations specified in condition are checked for and masked against the currently-satisfied conditions on socket. The result is returned.
bool conditionTimedWait(glib.types.IOCondition condition, long timeoutUs, gio.cancellable.Cancellable cancellable = null)Waits for up to timeout_us microseconds for condition to become true on socket. If the condition is met, true is returned.
bool conditionWait(glib.types.IOCondition condition, gio.cancellable.Cancellable cancellable = null)Waits for condition to become true on socket. When the condition is met, true is returned.
bool connect(gio.socket_address.SocketAddress address, gio.cancellable.Cancellable cancellable = null)Connect the socket to the specified remote address.
gio.socket_connection.SocketConnection connectionFactoryCreateConnection() nothrowCreates a #GSocketConnection subclass of the right type for socket. Returns: a #GSocketConnection
ptrdiff_t getAvailableBytes() nothrowGet the amount of data pending in the OS input buffer, without blocking.
bool getBlocking() nothrowGets the blocking mode of the socket. For details on blocking I/O, see [gio.socket.Socket.setBlocking]. Returns: true if blocking I/O is used, false otherwise.
bool getBroadcast() nothrowGets the broadcast setting on socket; if true, it is possible to send packets to broadcast addresses. Returns: the broadcast setting on socket
gio.credentials.Credentials getCredentials()Returns the credentials of the foreign process connected to this socket, if any (e.g. it is only supported for [gio.types.SocketFamily.Unix] sockets).
gio.types.SocketFamily getFamily() nothrowGets the socket family of the socket. Returns: a #GSocketFamily
int getFd() nothrowReturns 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 unusu...
bool getKeepalive() nothrowGets the keepalive mode of the socket. For details on this, see [gio.socket.Socket.setKeepalive]. Returns: true if keepalive is active, false otherwise.
int getListenBacklog() nothrowGets the listen backlog setting of the socket. For details on this, see [gio.socket.Socket.setListenBacklog]. Returns: the maximum number of pending connections.
gio.socket_address.SocketAddress getLocalAddress()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. Returns: a #GSocketAddress or n...
bool getMulticastLoopback() nothrowGets the multicast loopback setting on socket; if true (the default), outgoing multicast packets will be looped back to multicast listeners on the same host. Returns: the multicast loopback setting...
uint getMulticastTtl() nothrowGets the multicast time-to-live setting on socket; see [gio.socket.Socket.setMulticastTtl] for more details. Returns: the multicast time-to-live setting on socket
bool getOption(int level, int optname, out int value)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.)
gio.types.SocketProtocol getProtocol() nothrowGets the socket protocol id the socket was created with. In case the protocol is unknown, -1 is returned. Returns: a protocol id, or -1 if unknown
gio.socket_address.SocketAddress getRemoteAddress()Try to get the remote address of a connected socket. This is only useful for connection oriented sockets that have been connected. Returns: a #GSocketAddress or null on error. Free the returned obj...
gio.types.SocketType getSocketType() nothrowGets the socket type of the socket. Returns: a #GSocketType
uint getTimeout() nothrowGets the timeout setting of the socket. For details on this, see [gio.socket.Socket.setTimeout]. Returns: the timeout in seconds
uint getTtl() nothrowGets the unicast time-to-live setting on socket; see [gio.socket.Socket.setTtl] for more details. Returns: the time-to-live setting on socket
bool isClosed() nothrowChecks whether a socket is closed. Returns: true if socket is closed, false otherwise
bool isConnected() nothrowCheck whether the socket is connected. This is only useful for connection-oriented sockets.
bool joinMulticastGroup(gio.inet_address.InetAddress group, bool sourceSpecific, string iface = null)Registers socket to receive multicast messages sent to group. socket must be a [gio.types.SocketType.Datagram] socket, and must have been bound to an appropriate interface and port with [gio.socket...
bool joinMulticastGroupSsm(gio.inet_address.InetAddress group, gio.inet_address.InetAddress sourceSpecific = null, string iface = null)Registers socket to receive multicast messages sent to group. socket must be a [gio.types.SocketType.Datagram] socket, and must have been bound to an appropriate interface and port with [gio.socket...
bool leaveMulticastGroup(gio.inet_address.InetAddress group, bool sourceSpecific, string iface = null)Removes socket 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).
bool leaveMulticastGroupSsm(gio.inet_address.InetAddress group, gio.inet_address.InetAddress sourceSpecific = null, string iface = null)Removes socket 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).
bool listen()Marks the socket as a server socket, i.e. a socket that is used to accept incoming requests using [gio.socket.Socket.accept].
ptrdiff_t receive(ref ubyte[] buffer, gio.cancellable.Cancellable cancellable = null)Receive data (up to size bytes) from a socket. This is mainly used by connection-oriented sockets; it is identical to [gio.socket.Socket.receiveFrom] with address set to null.
glib.bytes.Bytes receiveBytes(size_t size, long timeoutUs, gio.cancellable.Cancellable cancellable = null)Receives data (up to size bytes) from a socket.
glib.bytes.Bytes receiveBytesFrom(out gio.socket_address.SocketAddress address, size_t size, long timeoutUs, gio.cancellable.Cancellable cancellable = null)Receive data (up to size bytes) from a socket.
ptrdiff_t receiveFrom(out gio.socket_address.SocketAddress address, ref ubyte[] buffer, gio.cancellable.Cancellable cancellable = null)Receive data (up to size bytes) from a socket.
ptrdiff_t receiveMessage(out gio.socket_address.SocketAddress address, gio.types.InputVector[] vectors, out gio.socket_control_message.SocketControlMessage[] messages, ref int flags, gio.cancellable.Cancellable cancellable = null)Receive data from a socket. For receiving multiple messages, see [gio.socket.Socket.receiveMessages]; for easier use, see [gio.socket.Socket.receive] and [gio.socket.Socket.receiveFrom].
ptrdiff_t receiveWithBlocking(ref ubyte[] buffer, bool blocking, gio.cancellable.Cancellable cancellable = null)This behaves exactly the same as [gio.socket.Socket.receive], except that the choice of blocking or non-blocking behavior is determined by the blocking argument rather than by socket's properties.
ptrdiff_t send(ubyte[] buffer, gio.cancellable.Cancellable cancellable = null)Tries to send size bytes from buffer on the socket. This is mainly used by connection-oriented sockets; it is identical to [gio.socket.Socket.sendTo] with address set to null.
ptrdiff_t sendMessage(gio.socket_address.SocketAddress address, gio.types.OutputVector[] vectors, gio.socket_control_message.SocketControlMessage[] messages, int flags, gio.cancellable.Cancellable cancellable = null)Send data to address on socket. For sending multiple messages see [gio.socket.Socket.sendMessages]; for easier use, see [gio.socket.Socket.send] and [gio.socket.Socket.sendTo].
gio.types.PollableReturn sendMessageWithTimeout(gio.socket_address.SocketAddress address, gio.types.OutputVector[] vectors, gio.socket_control_message.SocketControlMessage[] messages, int flags, long timeoutUs, out size_t bytesWritten, gio.cancellable.Cancellable cancellable = null)This behaves exactly the same as [gio.socket.Socket.sendMessage], except that the choice of timeout behavior is determined by the timeout_us argument rather than by socket's properties.
ptrdiff_t sendTo(gio.socket_address.SocketAddress address, ubyte[] buffer, gio.cancellable.Cancellable cancellable = null)Tries to send size bytes from buffer to address. If address is null then the message is sent to the default receiver (set by [gio.socket.Socket.connect]).
ptrdiff_t sendWithBlocking(ubyte[] buffer, bool blocking, gio.cancellable.Cancellable cancellable = null)This behaves exactly the same as [gio.socket.Socket.send], except that the choice of blocking or non-blocking behavior is determined by the blocking argument rather than by socket's properties.
void setBlocking(bool blocking) nothrowSets 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 fun...
void setBroadcast(bool broadcast) nothrowSets whether socket should allow sending to broadcast addresses. This is false by default.
void setKeepalive(bool keepalive) nothrowSets 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 sufficien...
void setListenBacklog(int backlog) nothrowSets 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 the...
void setMulticastLoopback(bool loopback) nothrowSets whether outgoing multicast packets will be received by sockets listening on that multicast address on the same host. This is true by default.
void setMulticastTtl(uint ttl) nothrowSets 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.
bool setOption(int level, int optname, int value)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.)
void setTimeout(uint timeout) nothrowSets the time in seconds after which I/O operations on socket will time out if they have not yet completed.
void setTtl(uint ttl) nothrowSets the time-to-live for outgoing unicast packets on socket. By default the platform-specific default value is used.
bool shutdown(bool shutdownRead, bool shutdownWrite)Shut down part or all of a full-duplex connection.
bool speaksIpv4() nothrowChecks if a socket is capable of speaking IPv4.
Constructors
this(void * ptr, Flag!"Take" take)
this(gio.types.SocketFamily family, gio.types.SocketType type, gio.types.SocketProtocol protocol)Creates a new #GSocket with the defined family, type and protocol. If protocol is 0 ([gio.types.SocketProtocol.Default]) the default protocol type for the family and type is used.

Fluent builder implementation template for gio.socket.Socket

Methods
T blocking(bool propval) nothrowSet `blocking` property. Params: propval = Whether I/O on this socket is blocking. Returns: Builder instance for fluent chaining
T broadcast(bool propval) nothrowSet `broadcast` property. Params: propval = Whether the socket should allow sending to broadcast addresses. Returns: Builder instance for fluent chaining
T family(gio.types.SocketFamily propval) nothrowSet `family` property. Params: propval = The socket’s address family. Returns: Builder instance for fluent chaining
T fd(int propval) nothrowSet `fd` property. Params: propval = The socket’s file descriptor. Returns: Builder instance for fluent chaining
T keepalive(bool propval) nothrowSet `keepalive` property. Params: propval = Whether to keep the connection alive by sending periodic pings. Returns: Builder instance for fluent chaining
T listenBacklog(int propval) nothrowSet `listenBacklog` property. Params: propval = The number of outstanding connections in the listen queue. Returns: Builder instance for fluent chaining
T multicastLoopback(bool propval) nothrowSet `multicastLoopback` property. Params: propval = Whether outgoing multicast packets loop back to the local host. Returns: Builder instance for fluent chaining
T multicastTtl(uint propval) nothrowSet `multicastTtl` property. Params: propval = Time-to-live out outgoing multicast packets Returns: Builder instance for fluent chaining
T protocol(gio.types.SocketProtocol propval) nothrowSet `protocol` property. Params: propval = The ID of the protocol to use, or `-1` for unknown. Returns: Builder instance for fluent chaining
T timeout(uint propval) nothrowSet `timeout` property. Params: propval = The timeout in seconds on socket I/O Returns: Builder instance for fluent chaining
T ttl(uint propval) nothrowSet `ttl` property. Params: propval = Time-to-live for outgoing unicast packets Returns: Builder instance for fluent chaining
T type(gio.types.SocketType propval) nothrowSet `type` property. Params: propval = The socket’s type. Returns: Builder instance for fluent chaining

Fluent builder for gio.socket.Socket

Methods
Socket build() nothrowCreate object from builder. Returns: New object