Skip to content

TCP

Connect, listen, and move bytes through TCP sockets.

tcp is a module — import tcp — and it is byte transport and nothing more. tcp.connect and tcp.listen return opaque resource handles; read_into and write_all move bytes between the kernel and a guest []byte with no staging copy. Framing, encoding, retries, and protocol semantics are yours.

tcp means a reliable ordered stream, and which kind is a fact about the address:

Spelled What it is
"127.0.0.1:8080", "[::1]:443", "example.com:443" TCP
"unix:/run/app.sock" a Unix stream socket
either, then starttls_* TLS over the one underneath

The module is not renamed for the other two, because a separate unix import would duplicate the whole surface to say what a five-character scheme says. The scheme is what makes it decidable: without it, /run/app.sock is a hostname to look up.

read_into, write_all and write_some are the same three calls whatever is underneath.

A client exchange

import tcp

fn ping(addr string, msg string) int ! tcp.Error {
    conn := tcp.connect(addr)?
    written := conn.write_all(msg.to_bytes())?

    mut buf: []byte = List.new[byte](1024)
    n := conn.read_into(&mut buf, 1024)?
    conn.close()

    println("sent ${written}, received ${n}")
    return n
}

fn main() void {
    match ping("127.0.0.1:9000", "ping\n") {
        Ok(n) => println("${n} bytes back")
        Err(ConnectionRefused { addr }) => println("refused by ${addr}")
        Err(Other) => println("a failure with no kind of its own")
        Err(e) => println("connection failed")
    }
}

Addresses are host:port text. tcp.connect suspends until the socket is connected.

Reading

read_into(&buf, max) reserves max spare bytes on buf, lets the kernel fill that tail in place, and returns the count actually read. The count can be smaller than max even on a healthy connection; 0 means the peer closed. max <= 0 returns Ok(0) without touching the socket.

It appends — it never clears the buffer — so track the new region yourself:

import tcp

fn drain(conn tcp.Conn) int {
    mut buf: []byte = []
    mut total := 0
    for {
        before := buf.len()
        n := match conn.read_into(&mut buf, 4096) {
            Ok(c) => c
            Err(e) => break
        }
        if n == 0 {
            println("peer closed after ${total} bytes")
            break
        }
        println("received ${n} bytes at offset ${before}")
        total = total + n
    }
    conn.close()
    return total
}

fn main() void {
    match tcp.connect("127.0.0.1:9000") {
        Ok(conn) => println("${drain(conn)} bytes total")
        Err(e) => println("connect failed")
    }
}

A clean EOF (Ok(0)) and a reset (Err) are different events. EOF means the peer finished; a reset means the exchange was interrupted and any in-flight request is of unknown status.

Writing

write_all(buf) takes []byte — owned or a window — and loops host-side until every byte is sent, returning the count. An empty buffer returns Ok(0) with no I/O.

import tcp

fn send_all(addr string, lines []string) int ! tcp.Error {
    conn := tcp.connect(addr)?
    mut sent := 0
    for line in lines {
        sent = sent + conn.write_all(line.to_bytes())?
    }
    conn.close()
    return sent
}

fn main() void {
    mut lines: []string = List.new[string]()
    lines.push("HELLO\n")
    lines.push("BYE\n")
    match send_all("127.0.0.1:9000", lines) {
        Ok(n) => println("wrote ${n} bytes")
        Err(e) => println("write failed")
    }
}

string.to_bytes() yields the []byte that write_all expects.

When the count matters

write_all answers Err(Timeout) if a deadline cuts it short, and the count it had reached is gone with it — so “nothing sent” and “half a frame sent” become indistinguishable, and the only safe recovery is destroying the connection. That is a heavy price for a slow peer.

write_some(slice) is the primitive underneath: it waits once for writability, writes once, and answers what it managed. Loop it and the count is yours.

import tcp

