Socket

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.ObjectG.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 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
  }
class Socket : ObjectG , DatagramBased , Initable {}

Constructors

this
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.

Members

Functions

accept
gio.socket.Socket accept(gio.cancellable.Cancellable cancellable)

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.

bind
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.

checkConnectResult
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.

close
bool close()

Closes the socket, shutting down any active connection.

conditionCheck
glib.types.IOCondition conditionCheck(glib.types.IOCondition condition)

Checks 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.

conditionTimedWait
bool conditionTimedWait(glib.types.IOCondition condition, long timeoutUs, gio.cancellable.Cancellable cancellable)

Waits for up to timeout_us microseconds for condition to become true on socket. If the condition is met, true is returned.

conditionWait
bool conditionWait(glib.types.IOCondition condition, gio.cancellable.Cancellable cancellable)

Waits for condition to become true on socket. When the condition is met, true is returned.

connect
bool connect(gio.socket_address.SocketAddress address, gio.cancellable.Cancellable cancellable)

Connect the socket to the specified remote address.

connectionFactoryCreateConnection
gio.socket_connection.SocketConnection connectionFactoryCreateConnection()

Creates a #GSocketConnection subclass of the right type for socket.

getAvailableBytes
ptrdiff_t getAvailableBytes()

Get the amount of data pending in the OS input buffer, without blocking.

getBlocking
bool getBlocking()

Gets the blocking mode of the socket. For details on blocking I/O, see gio.socket.Socket.setBlocking.

getBroadcast
bool getBroadcast()

Gets the broadcast setting on socket; if true, it is possible to send packets to broadcast addresses.

getCredentials
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).

getFamily
gio.types.SocketFamily getFamily()

Gets the socket family of the socket.

getFd
int getFd()

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.

getKeepalive
bool getKeepalive()

Gets the keepalive mode of the socket. For details on this, see gio.socket.Socket.setKeepalive.

getListenBacklog
int getListenBacklog()

Gets the listen backlog setting of the socket. For details on this, see gio.socket.Socket.setListenBacklog.

getLocalAddress
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.

getMulticastLoopback
bool getMulticastLoopback()

Gets the multicast loopback setting on socket; if true (the default), outgoing multicast packets will be looped back to multicast listeners on the same host.

getMulticastTtl
uint getMulticastTtl()

Gets the multicast time-to-live setting on socket; see gio.socket.Socket.setMulticastTtl for more details.

getOption
bool getOption(int level, int optname, 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.)

getProtocol
gio.types.SocketProtocol getProtocol()

Gets the socket protocol id the socket was created with. In case the protocol is unknown, -1 is returned.

getRemoteAddress
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.

getSocketType
gio.types.SocketType getSocketType()

Gets the socket type of the socket.

getTimeout
uint getTimeout()

Gets the timeout setting of the socket. For details on this, see gio.socket.Socket.setTimeout.

getTtl
uint getTtl()

Gets the unicast time-to-live setting on socket; see gio.socket.Socket.setTtl for more details.

isClosed
bool isClosed()

Checks whether a socket is closed.

isConnected
bool isConnected()

Check whether the socket is connected. This is only useful for connection-oriented sockets.

joinMulticastGroup
bool joinMulticastGroup(gio.inet_address.InetAddress group, bool sourceSpecific, string iface)

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.Socket.bind.

joinMulticastGroupSsm
bool joinMulticastGroupSsm(gio.inet_address.InetAddress group, gio.inet_address.InetAddress sourceSpecific, string iface)

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.Socket.bind.

leaveMulticastGroup
bool leaveMulticastGroup(gio.inet_address.InetAddress group, bool sourceSpecific, string iface)

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).

leaveMulticastGroupSsm
bool leaveMulticastGroupSsm(gio.inet_address.InetAddress group, gio.inet_address.InetAddress sourceSpecific, string iface)

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).

listen
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.

receive
ptrdiff_t receive(ubyte[] buffer, gio.cancellable.Cancellable cancellable)

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.

receiveBytes
glib.bytes.Bytes receiveBytes(size_t size, long timeoutUs, gio.cancellable.Cancellable cancellable)

Receives data (up to size bytes) from a socket.

receiveBytesFrom
glib.bytes.Bytes receiveBytesFrom(gio.socket_address.SocketAddress address, size_t size, long timeoutUs, gio.cancellable.Cancellable cancellable)

Receive data (up to size bytes) from a socket.

receiveFrom
ptrdiff_t receiveFrom(gio.socket_address.SocketAddress address, ubyte[] buffer, gio.cancellable.Cancellable cancellable)

Receive data (up to size bytes) from a socket.

