Module std::net

TCP networking.

Create TCP servers and clients for bidirectional byte-stream communication. Handle types (Listener, Connection) provide type-safe wrappers over raw file descriptors.

Error Handling

listen and connect return Result with net.NetError. A connection speaks the pipe verbs: recv() yields Option<bytes> (None is EOF, a transport failure traps), send(bytes) returns Result<(), SendError> and finish() half-closes. Other protocol modules have their own result types; check their signatures when handling errors:

import std.net;

fn dial(addr: string) -> Result<net.Connection, net.NetError> {
    net.connect(addr)
}

fn main() {
    match dial("localhost:9000") {
        .Ok(conn) => println("connected"),
        .Err(e) => {
            match e {
                NetError.ConnectionRefused(_) => println("nobody home"),
                NetError.TimedOut(_)          => println("timed out"),
                _                              => println("network error"),
            }
        }
    }
}

Examples

import std.net;

fn main() {
    let listener = match net.listen(":9000") { .Ok(value) => value, .Err(error) => panic("network operation failed"), };
    let conn = listener.accept();
    // An echo turn: `None` is the peer's EOF; `send` answers `Closed` once
    // the peer is gone, which an echo server treats as the end.
    if let .Some(data) = conn.recv() {
        let _ = conn.send(data);
    }
    conn.close();
}

Contents

Functions

Function net_error_from_errno

pub fn net_error_from_errno(errno: i64) -> NetError

Map an OS errno integer to a structured NetError variant.

The i64 payload carried in each variant is the raw OS errno so callers can inspect the platform value. errno=0 (no OS error) maps to Other(0).

Covers TCP, QUIC, TLS, HTTP, WebSocket, and DNS failure codes.

Function abi_i32_max

pub fn abi_i32_max() -> i64

Largest value the i32 parameters of the networking C ABI can carry.

Function duration_ms

pub fn duration_ms(context: string, ms: i64) -> Result<i64, NetError>

Validate a millisecond duration that the C ABI carries as an i32.

context names the calling API so the rejection identifies its origin.

Function size_arg

pub fn size_arg(context: string, size: i64) -> Result<i64, NetError>

Validate a byte count that the C ABI carries as an i32.

Function port_arg

pub fn port_arg(context: string, port: i64) -> Result<i64, NetError>

Validate a TCP/UDP port number.

Function parse_endpoint

pub fn parse_endpoint(context: string, addr: string) -> Result<Endpoint, NetError>

Parse host:port, :port, or [ipv6]:port into a validated Endpoint.

This is the single endpoint grammar for the networking modules. A missing port, a non-numeric port, a port outside 0..=65535, an unbracketed IPv6 literal, and an unterminated bracket are all rejected here, before any address string reaches a resolver or a native connect.

An empty host means "this machine": :9000 yields host 127.0.0.1.

Examples

import std.net;

fn main() {
    match net.parse_endpoint("net.connect_timeout", "[::1]:9000") {
        .Ok(ep) => println(f"{ep.host} {ep.port}"),
        .Err(err) => println(err),
    }
}

Function net_error_timed_out

pub fn net_error_timed_out() -> NetError

Construct a NetError.TimedOut(0) value without a platform-specific errno. Useful for in-process deadline expiry where there is no OS error to map.

Function net_error_cancelled

pub fn net_error_cancelled() -> NetError

Construct a NetError.Cancelled(0) value without a platform-specific errno. Useful for in-process cancellation where there is no OS error to map.

Function listen

pub fn listen(addr: string) -> Result<Listener, NetError>

Create a TCP listener bound to the given address.

Returns Err(NetError) instead of panicking on bind failure.

Examples

import std.net;

fn main() {
    match net.listen(":9000") {
        .Ok(ln) => { /* accept connections */ }
        .Err(net.NetError.AddressInUse(_)) => println("port already taken"),
        .Err(e) => println("bind failed"),
    }
}

Function connect

pub fn connect(addr: string) -> Result<Connection, NetError>

Connect to a TCP server at the given address.

Returns Err(NetError) instead of panicking on failure.

Examples

import std.net;

fn main() {
    match net.connect("localhost:9000") {
        .Ok(conn) => { /* use conn */ }
        .Err(net.NetError.ConnectionRefused(_)) => println("nothing listening"),
        .Err(e) => println("connect failed"),
    }
}

