std::netTCP networking.
Create TCP servers and clients for bidirectional byte-stream
communication. Handle types (Listener, Connection) provide
type-safe wrappers over raw file descriptors.
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"),
}
}
}
}
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();
}
net_error_from_errnoMap 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.
abi_i32_maxLargest value the i32 parameters of the networking C ABI can carry.
duration_msValidate a millisecond duration that the C ABI carries as an i32.
context names the calling API so the rejection identifies its origin.
size_argValidate a byte count that the C ABI carries as an i32.
port_argValidate a TCP/UDP port number.
parse_endpointParse 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.
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),
}
}
net_error_timed_outConstruct a NetError.TimedOut(0) value without a platform-specific
errno. Useful for in-process deadline expiry where there is no OS error
to map.
net_error_cancelledConstruct a NetError.Cancelled(0) value without a platform-specific
errno. Useful for in-process cancellation where there is no OS error
to map.
listenCreate a TCP listener bound to the given address.
Returns Err(NetError) instead of panicking on bind failure.
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"),
}
}
connectConnect to a TCP server at the given address.
Returns Err(NetError) instead of panicking on failure.
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"),
}
}
connect_timeoutConnect 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.
broadcast_exceptBroadcast 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.
NetErrorStructured 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.
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.
EndpointA validated host / port pair.
host never carries the IPv6 bracket form: [::1]:9000 yields host
::1, which is what the resolver expects.
ListenerA 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.
ConnectionAn established TCP connection for reading and writing.
Obtained from listener.accept() or net.connect(addr).
ListenerMethodsMethods available on a TCP Listener.
Wait until a client connects and return the new Connection.
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.
ConnectionMethodsMethods available on a TCP Connection: the pipe verbs on one
bidirectional handle. split gives the two halves separate owners.
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.
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.
Half-close: send FIN to the peer while this side keeps reading.
Set the read timeout in milliseconds.
Pass a negative value to clear the timeout.
Set the write timeout in milliseconds.
Pass a negative value to clear the timeout.