fn send_keeping_count(addr string, payload []byte) int ! tcp.Error {
    conn := tcp.connect(addr)?
    mut sent := 0
    for _i in 0..4096 {
        if sent >= payload.len() {
            break
        }
        rest := match payload.get(sent.to_usize()..payload.len().to_usize()) {
            Some(r) => r
            None => break
        }
        w := conn.write_some(rest)?
        sent = sent + w
    }
    conn.close()
    return sent
}

fn main() void {
    mut payload: []byte = List.new[byte](4)
    payload.push(1u8)
    payload.push(2u8)
    match send_keeping_count("127.0.0.1:9000", payload) {
        Ok(n) => println("sent ${n}")
        Err(e) => println("send failed")
    }
}

A short answer is also the backpressure signal: a peer that took less than you offered is behind, and you know it without inferring it from a clock.

Half-close

finish_writing() sends FIN on the write half and leaves the read half open, so the peer sees end-of-request and you can still read its answer. close() takes both directions, which is a different thing.

This is what every protocol needs when the response length is the peer’s to decide — an HTTP/1.0-style Connection: close, a nc -N pipe, parts of SMTP and LMTP.

import tcp

fn ask_and_read_to_eof(addr string, request []byte) int ! tcp.Error {
    conn := tcp.connect(addr)?
    conn.write_all(request)?
    // The peer now sees EOF on its read, which is what tells it the
    // request is complete. The read half below is still open.
    conn.finish_writing()?
    mut answer: []byte = List.new[byte](4096)
    mut total := 0
    for _i in 0..4096 {
        n := conn.read_into(&mut answer, 4096)?
        if n == 0 {
            break
        }
        total = total + n
    }
    conn.close()
    return total
}

fn main() void {
    match ask_and_read_to_eof("127.0.0.1:9000", "PING\n".to_bytes()) {
        Ok(n) => println("read ${n} bytes")
        Err(e) => println("exchange failed")
    }
}

Who is at the other end

peer_ip() and peer_port() answer the address a connection was accepted from or dialled to. local_ip() and local_port() answer this end’s own — and it is local_ip(), not the port, that says which interface a connection on a multi-homed machine left by. The addresses are net.IpAddr values, None for a socket the platform will not name, which is not an error, and the ports are u16. peer_addr() and local_addr() answer the address and the port together, as the net.SocketAddr a reply, a log line or an allow-list holds. The host writes the words into the answer: no text is rendered, parsed or allocated, and a connection remembers both ends from its making, so asking costs no call to the network stack.

A v4 client reaching a dual-stack listener answers 127.0.0.1 and not ::ffff:127.0.0.1: the kernel’s mapped spelling is undone on the way out, so an allow-list written on one machine means the same thing on another. A unix: connection has no IP address: peer_ip() is None, both ports are 0, and the peer’s path is peer_path() (local_path() for this end’s own, and Listener.path() for a listener’s), None for an IP connection and for a peer with no name.

tcp.listen_unix(addr, mode) binds a unix: socket whose file carries mode, a tcp.UnixMode: UnixMode.owner_only() (0o600), owner_and_group() or everyone(), or UnixMode.of(0o640), which is None unless the bits are nine permission bits.

A listener bound to 0.0.0.0 answers 0.0.0.0 from ip(), and that is not a defect: an unspecified bind is on every interface, so there is no one address to name. Ask an accepted connection instead.

import net
import tcp

fn banned(ip net.IpAddr?) bool {
    return ip == Some(net.IpAddr.v4(10, 0, 0, 9))
}

fn serve_one(l tcp.Listener) int ! tcp.Error {
    conn := l.accept()?
    if banned(conn.peer_ip()) {
        conn.close()
        return 0
    }
    mut buf: []byte = List.new[byte](64)
    n := conn.read_into(&mut buf, 64)?
    conn.close()
    return n
}

fn main() void {
    match tcp.listen("127.0.0.1:0") {
        Ok(l) => {
            match serve_one(l) {
                Ok(n) => println("read ${n}")
                Err(e) => println("failed")
            }
        }
        Err(e) => println("bind failed")
    }
}

