Skip to content
Tutorials Center
My learning

Topics

Lesson 90 of 132 ยท Standard Library Tour

Networking with std::net

Learn Rust networking with std::net: parse IP and socket addresses, build a TCP echo server and client on loopback with threads, send UDP datagrams and set timeouts.

Every network program, from a web server to a chat client, does the same few things: name a machine and a port, open a connection, and move bytes back and forth. Rust's standard library covers this with the std::net module: address types such as IpAddr and SocketAddr, TcpListener and TcpStream for reliable connections, and UdpSocket for individual datagrams. It is blocking and thread based, which makes it simple to reason about, and it is the foundation that async runtimes build on.

In this lesson you will parse and inspect addresses, write a small TCP echo server and client, speak a line-based protocol, handle several clients with threads, add timeouts so nothing waits forever, and send UDP datagrams. Everything runs on the loopback address 127.0.0.1, which only talks to the same machine. That is exactly what our editor allows, and it is also how real programs are tested.

Always bind to port 0 in examples you run here. Port 0 means "pick any free port for me"; you then ask the listener which one it got with local_addr(). Never print the port number itself, because it differs on every run.

Addresses: IpAddr, SocketAddr and parsing

An IP address identifies a machine; a socket address is an IP address plus a port number, which identifies one program on that machine. The standard library models them as plain values you can parse, compare and inspect:

  • Ipv4Addr and Ipv6Addr are the two address families.
  • IpAddr is an enum over both.
  • SocketAddrV4, SocketAddrV6 and SocketAddr pair an address with a port.

All of them implement FromStr, so "127.0.0.1:8080".parse::<SocketAddr>() works, and all return a Result because the text may be malformed.

Rust Parsing and inspecting addresses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice that "127.0.0.1" fails as a SocketAddr: it has no port. Parse it as an IpAddr instead, then combine it with a port using SocketAddr::new(ip, 80).

SocketAddr::from_str never does a DNS lookup. "example.com:80".parse::<SocketAddr>() fails. Name resolution belongs to the ToSocketAddrs trait, which TcpStream::connect("example.com:80") uses internally. Our sandbox has no network, so resolution is shown only in read-only snippets.

A TCP listener and your first connection

TCP gives you a reliable, ordered stream of bytes between two programs. One side listens, the other connects.

  • TcpListener::bind(addr) reserves a port and starts accepting connections.
  • listener.accept() blocks until a client connects, then returns a (TcpStream, SocketAddr).
  • TcpStream::connect(addr) is the client side.
  • A TcpStream implements Read and Write, so everything from Read, Write and BufRead applies.

Because accept blocks, the server needs its own thread when the client lives in the same program. This example sends one message and reads one reply:

Rust One server, one client

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Study the details, because they trip up almost everyone:

  1. bind succeeds before connect runs, so the connection is queued by the operating system even if accept has not been called yet. That is why there is no race here.
  2. The server's read returns however many bytes happen to be available. TCP has no message boundaries. "ping" is four bytes and arrived in one piece here, but a larger message could arrive in several chunks, and two small messages could arrive glued together.
  3. read_to_string on the client waits for end-of-stream. The stream ends when the server drops its TcpStream at the end of the thread closure, which closes the connection.

Framing: lines with BufReader

Since TCP is a stream, a protocol must say where one message ends. The simplest rule is "one message per line". BufReader::lines() does the splitting and buffering for you. Here is a tiny echo server that upper-cases each line and says goodbye when the client sends quit.

Rust A line-based echo server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Two habits worth copying:

  • Wrap the stream in BufReader when you read line by line. Without it, every small read is a system call.
  • Use try_clone (or &stream, since &TcpStream also implements Read and Write) so one handle reads while another writes. Writing a reply through the same BufReader is not possible because BufReader owns its inner reader.

Each line sent must end with a newline. If the client forgot writeln! and used write!, the server would wait forever for the rest of the line, which leads straight to the topic of timeouts.

Serving many clients with threads

A real server must keep accepting while earlier clients are still being served. The classic blocking design is one thread per connection: the main loop calls accept, then hands each stream to a new thread. It is easy to write and works well for hundreds of connections. For tens of thousands you would want the async approach.

The example below serves three clients concurrently. To keep the output deterministic, the clients collect their replies and the main thread prints them in order.

Rust Thread per connection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Points to remember:

  • listener.incoming() is an endless iterator of io::Result<TcpStream>. We use .take(3) so the demo ends; a real server loops forever.
  • shutdown(Shutdown::Write) closes only the sending half. The server's lines() loop sees end-of-input and finishes, while the client can still read the reply. Dropping the stream closes both halves.
  • Each failed accept or I/O call returns an Err. In a real server, log it and keep going rather than letting one bad client stop the loop.

Timeouts: never wait forever

By default every read, write, accept and connect can block indefinitely. A client that connects and then says nothing would hang a thread for good. Set timeouts on the stream:

  • set_read_timeout(Some(Duration)) and set_write_timeout(...) limit single operations.
  • TcpStream::connect_timeout(&addr, duration) limits connecting.
  • None removes the limit. A zero duration is an error.
  • When the limit expires you get an io::Error whose kind is WouldBlock on Unix-like systems and TimedOut on Windows, so check for both.
