Skip to content

Networking

Chloë Strainge edited this page Oct 14, 2026 · 1 revision

Sockets, DNS, and TLS

std::net groups network facilities. Import a child module when a narrower namespace makes code clearer.

Module Main operations
std::net::dns Resolve a hostname to addresses.
std::net::tcp Connect, listen, accept reliable byte streams.
std::net::udp Bind, send, receive datagrams.
std::net::unix Local Unix-domain stream sockets.
std::net::tls Verified encrypted streams.

Endpoints contain host and port. Connections expose readers and writers; the byte APIs are shared with files and memory.

A complete local exchange

Binding port zero asks the operating system to select a free local port. This example connects before accepting, sends a short message, and closes all handles.

import std::net::tcp
import std::io
let $listener = std::net::tcp::listen "127.0.0.1" 0
try
{
    let $address = $listener.address
    let $sender = std::net::tcp::connect $address.host $address.port
    let $receiver = $listener.accept
    try
    {
        $sender.writer.write std::io::Bytes("ping")
        $sender.shutdown_write
        echo $receiver.reader.read_all.decode_utf8
    }
    finally { $sender.close; $receiver.close }
}
finally { $listener.close }
ping

These are blocking operations. A listener or read can wait for its peer; use a protocol that defines message boundaries and deadlines rather than assuming a single socket read equals one message.

Datagram and encrypted connections

UDP receives a Datagram with bytes, peer, and truncated; check truncation before treating the payload as complete. Sending preserves datagram boundaries.

TLS wraps TCP with peer verification. Supply the hostname used for verification; optional trust bytes configure an explicit trust source. Closing adapters and connections matters even after an error.

Use HTTP for request/response semantics, or Framing and RPC for message boundaries on a byte stream. Process supervision can bound a whole script while developing an experimental network service.


Related: Bytes and I/O · HTTP · Framing and RPC

Clone this wiki locally