receiveMessage
ptrdiff_t receiveMessage(gio.socket_address.SocketAddress address, gio.types.InputVector[] vectors, gio.socket_control_message.SocketControlMessage[] messages, int flags, gio.cancellable.Cancellable cancellable)

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.

receiveWithBlocking
ptrdiff_t receiveWithBlocking(ubyte[] buffer, bool blocking, gio.cancellable.Cancellable cancellable)

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.

send
ptrdiff_t send(ubyte[] buffer, gio.cancellable.Cancellable cancellable)

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.

sendMessage
ptrdiff_t sendMessage(gio.socket_address.SocketAddress address, gio.types.OutputVector[] vectors, gio.socket_control_message.SocketControlMessage[] messages, int flags, gio.cancellable.Cancellable cancellable)

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.

sendMessageWithTimeout
gio.types.PollableReturn sendMessageWithTimeout(gio.socket_address.SocketAddress address, gio.types.OutputVector[] vectors, gio.socket_control_message.SocketControlMessage[] messages, int flags, long timeoutUs, size_t bytesWritten, gio.cancellable.Cancellable cancellable)

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.

sendTo
ptrdiff_t sendTo(gio.socket_address.SocketAddress address, ubyte[] buffer, gio.cancellable.Cancellable cancellable)

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).

sendWithBlocking
ptrdiff_t sendWithBlocking(ubyte[] buffer, bool blocking, gio.cancellable.Cancellable cancellable)

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.

setBlocking
void setBlocking(bool blocking)

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.types.IOErrorEnum.WouldBlock error.

setBroadcast
void setBroadcast(bool broadcast)

Sets whether socket should allow sending to broadcast addresses. This is false by default.

setKeepalive
void setKeepalive(bool keepalive)

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.

setListenBacklog
void setListenBacklog(int backlog)

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.

setMulticastLoopback
void setMulticastLoopback(bool loopback)

Sets whether outgoing multicast packets will be received by sockets listening on that multicast address on the same host. This is true by default.

setMulticastTtl
void setMulticastTtl(uint ttl)

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.

setOption
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.)

setTimeout
void setTimeout(uint timeout)

Sets the time in seconds after which I/O operations on socket will time out if they have not yet completed.

setTtl
void setTtl(uint ttl)

Sets the time-to-live for outgoing unicast packets on socket. By default the platform-specific default value is used.

shutdown
bool shutdown(bool shutdownRead, bool shutdownWrite)

Shut down part or all of a full-duplex connection.

speaksIpv4
bool speaksIpv4()

Checks if a socket is capable of speaking IPv4.

Static functions

newFromFd
gio.socket.Socket newFromFd(int fd)

Creates a new #GSocket from a native file descriptor or winsock SOCKET handle.

Mixed In Members

From mixin DatagramBasedT!()

conditionCheck
glib.types.IOCondition conditionCheck(glib.types.IOCondition condition)

Checks on the readiness of datagram_based to perform operations. The operations specified in condition are checked for and masked against the currently-satisfied conditions on datagram_based. The result is returned.

conditionWait
bool conditionWait(glib.types.IOCondition condition, long timeout, gio.cancellable.Cancellable cancellable)

Waits for up to timeout microseconds for condition to become true on datagram_based. If the condition is met, true is returned.

createSource
glib.source.Source createSource(glib.types.IOCondition condition, gio.cancellable.Cancellable cancellable)

Creates a #GSource that can be attached to a #GMainContext to monitor for the availability of the specified condition on the #GDatagramBased. The #GSource keeps a reference to the datagram_based.

From mixin InitableT!()

init_
bool init_(gio.cancellable.Cancellable cancellable)

Initializes the object implementing the interface.

Inherited Members

From ObjectG

setGObject
void setGObject(void* cObj, Flag!"Take" take)

Set the GObject of a D ObjectG wrapper.

cPtr
void* cPtr(Flag!"Dup" dup)

Get a pointer to the underlying C object.

ref_
void* ref_(void* gObj)

Calls g_object_ref() on a GObject.

unref
unref(void* gObj)

Calls g_object_unref() on a GObject.

getType
GType getType()

Get the GType of an object.

gType
GType gType [@property getter]

GObject GType property.

self
ObjectG self()

Convenience method to return this cast to a type. For use in D with statements.

getDObject
T getDObject(void* cptr, Flag!"Take" take)

Template to get the D object from a C GObject and cast it to the given D object type.

connectSignalClosure
ulong connectSignalClosure(string signalDetail, DClosure closure, Flag!"After" after)

Connect a D closure to an object signal.

setProperty
void setProperty(string propertyName, T val)

Template for setting a GObject property.

getProperty
T getProperty(string propertyName)

Template for getting a GObject property.