Rust A read that times out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Choose timeouts deliberately. Too short and slow but healthy peers fail; too long and one stuck peer ties up a thread. Also remember that a timeout applies to each call, not to the whole conversation. A peer that sends one byte every 90 ms would never trip a 100 ms read timeout. For a total deadline, track the elapsed time yourself.

There is also non-blocking mode (set_nonblocking(true)), where operations return WouldBlock immediately. You normally pair it with a readiness API such as epoll, which is exactly what async runtimes do. Plain std::net programs rarely need it.

UDP: datagrams instead of streams

UDP sends independent packets called datagrams. There is no connection, no guaranteed delivery and no ordering over a real network, but each datagram arrives whole or not at all, so message boundaries are free. It suits things like DNS lookups, game state and metrics, where a lost packet is cheaper than waiting.

  • UdpSocket::bind(addr) opens a socket.
  • send_to(bytes, addr) sends one datagram.
  • recv_from(&mut buf) receives one datagram and tells you who sent it. If the buffer is smaller than the datagram, the extra bytes are silently discarded.
Rust Two UDP sockets on loopback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

On loopback nothing is ever lost, so this always works. On a real network you would add your own timeouts (set_read_timeout works on UdpSocket too), sequence numbers and retries.

Read-only: talking to the real internet

Our sandbox has no outside network, so here are two snippets to try on your own machine. They are not runnable in the editor.

Rust
// Needs real network access: not runnable in our editor.
use std::io::{Read, Write};
use std::net::TcpStream;

fn main() -> std::io::Result<()> {
    // Name resolution happens inside connect (ToSocketAddrs).
    let mut stream = TcpStream::connect("example.com:80")?;
    stream.write_all(b"GET / HTTP/1.0\r\nHost: example.com\r\n\r\n")?;
    let mut response = String::new();
    stream.read_to_string(&mut response)?;
    println!("{}", response.lines().next().unwrap_or(""));
    Ok(())
}

And resolving a name without connecting:

Rust
// Needs a DNS resolver: not runnable in our editor.
use std::net::ToSocketAddrs;

fn main() -> std::io::Result<()> {
    for addr in "localhost:3000".to_socket_addrs()? {
        println!("{addr}");
    }
    Ok(())
}

This raw HTTP request is for learning only. TLS (https), redirects, chunked bodies and connection reuse are real work, so production code uses a client crate such as reqwest or ureq, and servers use axum, actix-web or hyper. The ecosystem lesson shows where those fit.

Pitfalls professionals avoid

  • Assuming one read equals one message. Loop until you have what the protocol promises, or use read_exact, read_line or a length prefix.
  • Forgetting that write may write less than you asked. Use write_all. writeln! and write! already do.
  • Unbounded input. read_line on a hostile peer can allocate gigabytes. Wrap the reader in .take(limit) to cap how much a client may send.
  • Blocking forever. Set timeouts on every stream you accept from outside.
  • Unwrapping inside servers. One bad client must not crash the process; propagate or log the error.
  • Binding to 0.0.0.0 by accident. 127.0.0.1 accepts only local connections. 0.0.0.0 accepts from every network interface, which is a security decision.
  • Thread per connection without a limit. An attacker opening 100,000 connections exhausts memory. Use a thread pool or an async runtime in production.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do the examples bind to port 0?

    Binding to port 0 asks the OS for any free port. This avoids clashes between runs, and local_addr() tells you which port you got.
  2. 2. A client calls write_all(b"hello") twice quickly. What may the server's single read() return?

    TCP is a byte stream with no message boundaries. A read returns whatever is available, so protocols need framing such as newlines or length prefixes.
  3. 3. What does "127.0.0.1".parse::<SocketAddr>() return?

    A SocketAddr is an IP address plus a port. Text without a port is not valid; parse it as IpAddr and combine it with a port.
  4. 4. What happens if the buffer passed to UdpSocket::recv_from is smaller than the datagram?

    A UDP datagram is delivered as a unit. If your buffer is too small, the part that does not fit is lost.
  5. 5. Which tool stops a read on a silent peer from blocking forever?

    set_read_timeout makes a read fail with WouldBlock or TimedOut after the given time, so your code can give up or retry.

Summary

  • std::net provides IpAddr, SocketAddr (parsable, inspectable values), TcpListener, TcpStream and UdpSocket.
  • Bind to 127.0.0.1:0 for tests and examples and read the real port from local_addr().
  • TcpStream implements Read and Write; TCP is a byte stream, so you must frame messages (newlines, length prefixes).
  • Use BufReader with lines() or read_line for text protocols, and try_clone to read and write at once.
  • A thread per connection is the simplest server design; limit it in production or move to async.
  • Set read, write and connect timeouts; treat both WouldBlock and TimedOut as "expired".
  • UDP sends whole datagrams without delivery guarantees; truncated receive buffers lose data.

Next: JSON, Serialization and Text Formats by Hand