That is the “per-peer request rate” row of the Overload table below: a bound you cannot apply without knowing who the peer is.

Socket options

Method What it does
no_delay(on) Nagle off — a small write goes out without waiting to coalesce
keep_alive(idle_ms) probe an idle connection, so a peer that vanished is noticed; 0 off
linger(seconds) how long close waits for unsent data; negative turns it off
hops(ttl) the IP time-to-live on packets this connection sends
recv_buffer(bytes) / send_buffer(bytes) the kernel’s buffers for this socket

Each answers Result[void, tcp.Error] and is synchronous.

keep_alive is the one worth reaching for by default on a long-lived server. Without it, a connection whose peer vanished behind a NAT or a load balancer stays open until something else times it out — the platform’s own default is two hours on Linux — and the task reading it is parked that whole time. Nagle, by contrast, you can usually sidestep by assembling into one write_all.

Reading an option back

Every setter has a _now getter, and they round-trip: what linger_now() answers is what linger() takes, with None for a socket that does not linger. The one that does not round-trip is the reason the getters exist — Linux doubles a buffer size you ask for and then clamps it to net.core.rmem_max, so the number a program set and the number it has are routinely different.

import tcp

fn tuned(conn tcp.Conn) int ! tcp.Error {
    conn.recv_buffer(65536)?
    // Not necessarily 65536: the kernel decides, and this is how to find out.
    return conn.recv_buffer_now()?
}

fn main() void {
    match tcp.connect("127.0.0.1:9000") {
        Ok(conn) => {
            match tuned(conn) {
                Ok(n) => println("receive buffer is ${n}")
                Err(e) => println("failed")
            }
        }
        Err(e) => println("connect failed")
    }
}

mtu() answers the path MTU the kernel discovered, and is Linux only — elsewhere it is Err(Unsupported) rather than a guess.

last_error() is the only way to learn why a connection died after the fact: an asynchronous failure the kernel recorded with no read or write of yours outstanding to receive it. It has three answers because they need three recoveries — Ok(None) is a healthy socket, Ok(Some(e)) is what it recorded, Err(e) is the call itself failing — and reading it clears it.

What a listener hands out

accept_no_delay(on) and accept_hops(ttl) are recorded on the listener and applied to every connection it accepts. A request/response server otherwise pays a boundary crossing and a syscall per connection for a setting that never varies.

import tcp

fn quick(addr string) Result[tcp.Listener, tcp.Error] {
    l := match tcp.listen(addr) { Ok(l) => l Err(e) => return Err(e) }
    match l.accept_no_delay(true) { Ok(k) => {} Err(e) => return Err(e) }
    return Ok(l)
}

fn main() void {
    match quick("127.0.0.1:0") {
        Ok(l) => l.close()
        Err(e) => println("bind failed")
    }
}

accept_no_delay_now() answers Option[bool], not bool: None means this listener was never told, which is not the same as being told to leave it off.

Bounding a connect, and leaving by a named address

tcp.connect(addr) has no bound of its own — a connect to an address that silently drops packets sits in retransmission for the kernel’s own timeout, which is minutes. connect_within(addr, timeout_ms) is the one worth using.

The bound is per attempt. A name that resolves to four addresses and a two-second bound may take eight seconds to give up, because trying four addresses is what connecting to that name means — and each one being bounded is the point: a black-holed AAAA cannot eat the whole budget before the v4 address is reached.

connect_from(addr, source, timeout_ms) names the local address to leave by, for a machine with several interfaces or several source addresses on one. source is a net.SocketAddr — 10.0.0.7 and port 0 for “that interface, any port”. A source address of the wrong family for the destination is Err(AddressNotAvailable) rather than a silent fall back to the kernel’s choice.

Dual-stack, said out loud

tcp.listen("[::]:8080") binds a dual-stack socket on every platform: a v4 client reaches it, and peer_ip() answers the v4 address. It is not left to the platform’s default, which Linux and Windows and the BSDs disagree about — so identical source behaves the same wherever it runs.