compatControl
size_t compatControl(size_t what, void* data)
bindProperty
gobject.binding.Binding bindProperty(string sourceProperty, gobject.object.ObjectG target, string targetProperty, gobject.types.BindingFlags flags)

Creates a binding between source_property on source and target_property on target.

bindPropertyFull
gobject.binding.Binding bindPropertyFull(string sourceProperty, gobject.object.ObjectG target, string targetProperty, gobject.types.BindingFlags flags, gobject.closure.Closure transformTo, gobject.closure.Closure transformFrom)

Creates a binding between source_property on source and target_property on target, allowing you to set the transformation functions to be used by the binding.

forceFloating
void forceFloating()

This function is intended for #GObject implementations to re-enforce a floating[floating-ref] object reference. Doing this is seldom required: all #GInitiallyUnowneds are created with a floating reference which usually just needs to be sunken by calling gobject.object.ObjectG.refSink.

freezeNotify
void freezeNotify()

Increases the freeze count on object. If the freeze count is non-zero, the emission of "notify" signals on object is stopped. The signals are queued until the freeze count is decreased to zero. Duplicate notifications are squashed so that at most one #GObject::notify signal is emitted for each property modified while the object is frozen.

getData
void* getData(string key)

Gets a named field from the objects table of associations (see gobject.object.ObjectG.setData).

getProperty
void getProperty(string propertyName, gobject.value.Value value)

Gets a property of an object.

getQdata
void* getQdata(glib.types.Quark quark)

This function gets back user data pointers stored via gobject.object.ObjectG.setQdata.

getv
void getv(string[] names, gobject.value.Value[] values)

Gets n_properties properties for an object. Obtained properties will be set to values. All properties must be valid. Warnings will be emitted and undefined behaviour may result if invalid properties are passed in.

isFloating
bool isFloating()

Checks whether object has a floating[floating-ref] reference.

notify
void notify(string propertyName)

Emits a "notify" signal for the property property_name on object.

notifyByPspec
void notifyByPspec(gobject.param_spec.ParamSpec pspec)

Emits a "notify" signal for the property specified by pspec on object.

refSink
gobject.object.ObjectG refSink()

Increase the reference count of object, and possibly remove the floating[floating-ref] reference, if object has a floating reference.

runDispose
void runDispose()

Releases all references to other objects. This can be used to break reference cycles.

setData
void setData(string key, void* data)

Each object carries around a table of associations from strings to pointers. This function lets you set an association.

setProperty
void setProperty(string propertyName, gobject.value.Value value)

Sets a property on an object.

stealData
void* stealData(string key)

Remove a specified datum from the object's data associations, without invoking the association's destroy handler.

stealQdata
void* stealQdata(glib.types.Quark quark)

This function gets back user data pointers stored via gobject.object.ObjectG.setQdata and removes the data from object without invoking its destroy() function (if any was set). Usually, calling this function is only required to update user data pointers with a destroy notifier, for example:

thawNotify
void thawNotify()

Reverts the effect of a previous call to gobject.object.ObjectG.freezeNotify. The freeze count is decreased on object and when it reaches zero, queued "notify" signals are emitted.

watchClosure
void watchClosure(gobject.closure.Closure closure)

This function essentially limits the life time of the closure to the life time of the object. That is, when the object is finalized, the closure is invalidated by calling gobject.closure.Closure.invalidate on it, in order to prevent invocations of the closure with a finalized (nonexisting) object. Also, gobject.object.ObjectG.ref_ and gobject.object.ObjectG.unref are added as marshal guards to the closure, to ensure that an extra reference count is held on object during invocation of the closure. Usually, this function will be called on closures that use this object as closure data.

connectNotify
ulong connectNotify(string detail, T callback, Flag!"After" after)

Connect to Notify signal.

From DatagramBased

conditionCheck
glib.types.IOCondition conditionCheck(glib.types.IOCondition condition)

Checks on the readiness of datagram_based to perform operations. The operations specified in condition are checked for and masked against the currently-satisfied conditions on datagram_based. The result is returned.

conditionWait
bool conditionWait(glib.types.IOCondition condition, long timeout, gio.cancellable.Cancellable cancellable)

Waits for up to timeout microseconds for condition to become true on datagram_based. If the condition is met, true is returned.

createSource
glib.source.Source createSource(glib.types.IOCondition condition, gio.cancellable.Cancellable cancellable)

Creates a #GSource that can be attached to a #GMainContext to monitor for the availability of the specified condition on the #GDatagramBased. The #GSource keeps a reference to the datagram_based.

From Initable

init_
bool init_(gio.cancellable.Cancellable cancellable)

Initializes the object implementing the interface.