libstd/net

TCP/IPv4 sockets: create, bind, listen, accept, connect, socket options and receive timeouts. On Linux it uses the system calls; on Windows Winsock (ws2_32.dll), which the library starts by itself when it is included. socket, bind, listen, accept, connect and the socket options are the same on both systems, with the same names and arguments. A socket is a file descriptor on both systems (on Windows the socket's handle truncated to 32 bits, like any other descriptor), so sys_write, sys_read and sys_close work on it as on a file; SOCKET is its type. The HTTP server that serves this documentation is written with it.

#include <libstd/net>

Includes libstd/stdio, libstd/macro. Same functions and constant names on Linux and Windows: the system-specific part is in wrapper/linux/sysnet and wrapper/windows/sysnet (see Linux and Windows). Links the shared library ws2_32.dll (FFI).

Example

#include <libstd/stdio>
#include <libstd/net>
#include <libstd/file>

addr = new Sockaddr_in()
set_sin_fam(addr, AF_INET, 0)
set_sockip(addr, 127, 0, 0, 1)
set_door(addr, 8000)

fd = socket(AF_INET, SOCK_STREAM, TCP)
set_sockopt(fd, IPPROTO_TCP, TCP_NODELAY, 1)
bind(fd, addr)
listen(fd, 16)
while 1:
    client = accept(fd, 0)
    if client < 0:
        continue
    fprint(client, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")
    close(client)

Constants

NameLinuxWindowsMeaning
TCP66
UDP1717
SOCK_STREAM11
AF_INET22ipv4
TCP_NODELAY11Sends every write at once instead of waiting to fill a segment (Nagle's algorithm off).
SOL_SOCKET11
SO_REUSEADDR22
SO_REUSEPORT1515Linux only: several sockets, even of different processes, listen on the same port and the kernel spreads the connections. Windows has nothing equivalent, and ignoring it would change what the program does.
IPPROTO_IP000
IPPROTO_IPV64141
IPPROTO_TCP66
IPPROTO_UDP1717
SO_LINGER13128
SOCKETintintThe type of a socket: an int file descriptor on both systems.
SOL_SOCKET1165535Level of the options valid for any socket (SOL_SOCKET).
TCP_MAXSEG24Maximum segment size: the largest TCP payload of a single packet.
TCP_CORK3-1002Holds back partial segments until they are full. An optimisation with no Windows option: there it does nothing.
TCP_KEEPIDLE43Seconds of silence before the first keep-alive probe.
TCP_KEEPINTVL517Seconds between two keep-alive probes.
TCP_KEEPCNT616Keep-alive probes left unanswered before the connection is declared dead.
TCP_QUICKACK12-1003Sends ACKs at once instead of delaying them. An optimisation with no Windows option: there it does nothing.
TCP_USER_TIMEOUT1814Milliseconds that sent data may stay unacknowledged before the connection is dropped. On Windows it is TCP_MAXRTMS, with the same meaning.
TCP_DEFER_ACCEPT9-1001Seconds during which accept waits for the client's first data instead of returning at once. An optimisation with no Windows option: there it does nothing.
SO_RCVTIMEO204102Receive timeout; set it with set_recv_timeout (a timeval on Linux, milliseconds on Windows).

Classes

class
Sockaddr_in

A struct sockaddr_in: family and port packed in the first 4 bytes, the IPv4 address, padding. Fill it with set_sin_fam, set_door, set_sockip.

    sin_fam_door int
    ip_addr int
    padding str
class
Linger

The system's struct linger: two int on Linux, one int holding Winsock's two 16-bit fields on Windows. set_linger and get_linger use it the same way on both.

    l_onoff int
    l_linger int

Functions

def set_sin_fam(addr: Sockaddr_in, sin_fam: int, protocol: int) -> None

Writes the address family (AF_INET) into a Sockaddr_in.

def set_door(addr: Sockaddr_in, door: int) -> None

Writes the port (network byte order) into a Sockaddr_in.

def set_sockip(addr: Sockaddr_in, first: int, second: int, third: int, fourth: int) -> None

Writes the IPv4 address given as four octets.

def socket(ip_family: int, sock_type: int, protocol: int) -> SOCKET

Creates a socket (AF_INET, SOCK_STREAM, TCP); returns the descriptor or a negative errno.

def bind(fd_sock: SOCKET, addr: Sockaddr_in) -> int

Binds the socket to the address in addr.

def listen(sock: SOCKET, size_queue: int) -> int

Marks the socket as listening with a backlog of size_queue.

def accept(sock: SOCKET, sock_info: Sockaddr_in) -> SOCKET

Accepts a connection and returns the client descriptor (pass 0 as addr to ignore the peer address).

def connect(sock: SOCKET, addr: Sockaddr_in) -> int

Connects the socket to the address in addr; on error it prints a message and exits, like bind.

def set_sockopt(sock: SOCKET, level: int, optname: int, value: int) -> int

Sets an int option of a socket: 1/0 for the on/off ones (TCP_NODELAY), a number for the others (TCP_KEEPIDLE). Returns 0, or a negative error (-errno on Linux, -WSAGetLastError() on Windows).

def get_sockopt(sock: SOCKET, level: int, optname: int) -> (int, int)

Reads an int option: value, err = get_sockopt(fd, IPPROTO_TCP, TCP_NODELAY), with err 0 or negative as for set_sockopt.

def epoll_create1(flags: int) -> int

A new epoll instance (Linux): its descriptor, or a negative errno. On Windows it stops the build with an error.

def sys_epoll_create1(flags: int) -> int

Linux only.

Raw epoll_create1(2): flags 0 or EPOLL_CLOEXEC (524288).

def sys_fcntl(fd: SOCKET, cmd: int, flags: int) -> int

Linux only.

Raw fcntl(2): sys_fcntl(fd, 3, 0) reads the flags (F_GETFL), sys_fcntl(fd, 4, flags | 2048) makes it non-blocking (F_SETFL, O_NONBLOCK).

def sys_epoll_ctl(epfd: int, op: int, fd: SOCKET, event: str) -> int

Linux only.

Raw epoll_ctl(2): adds (1), removes (2) or modifies (3) fd in the instance. event is the raw struct epoll_event: events at offset 0, data at +4 on x86_64 (12 bytes, packed) and at +8 on aarch64 (16 bytes). 0 or a negative errno.

def sys_epoll_pwait(epfd: int, events: str, maxevents: int, timeout: int) -> int

Linux only.

Raw epoll_pwait(2) without a signal mask (aarch64 has no epoll_wait): waits up to timeout milliseconds (-1 = forever) and writes at most maxevents events into events. The number of events, or a negative errno.

def sys_accept4(fd_sock: SOCKET, flags: int) -> int

Linux only.

Raw accept4(2) without the client address: flags SOCK_NONBLOCK (2048) and/or SOCK_CLOEXEC (524288) are applied to the new socket. The client socket, or a negative errno (-11 when no client is waiting on a non-blocking socket).

def sys_send_nosignal(fd: SOCKET, buf: str, length: long) -> long

Linux only.

Writes to a socket like sys_write, with MSG_NOSIGNAL: if the client has already closed the connection it returns -32 (EPIPE) instead of killing the process with SIGPIPE. The bytes written, or a negative errno.

def sys_socket(ip_family: int, sock_type: int, protocol: int) -> int

Raw socket(2) (Winsock's socket on Windows): the socket, or a negative error.

def sys_connect(sockfd: int, sockaddr: Sockaddr_in) -> int

Raw connect(2): 0 or a negative error.

def sys_bind(fd_sock: int, addr: Sockaddr_in) -> int

Raw bind(2): 0 or a negative error.

def sys_listen(fd_sock: int, size_queue: int) -> int

Raw listen(2): 0 or a negative error.

def sys_accept(fd_sock: int, addr: Sockaddr_in, len_sockaddr_in: &int) -> int

Raw accept(2): the client socket, or a negative error (accept turns it into an error message and exit). The sys_* errors are -errno on Linux and -WSAGetLastError() on Windows.

def sys_getsockopt_n(sockfd: int, level: int, optname: int, optval: long, optlen: &int) -> int
getsockopt for an option of any size: the buffer and its length, which on return is the length written.
def sys_getsockopt(sockfd: int, level: int, optname: int, optval: &int) -> int
getsockopt for an int option, read into *optval; get_sockopt is the same with the value returned.
def sys_setsockopt(sockfd: int, level: int, optname: int, optval: &int) -> int
setsockopt for an int option: sys_setsockopt(fd, TCP, TCP_NODELAY, &one); set_sockopt is the same with the value passed directly.
def sys_setsockopt_n(sockfd: int, level: int, optname: int, optval: long, optlen: int) -> int
setsockopt for an option of arbitrary size (pointer and length).
def set_recv_timeout(sockfd: int, seconds: long) -> int

Sets SO_RCVTIMEO to seconds so that a read on the socket gives up instead of blocking forever (a timeval on Linux, milliseconds on Windows).

def set_linger(sockfd: int, onoff: int, seconds: int) -> int

Sets SO_LINGER: with onoff 1, close waits up to seconds for queued data to leave (0 seconds closes at once with a reset); with 0, close returns at once, the default. Returns 0 or a negative error.

def get_linger(sockfd: int) -> (int, int)

Reads SO_LINGER: onoff, seconds = get_linger(fd), or (-1, error).

def sys_shutdown(fd: SOCKET, how: int) -> None

Windows only.

Raw shutdown(2) on a socket (SHUT_RD/SHUT_WR/SHUT_RDWR).

Internal helpers

Used by the functions above; not meant to be called directly.