A 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.
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 SocketClient
, SocketService and
SocketConnection. However there may be cases where direct use of Socket is useful.
Socket 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 Socket and
Socket.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.
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 Socket causes the signal sigpipe to be ignored for the
remainder of the program. If you are writing a command-line utility that uses 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, Socket is not inherently thread safe. To use a Socket
concurrently from multiple threads, you must implement your own locking.
Example: Sockets:
public static void server (SocketAddress address) throws Error {
Socket socket = new Socket (SocketFamily.IPV4, SocketType.STREAM, SocketProtocol.TCP);
assert (socket != null);
socket.bind (address, true);
socket.set_listen_backlog (10);
socket.listen ();
for (int i = 0; true ; i = (i + 1) % 10) {
Socket connection = socket.accept ();
print (@"Accepted ($i)\n");
connection.send (i.to_string ().data);
}
}
public static void client (SocketAddress address) throws Error {
Socket socket = new Socket (SocketFamily.IPV4, SocketType.STREAM, SocketProtocol.TCP);
assert (socket != null);
socket.connect (address);
print ("Connected\n");
uint8 buffer[100];
ssize_t len;
len = socket.receive (buffer);
stdout.write (buffer, len);
print ("\n");
}
public static int main (string[] args) {
try {
if (args.length != 2) {
print ("%s server|client\n", args[0]);
return 0;
}
InetAddress address = new InetAddress.loopback (SocketFamily.IPV4);
InetSocketAddress inetaddress = new InetSocketAddress (address, 2001);
if (args[1] == "server") {
server (inetaddress);
} else if (args[1] == "client") {
client (inetaddress);
} else {
print ("Unknown option.\n");
}
} catch (Error e) {
print ("Error: %s\n", e.message);
}
return 0;
}
valac --pkg gio-2.0 GLib.Socket.vala
- public Socket accept (Cancellable? cancellable = null) throws Error
Accept incoming connections on a connection-based socket.
- public bool bind (SocketAddress address, bool allow_reuse) throws Error
When a socket is created it is attached to an address family, but it
doesn't have an address in this family.
- public bool check_connect_result () throws Error
Checks and resets the pending connect error for the socket.
- public bool close () throws Error
Closes the socket, shutting down any active connection.
- public IOCondition condition_check (IOCondition condition)
Checks on the readiness of this to
perform operations.
- public bool condition_timed_wait (IOCondition condition, int64 timeout_us, Cancellable? cancellable = null) throws Error
Waits for up to timeout_us
microseconds for
condition
to become true on this.
- public bool condition_wait (IOCondition condition, Cancellable? cancellable = null) throws IOError
Waits for condition
to become true on
this.
- public bool connect (SocketAddress address, Cancellable? cancellable = null) throws Error
Connect the socket to the specified remote address.
- public SocketSource create_source (IOCondition condition, Cancellable? cancellable = null)
Creates a SocketSource
that can be attached to a gmaincontext to monitor for the availability of the specified
condition
on the socket.
- public ssize_t get_available_bytes ()
Get the amount of data pending in the OS input buffer, without
blocking.
- public bool get_blocking ()
Gets the blocking mode of the socket.
- public bool get_broadcast ()
Gets the broadcast setting on this;
if true, it is possible to send packets to broadcast addresses.
- public Credentials get_credentials () throws Error
Returns the credentials of the foreign process connected to this
socket, if any (e.
- public SocketFamily get_family ()
Gets the socket family of the socket.
- public int get_fd ()
Returns the underlying OS socket object.
- public bool get_keepalive ()
Gets the keepalive mode of the socket.
- public int get_listen_backlog ()
Gets the listen backlog setting of the socket.
- public SocketAddress get_local_address () throws Error
Try to get the local address of a bound socket.
- public bool get_multicast_loopback ()
Gets the multicast loopback setting on this
; if true (the default), outgoing multicast packets will be looped back to multicast
listeners on the same host.
- public uint get_multicast_ttl ()
Gets the multicast time-to-live setting on
this; see set_multicast_ttl for more details.
- public bool get_option (int level, int optname, out int value) throws Error
Gets the value of an integer-valued option on
this, as with getsockopt
.
- public SocketProtocol get_protocol ()
Gets the socket protocol id the socket was created with.
- public SocketAddress get_remote_address () throws Error
Try to get the remote address of a connected socket.
- public SocketType get_socket_type ()
Gets the socket type of the socket.
- public uint get_timeout ()
Gets the timeout setting of the socket.
- public uint get_ttl ()
Gets the unicast time-to-live setting on
this; see set_ttl for more details.
- public bool is_closed ()
Checks whether a socket is closed.
- public bool is_connected ()
Check whether the socket is connected.
- public bool join_multicast_group (InetAddress group, bool source_specific, string? iface) throws Error
Registers this to receive multicast
messages sent to group
.
- public bool join_multicast_group_ssm (InetAddress group, InetAddress? source_specific, string? iface) throws Error
Registers this to receive multicast
messages sent to group
.
- public bool leave_multicast_group (InetAddress group, bool source_specific, string? iface) throws Error
Removes this 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).
- public bool leave_multicast_group_ssm (InetAddress group, InetAddress? source_specific, string? iface) throws Error
Removes this 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).
- public bool listen () throws Error
Marks the socket as a server socket, i.
- public ssize_t receive (uint8[] buffer, Cancellable? cancellable = null) throws Error
Receive data (up to buffer.length
bytes) from a socket.
- public ssize_t receive_from (out SocketAddress address, uint8[] buffer, Cancellable? cancellable = null) throws Error
Receive data (up to buffer.length
bytes) from a socket.
- public ssize_t receive_message (out SocketAddress? address, InputVector[] vectors, out SocketControlMessage[]? messages, ref int flags, Cancellable? cancellable = null) throws Error
Receive data from a socket.
- public int receive_messages (InputMessage[] messages, int flags, Cancellable? cancellable = null) throws Error
Receive multiple data messages from this
in one go.
- public ssize_t receive_with_blocking (uint8[] buffer, bool blocking, Cancellable? cancellable = null) throws Error
This behaves exactly the same as
receive, except that the choice of blocking or non-blocking behavior is
determined by the blocking
argument rather than by this's properties.
- public ssize_t send (uint8[] buffer, Cancellable? cancellable = null) throws Error
Tries to send buffer.length
bytes from buffer
on the socket.
- public ssize_t send_message (SocketAddress? address, OutputVector[] vectors, SocketControlMessage[]? messages, int flags, Cancellable? cancellable = null) throws Error
Send data to address
on this
.
- public PollableReturn send_message_with_timeout (SocketAddress? address, OutputVector[] vectors, SocketControlMessage[]? messages, int flags, int64 timeout_us, out size_t bytes_written, Cancellable? cancellable = null) throws Error
This behaves exactly the same as
send_message, except that the choice of timeout behavior is determined by
the timeout_us
argument rather than by this's properties.
- public int send_messages (OutputMessage[] messages, int flags, Cancellable? cancellable = null) throws Error
Send multiple data messages from this
in one go.
- public ssize_t send_to (SocketAddress? address, uint8[] buffer, Cancellable? cancellable = null) throws Error
Tries to send buffer.length
bytes from buffer
to address
.
- public ssize_t send_with_blocking (uint8[] buffer, bool blocking, Cancellable? cancellable = null) throws Error
This behaves exactly the same as
send, except that the choice of blocking or non-blocking behavior is determined by
the blocking
argument rather than by this's properties.
- public void set_blocking (bool blocking)
Sets the blocking mode of the socket.
- public void set_broadcast (bool broadcast)
Sets whether this should allow
sending to broadcast addresses.
- public void set_keepalive (bool keepalive)
Sets or unsets the so_keepalive flag
on the underlying socket.
- public void set_listen_backlog (int backlog)
Sets the maximum number of outstanding connections allowed when
listening on this socket.
- public void set_multicast_loopback (bool loopback)
Sets whether outgoing multicast packets will be received by sockets
listening on that multicast address on the same host.
- public void set_multicast_ttl (uint ttl)
Sets the time-to-live for outgoing multicast datagrams on
this.
- public bool set_option (int level, int optname, int value) throws Error
Sets the value of an integer-valued option on
this, as with setsockopt
.
- public void set_timeout (uint timeout)
Sets the time in seconds after which I/O operations on
this will time out if they have not yet completed.
- public void set_ttl (uint ttl)
Sets the time-to-live for outgoing unicast packets on
this.
- public bool shutdown (bool shutdown_read, bool shutdown_write) throws Error
Shut down part or all of a full-duplex connection.
- public bool speaks_ipv4 ()
Checks if a socket is capable of speaking IPv4.