Socket module

accept

procedure · 1 overloadSource

Takes the next pending connection from the listening socket s and returns it with the peer's IPv4 address.

A blocking listener waits for a connection. A non-blocking one returns INVALID_SOCKET at once when none is pending, and get_last_socket_error() then equals SOCKET_WOULDBLOCK; any other error also gives INVALID_SOCKET, with the address left zeroed. The returned socket is owned by the caller, who releases it with close_and_reset. Whether it starts in non-blocking mode depends on the platform, so call set_blocking to pick one explicitly. Use accept_v6 for a listener bound to an IPv6 address; an IPv4 record cannot hold an IPv6 peer.

Example
assert(socket_init());

listener := socket(AF_INET, .SOCK_STREAM, .TCP);
defer close_and_reset(*listener);

assert(bind(listener, "127.0.0.1", 0) == 0);
assert(listen(listener, 4) == 0);

local: sockaddr_in;
length: socklen_t = size_of(sockaddr_in);
assert(getsockname(listener, cast(*sockaddr) *local, *length) == 0);

client := socket(AF_INET, .SOCK_STREAM, .TCP);
defer close_and_reset(*client);
assert(connect(client, cast(*sockaddr) *local, length) == 0);

peer, from := accept(listener);
defer close_and_reset(*peer);

assert(peer != INVALID_SOCKET);
assert(from.sin_family == AF_INET);

Doesn't run in the browser (skipped on wasm).

accept :: (s: Socket) -> (Socket, sockaddr_in)

Takes the next pending connection from the listening socket s and returns it with the peer's IPv4 address.

A blocking listener waits for a connection. A non-blocking one returns INVALID_SOCKET at once when none is pending, and get_last_socket_error() then equals SOCKET_WOULDBLOCK; any other error also gives INVALID_SOCKET, with the address left zeroed. The returned socket is owned by the caller, who releases it with close_and_reset. Whether it starts in non-blocking mode depends on the platform, so call set_blocking to pick one explicitly. Use accept_v6 for a listener bound to an IPv6 address; an IPv4 record cannot hold an IPv6 peer.

Parameters

s: Socket

Returns

Socket
sockaddr_in
Example
assert(socket_init());

listener := socket(AF_INET, .SOCK_STREAM, .TCP);
defer close_and_reset(*listener);

assert(bind(listener, "127.0.0.1", 0) == 0);
assert(listen(listener, 4) == 0);

local: sockaddr_in;
length: socklen_t = size_of(sockaddr_in);
assert(getsockname(listener, cast(*sockaddr) *local, *length) == 0);

client := socket(AF_INET, .SOCK_STREAM, .TCP);
defer close_and_reset(*client);
assert(connect(client, cast(*sockaddr) *local, length) == 0);

peer, from := accept(listener);
defer close_and_reset(*peer);

assert(peer != INVALID_SOCKET);
assert(from.sin_family == AF_INET);

Doesn't run in the browser (skipped on wasm).

See also