tcp.listen_v6_only(addr) is the other choice, said out loud; tcp.listen_using(addr, shared, v6_only) takes both switches at once. tcp.listen_shared(addr) asks for SO_REUSEPORT, so several sockets — one per reactor lane — may hold one port and have the kernel spread connections between them.

TLS on a socket that is already open

The protocols that need this do not begin encrypted. SMTP, IMAP, POP3, LDAP and PostgreSQL all speak a few lines of cleartext, agree to upgrade, and hand the same socket to TLS — so the upgrade is a call on a live connection at a moment the protocol picks, not a scheme on the address.

import tcp

fn upgraded(addr string, name string) string ! tcp.Error {
    conn := tcp.connect(addr)?
    // …speak the cleartext part of the protocol here…
    conn.starttls_client(name)?
    return conn.tls_version()
}

fn main() void {
    match upgraded("127.0.0.1:9000", "example.com") {
        Ok(v) => println("negotiated ${v}")
        Err(HandshakeFailed) => println("the certificate did not check out")
        Err(e) => println("failed")
    }
}

The handle keeps its identity: the same Conn reads and writes afterwards, through the record layer, with nothing else changed.

Call Role
starttls_client(name) verify the server against name and the platform’s roots
starttls_client_trusting(name, ca_path) trust the roots in ca_path instead of the platform’s
starttls_server(cert_path, key_path) present a chain and a key, both paths

Trusting a named CA replaces rather than extends, because a private CA added alongside the public ones is not the isolation an operator asking for one wanted.

tls_version(), tls_suite() and tls_server_name() answer facts about the negotiated session. A connection that is not encrypted answers "" — which is how a program asks whether it is. tls_server_name() is for the server side: it is the SNI the client asked for, and a client already passed its name in.

Two things to know before relying on it. A failed handshake destroys the connection, and the handle with it: there is no way back to cleartext once a ClientHello is on the wire, so a restored plain socket would look usable and would not be. And write_some over TLS answers the whole count rather than a short one, because a record is encrypted whole — over TLS the backpressure signal is the time a call took, not a short answer.

Servers

tcp.listen(addr) binds; accept() suspends until a client arrives. Spawn the handler so a slow peer cannot stall the accept loop.

import tcp

fn serve(conn tcp.Conn) int {
    mut buf: []byte = List.new[byte](4096)
    mut total := 0
    for {
        n := match conn.read_into(&mut buf, 4096) {
            Ok(c) => c
            Err(e) => break
        }
        if n == 0 {
            break
        }
        total = total + n
    }
    conn.close()
    return total
}

fn main() void {
    listener := match tcp.listen("127.0.0.1:9000") {
        Ok(l) => l
        Err(AddressInUse { addr }) => {
            println("${addr} is already bound")
            return
        }
        Err(e) => {
            println("bind failed")
            return
        }
    }

    for i in 0..8 {
        match listener.accept() {
            Ok(conn) => {
                worker := spawn { serve(conn) }
                println("connection ${i} dispatched")
            }
            Err(e) => {
                println("accept failed; stopping")
                break
            }
        }
    }
    listener.close()
}

The listener stays owned by the accepting scope; each connection is handed to the task responsible for its lifetime. Do not copy an opaque handle into long-lived data and treat each copy as an independent socket.

Framing

A protocol loop must preserve bytes that arrive before and after a message boundary. Here is a two-byte big-endian length prefix with a size cap:

import tcp

const MAX_FRAME: int = 65536

fn frame_len(buf &[]byte, start int) int {
    hi := int(buf.get(start) ?? 0u8)
    lo := int(buf.get(start + 1) ?? 0u8)
    return hi * 256 + lo
}

