Networking with the Standard Library
std.net
The std::net module provides synchronous, cross-platform networking primitives for TCP and UDP communication, IPv4 and IPv6 addressing, socket address parsing, and DNS hostname resolution.
+-------------------------------------------------------------------+
| std::net |
| |
| Addressing: |
| IpAddr = V4(Ipv4Addr) | V6(Ipv6Addr) |
| SocketAddr = V4(SocketAddrV4) | V6(SocketAddrV6) |
| ToSocketAddrs (Trait for converting/resolving endpoints) |
| |
| TCP (Stream-Oriented): UDP (Datagram-Oriented): |
| TcpListener --accept()--> UdpSocket |
| TcpStream (Read + Write) (send / recv / send_to) |
| Incoming (Iterator) |
| Shutdown (Read | Write | Both) |
+-------------------------------------------------------------------+
Core Types and Traits in std::net
| Item | Category | Description |
|---|---|---|
IpAddr |
Enum | Represents either an IpAddr::V4(Ipv4Addr) or IpAddr::V6(Ipv6Addr) host address. |
Ipv4Addr / Ipv6Addr |
Structs | 32-bit IPv4 and 128-bit IPv6 address structures with classification methods. |
SocketAddr |
Enum | Combines an IpAddr and a u16 port (SocketAddr::V4 or SocketAddr::V6). |
SocketAddrV4 / SocketAddrV6 |
Structs | Version-specific socket endpoints (SocketAddrV6 also carries flowinfo and scope_id). |
ToSocketAddrs |
Trait | Converts strings ("example.com:80"), tuples (("127.0.0.1", 8080)), or address structs into an iterator of resolved SocketAddrs. |
TcpListener |
Struct | Listening TCP socket that accepts incoming client connections. |
TcpStream |
Struct | Connected bidirectional TCP byte stream implementing std::io::Read and std::io::Write. |
UdpSocket |
Struct | Connectionless datagram socket supporting unicast, broadcast, and multicast packets. |
Shutdown |
Enum | Specifies which half of a TcpStream to close (Shutdown::Read, Shutdown::Write, or Shutdown::Both). |
AddrParseError |
Struct | Error returned when parsing a malformed IP or socket address string via FromStr. |
RAII Resource Management of Sockets
Just like std::fs::File, TcpListener, TcpStream, and UdpSocket own an underlying operating system socket descriptor (RawFd on Unix, RawSocket on Windows). When a socket value goes out of scope, its Drop implementation automatically closes the OS descriptor and releases the bound port or connection.
use std::io::{self, Read, Write};
use std::net::{Shutdown, TcpListener, TcpStream};
fn main() -> io::Result<()> {
let listener = TcpListener::bind(("127.0.0.1", 0))?;
let addr = listener.local_addr()?;
let mut client = TcpStream::connect(addr)?;
let (mut server_stream, peer_addr) = listener.accept()?;
assert_eq!(client.local_addr()?, peer_addr);
client.write_all(b"ping")?;
// Close the client's write half to signal EOF to the server
client.shutdown(Shutdown::Write)?;
let mut buf = String::new();
server_stream.read_to_string(&mut buf)?;
println!("Server received: {buf}");
Ok(())
} // `client`, `server_stream`, and `listener` close automatically here
Server received: ping