Function connect_timeout

pub fn connect_timeout(addr: string, timeout_sec: i64, timeout_usec: i64) -> Result<Connection, NetError>

Connect to a TCP server with a timeout, reporting invalid input and connect failure instead of fabricating a default.

The address is parsed by the shared endpoint authority, so an unbracketed IPv6 literal, a non-numeric port, and a missing port are all rejected before the native connect rather than becoming host 127.0.0.1 port 0. The deadline is accumulated with overflow checks and validated against the i32 the C ABI carries.

Function broadcast_except

pub fn broadcast_except(sender: Connection, message: bytes) -> Result<i64, NetError>

Broadcast a message to all connections except the sender.

Used in chat-server patterns to fan out messages. Delivery is best-effort: every eligible connection is attempted even after one fails. Ok(n) means n connections received the message and none failed (Ok(0) means there was nothing to deliver to); Err carries the NetError for the first failed write โ€” healthy connections were still delivered to.

Types

Enum NetError

Structured error type for network operations.

Returned by all try_* functions in net, net.tls, net.quic, net.http, net.websocket, and net.dns. Use Result<T, NetError> return types with the ? operator for structured error propagation.

For file-system errors see fs.IoError.

Variants

ConnectionRefused(i64)

The remote host actively refused the connection (ECONNREFUSED).

AddressInUse(i64)

The local address is already in use (EADDRINUSE).

AddressNotAvailable(i64)

The address or hostname could not be resolved (EADDRNOTAVAIL).

TimedOut(i64)

The connection attempt or I/O operation timed out (ETIMEDOUT).

Cancelled(i64)

Operation was cancelled (e.g., a deadline expired before the I/O could complete).

Distinct from TimedOut: TimedOut means the OS deadline expired; Cancelled means the operation was abandoned for another reason (e.g. the blocking pool was shut down mid-call).

InvalidArgument(string)

An argument was rejected before it reached the operating system.

Carries the rejection detail rather than an errno: no syscall was made, so there is no platform error code to report. Produced by the endpoint and duration validation below, which run before every native call whose C ABI narrows an i64 to an i32.

Other(i64)

Any other network-level failure.

Struct Endpoint

A validated host / port pair.

host never carries the IPv6 bracket form: [::1]:9000 yields host ::1, which is what the resolver expects.

Fields

host: string
port: i64

Struct Listener

A TCP listener bound to an address, waiting for connections.

Created by net.listen(addr). Returns a negative value (as i32) on failure when cast; use comparison to check success.

Struct Connection

An established TCP connection for reading and writing.

Obtained from listener.accept() or net.connect(addr).

Traits

Trait ListenerMethods

Methods available on a TCP Listener.

Methods

fn accept(self: Self) -> Connection

Wait until a client connects and return the new Connection.

fn local_port(self: Self) -> i64

Return the port selected for this listener, including an ephemeral port chosen by listen("...:0"). This is a borrowing inspection; it does not alter the listener's close authority.

Trait ConnectionMethods

Methods available on a TCP Connection: the pipe verbs on one bidirectional handle. split gives the two halves separate owners.

Methods

fn recv(self: Self) -> Option<bytes>

Receive the next chunk of bytes from the peer.

Waits until data is available. None is an orderly EOF: the peer finished writing. A transport failure traps the calling actor with the OS error, so the loop never sees an error value.

fn send(self: Self, data: bytes) -> Result<(), SendError>

Send raw bytes to the peer.

Returns Ok(()) once the payload is handed to the OS send buffer. Err(SendError.Closed) means the peer reset or closed the connection; Err(SendError.Full) means the send buffer stayed full past the write deadline set by set_write_timeout (without a deadline a full buffer waits until it drains). Any other failure traps the calling actor. The connection may have committed a prefix of the payload before Full, so a whole-payload retry is unsafe.

fn finish(self: Self)

Half-close: send FIN to the peer while this side keeps reading.

fn set_read_timeout(self: Self, ms: i64) -> Result<(), NetError>

Set the read timeout in milliseconds.

Pass a negative value to clear the timeout.

fn set_write_timeout(self: Self, ms: i64) -> Result<(), NetError>

Set the write timeout in milliseconds.

Pass a negative value to clear the timeout.