fn read_frames(conn tcp.Conn) int {
    mut buf: []byte = List.new[byte](4096)
    mut consumed := 0
    mut frames := 0

    for {
        available := buf.len() - consumed
        if available >= 2 {
            size := frame_len(buf, consumed)
            if size > MAX_FRAME {
                println("frame of ${size} exceeds the cap")
                break
            }
            if available >= 2 + size {
                frames = frames + 1
                consumed = consumed + 2 + size
                continue
            }
        }

        n := match conn.read_into(&mut buf, 4096) {
            Ok(c) => c
            Err(e) => break
        }
        if n == 0 {
            if buf.len() > consumed {
                println("EOF with a partial frame — truncated, not complete")
            }
            break
        }
    }

    conn.close()
    return frames
}

fn main() void {
    match tcp.connect("127.0.0.1:9000") {
        Ok(conn) => println("${read_frames(conn)} frames read")
        Err(e) => println("connect failed")
    }
}

The three invariants worth copying: parse only when a complete frame is present, check the declared size against a cap before trusting it, and treat EOF with a partial frame as truncation rather than clean completion.

Length prefixes need a fixed byte order and overflow checks; delimiters need an escape rule and a maximum search length; text protocols need an explicit encoding. The TCP API deliberately guesses none of that.

Errors

tcp.Error names address conflicts (AddressInUse, AddressNotAvailable, InvalidAddress), connection failures (ConnectionRefused, Unreachable, ConnectionReset, ConnectionAborted, NotConnected), Timeout { duration_ms }, PermissionDenied { message }, InvalidHandle, Unsupported, HandshakeFailed, Unflushed, InvalidArgument, and Other.

Unsupported and InvalidAddress are kept apart because the recoveries are opposite: a malformed argument is a bug in the caller, and a missing capability is a fact about where the program is running — starttls in a build without TLS, mtu() off Linux, a TCP-level option on a Unix socket.

HandshakeFailed is the one that must never be retried through: the connection was reached, the peer answered, and what it said did not check out.

Each of those has a producer: the host answers a typed fault, the wrappers build the variant that names it, and Other is what is left when a platform reports something with no variant of its own. Match the named ones; keep an arm for Other because a kernel can always surprise you, not because it is the one that fires.

Timeout { duration_ms } is either clock: the kernel’s own — a connect that gave up in retransmission — or an ambient deadline armed with time.push_deadline, which the reactor enforces per call. duration_ms is 0 for a bound this side was only told about rather than set.

Lifetime

tcp.Listener and tcp.Conn implement Drop, so normal scope exit, ? propagation, and cancellation all release the host socket. close() is synchronous, idempotent, and only needed to release early inside a long-lived scope. A closed handle must not be used again.

Overload

A listening server needs bounds at several levels:

Bound Protects
Concurrent connection count tasks, handles, memory
Per-read maximum guest allocation growth
Frame or request size parser memory and CPU
Idle / read / write deadline resources held by stalled peers
Per-peer request rate downstream work — needs peer_ip()
keep_alive on accepted connections tasks parked on peers that vanished
connect_within on every dial tasks parked in the kernel’s retransmission

Spawning one unbounded task per accepted connection just moves overload from the accept loop into memory and scheduling. Acquire capacity before dispatching, and make cancellation close the listener plus every owned connection.

Effects

Connect, listen, accept, read, and both writes carry Suspend — including tcp.listen, whose bind completes inline but uses the suspending call ABI.

starttls_client, starttls_client_trusting and starttls_server carry Suspend too: a certificate is a file and a handshake is several round trips.

close, finish_writing, peer_addr, peer_ip, peer_path, peer_port, local_addr, local_ip, local_path, local_port, every socket option in both directions, and the three tls_* readers are synchronous: each is one syscall answered from the socket table, or a fact already decided and sitting in the session, so none of them can wait and none pays a resume round-trip. close being synchronous is what lets it run from a Drop body.

A suspending read keeps the guest byte allocation alive across the host operation; raw pointers stay an implementation detail of the safe wrappers.

For cancellation behavior see Cancellation; for structured child tasks see Spawning.

Type to search…

↑↓ navigate↵ selectEsc close