Shelves / Foundations of Computing
CS·09
Networking Fundamentals
How bytes cross the world: layered models, Ethernet and IP, addressing and routing, NAT, ARP, ICMP, DHCP, TCP's reliability and congestion control, UDP, DNS and TLS, with sockets in each language.
Start here: how computers talk to each other
Networks are a postal system
When you open a web page, your computer and a computer in a data centre, perhaps thousands of kilometres away, exchange messages. Almost everything about networking makes sense if you picture the postal system:
| Postal system | Computer networking |
|---|---|
| A building's street address | an IP address: which computer |
| The flat number inside the building | a port: which program on that computer |
| A long letter sent as several numbered postcards | data split into packets |
| Post offices passing mail along, hop by hop | routers forwarding packets |
| Envelope inside envelope (company mailroom, then post) | layers, each adding its own header |
| Looking up an address in a directory | DNS: name to IP address |
| A registered letter, with signed receipts | TCP: reliable, ordered delivery |
| A postcard: cheap, no guarantee | UDP: fast, no guarantees |
IP addresses and ports
Every device on a network has an IP address. IPv4 addresses are 32 bits, written as four bytes in decimal: 142.250.183.4. There are only about 4.3 billion of them, not enough for every device, so IPv6 uses 128 bits, written in hex: 2404:6800:4007:81a::2004. Some addresses are special: 127.0.0.1 (localhost) always means "this machine"; 10.x.x.x and 192.168.x.x are private addresses used inside homes and offices, where one router shares a single public address among many devices.
One computer runs many networked programs at once, so an address alone isn't enough. A port (a 16-bit number, 0–65535) picks the program. Well-known services use standard ports: 80 for HTTP, 443 for HTTPS, 22 for SSH, 5432 for PostgreSQL. A connection is identified by four things: source IP and port, destination IP and port.
Packets: why data travels in pieces
Networks don't send your data as one long stream down a dedicated wire. They split it into packets, typically up to about 1,500 bytes each, and each packet travels independently: different packets may take different routes, arrive out of order, arrive twice, or get lost when a router is overloaded. This design (packet switching) means no single broken link stops everything, and many conversations share the same cables fairly. A small simulation shows what the receiving side has to cope with:
message = "Namaste! The order for table 7 is two masala dosas and one filter coffee."
MTU = 16 # pretend each packet carries at most 16 bytes
packets = [(seq, message[i:i + MTU]) for seq, i in enumerate(range(0, len(message), MTU))]
arrived = packets[:]; random.shuffle(arrived) # the network may deliver them out of order…
lost = arrived.pop(2) # …and may lose one
missing = [s for s in range(len(packets)) if s not in {s for s, _ in arrived}]
arrived.append(packets[missing[0]]) # the sender retransmits the gap
print("".join(chunk for _, chunk in sorted(arrived)))
73 bytes split into 5 packets
arrived (seq numbers): [3, 4, 2, 1] | lost: 0
receiver asks again for: [0]
reassembled: Namaste! The order for table 7 is two masala dosas and one filter coffee.
Numbering the pieces, noticing gaps, asking for them again and putting everything back in order is exactly what TCP does for you, invisibly.
Layers: envelopes inside envelopes
Networking is split into layers, each solving one problem and relying on the one below. The usual practical model has four:
- Application layer: what the programs are actually saying (HTTP for the web, DNS for names, SMTP for mail).
- Transport layer: delivery between programs (ports), reliably (TCP) or not (UDP).
- Internet layer: delivery between computers anywhere (IP addresses, routing across networks).
- Link layer: delivery across one physical hop (Ethernet cable, Wi-Fi), using hardware MAC addresses.
The sender wraps the data in each layer's header on the way down; each router looks only at the IP header to choose the next hop; the receiver unwraps on the way up. You'll also hear of the 7-layer OSI model; it splits the same jobs more finely, and people still say "layer 4" (transport) and "layer 7" (application) from it.
DNS: the internet's phone book
People remember names like www.example.com; packets need IP addresses. The Domain Name System translates. Your computer asks a resolver (usually run by your ISP or a service like 1.1.1.1), which asks the servers responsible for .com, then for example.com, and caches answers for the time each answer says (its TTL). Before asking the network at all, your machine checks its own /etc/hosts file:
$ head -1 /etc/hosts
127.0.0.1 localhost
$ python3 -c "import socket; print(socket.gethostbyname('localhost'))"
127.0.0.1
When "the website is down" but its IP address works, DNS is the usual suspect.
TCP and UDP
| TCP | UDP | |
|---|---|---|
| Connection | set up first (the three-way handshake: SYN, SYN-ACK, ACK) | none: just send |
| Delivery | every byte arrives, in order, or you get an error | packets may be lost, duplicated or reordered |
| Speed control | slows down when the network is congested | none built in |
| Shape | a continuous stream of bytes | separate messages (datagrams) |
| Used by | web (HTTP/1.1, HTTP/2), email, SSH, databases | DNS, video calls, games, and QUIC (which HTTP/3 builds on, adding its own reliability) |
TCP gives a byte stream, not messages: if you send "Hello" then "World", the receiver might read "HelloWor" then "ld". Applications must mark where their messages end (HTTP uses headers like Content-Length). That's a classic beginner bug, and the full-depth sections show how each language handles it.
What happens when you type a URL
A URL packs the whole request into one line. Python's urllib splits one apart:
https://www.example.com:443/search?q=chai#top
scheme=https host=www.example.com port=443 path=/search query=q=chai fragment=top
Then, in order:
- DNS: look up
www.example.comto get an IP address. - TCP: connect to that IP on port 443 (the handshake).
- TLS: because the scheme is
https, agree on encryption keys and check the server's certificate (below). - HTTP: send the request:
GET /search?q=chai. (The#topfragment never leaves your browser; it just scrolls the page.) - The server sends a response: a status code, headers and the page.
- The browser reads the HTML, finds images, styles and scripts, and requests each of those too.
Speaking HTTP by hand
HTTP is plain text, so you can type it. Below, a tiny Python web server runs on port 8080 and nc (netcat) opens a TCP connection and sends a request exactly as a browser would (the \r\n pairs are the line endings HTTP requires; the blank line ends the request):
class H(BaseHTTPRequestHandler):
def do_GET(self):
body = f"Hello! You asked for {self.path}\n".encode()
self.send_response(200); self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
HTTPServer(("127.0.0.1", 8080), H).serve_forever()
$ printf 'GET /menu HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n' | nc 127.0.0.1 8080
HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.13.17
Date: Thu, 29 Oct 2026 07:42:33 GMT
Content-Type: text/plain
Content-Length: 27
Hello! You asked for /menu
The response's first line is the status: 200 OK. The ones to know: 200 OK, 301/302 moved (go here instead), 304 not modified (use your cached copy), 400 bad request, 401 not logged in, 403 forbidden, 404 not found, 429 too many requests, 500 server error, 503 unavailable. Roughly: 2xx success, 3xx go elsewhere, 4xx your mistake, 5xx the server's. curl -v shows the same exchange with > for what was sent and < for what came back; it's the most useful network debugging command you'll learn.
HTTPS and the padlock
Plain HTTP travels as readable text through every router and Wi-Fi network on the way, so anyone in between could read or change it. HTTPS is HTTP inside TLS, which provides:
- Encryption: eavesdroppers see only scrambled bytes.
- Integrity: any tampering is detected.
- Authentication: the server proves it really is
www.example.comwith a certificate signed by a certificate authority your system already trusts. The padlock means this check passed; it says nothing about whether the site itself is honest.
Check yourself
How deep to go in networking
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere and L4 in the labs at the end, which is the foundation every later volume builds on.
| Level | What you can do |
|---|---|
| L1 | Name the layers and protocols |
| L2 | Write socket clients and servers; configure DNS records and TLS |
| L3 | Explain addressing and routing, TCP's reliability and congestion control, DNS resolution, the TLS handshake |
| L4 | Diagnose with tcpdump, ss, dig, curl timings: retransmissions, DNS failures, handshake problems |
| L5 | Choose protocols, timeouts, connection management and addressing schemes for a system |
| L6 | Operate networks of services: certificates, DNS changes, MTU and NAT issues, cross-region latency |
Layers and models
Why layers
Sending a message from your laptop to a server on another continent involves radio or copper signals, local delivery, global routing, reliability, encryption and an application protocol. Networking splits those concerns into layers. Each layer provides a service to the one above it and uses the one below, and each talks to its peer layer on the other host through a protocol.
As data goes down the stack, each layer wraps it with its own header (encapsulation). On the receiver, each layer strips its header and passes the payload up:
The OSI model
The OSI reference model (ISO, 1984) has seven layers. The Internet never implemented OSI's own protocols, but its vocabulary is used everywhere ("an L4 load balancer," "an L7 firewall"):
| # | Layer | Responsibility | Unit | Examples |
|---|---|---|---|---|
| 7 | Application | Meaning of the conversation | message | HTTP, DNS, SMTP, gRPC, SSH |
| 6 | Presentation | Encoding, encryption, compression | TLS (arguably), JSON, Protobuf, gzip | |
| 5 | Session | Dialogues, checkpoints | (folded into apps; TLS sessions, RPC sessions) | |
| 4 | Transport | Process-to-process delivery, reliability, flow control | segment / datagram | TCP, UDP, QUIC |
| 3 | Network | Host-to-host delivery across networks: addressing, routing | packet | IPv4, IPv6, ICMP |
| 2 | Data link | Delivery within one local network, framing, MAC addresses | frame | Ethernet, Wi-Fi (802.11), ARP |
| 1 | Physical | Bits as signals | bit | Copper, fibre, radio |
The TCP/IP model
The TCP/IP model is what the Internet actually runs. It has four layers: link (OSI 1–2), internet (3), transport (4), and application (5–7). Its design philosophy is the end-to-end principle: keep the network core simple (routers just forward packets, best-effort) and put intelligence such as reliability, ordering and security in the end hosts. That's why IP itself is unreliable, why TCP does all the hard work at the edges, and why the Internet could grow from a few hosts to billions without redesigning the core.
What each kind of device looks at:
| Device | Layer | Decides using |
|---|---|---|
| Hub (obsolete) | 1 | Nothing: repeats bits to all ports |
| Switch | 2 | Destination MAC address |
| Router | 3 | Destination IP address + routing table |
| L4 load balancer (AWS NLB, LVS) | 4 | IP + port (doesn't parse HTTP) |
| L7 load balancer / reverse proxy (Nginx, Envoy, AWS ALB) | 7 | HTTP host, path, headers, cookies |
Link layer and IP
Ethernet
Ethernet (IEEE 802.3) is the dominant wired LAN technology, from 1 Gb/s on desktops to 100–800 Gb/s in data centres. An Ethernet frame carries:
| dst MAC (6) | src MAC (6) | EtherType (2) | payload (46–1500) | FCS / CRC-32 (4) |
0x0800 = IPv4, 0x86DD = IPv6, 0x0806 = ARP, 0x8100 = VLAN tag
- The MTU (maximum transmission unit) is the largest payload, 1500 bytes by default. Data centres often use jumbo frames (9000) to reduce per-packet overhead. A mismatch, or tunnels that add headers (VPNs, VXLAN overlays in Kubernetes), causes the classic "small requests work, large ones hang" bug, which is an MTU or path MTU discovery problem (see ICMP).
- Switches learn which MAC address lives behind which port by watching source addresses, and forward frames only to the right port. Unknown destinations and broadcasts (
ff:ff:ff:ff:ff:ff) are flooded to all ports in the broadcast domain. - VLANs (802.1Q tags) split one physical switch into separate logical LANs.
- Wi-Fi (802.11) uses a different physical layer and medium access (CSMA/CA), but presents the same Ethernet-like frames to IP.
MAC addresses
A MAC address is a 48-bit link-layer address, written 3c:22:fb:9a:10:4e. The first 24 bits (the OUI) identify the manufacturer. MACs are meant to be globally unique, but they're only meaningful on the local network. Routers rewrite the link-layer header at every hop, while the IP addresses stay end to end. Phones and laptops now randomise their MAC per Wi-Fi network for privacy. Containers and VMs get virtual MACs.
IP addresses: IPv4 and IPv6
The Internet Protocol delivers packets from a source host to a destination host across any number of networks, on a best-effort basis: packets can be lost, duplicated, reordered or corrupted, and IP doesn't fix any of it.
IPv4 addresses are 32 bits, written as four decimal octets: 192.168.1.20. That's about 4.3 billion addresses, which ran out at the registries during the 2010s. Key header fields: version, header length, TTL (decremented at each router hop and dropped at 0, which prevents routing loops), protocol (6 = TCP, 17 = UDP, 1 = ICMP), source and destination addresses, a header checksum, and fragmentation fields.
IPv6 addresses are 128 bits, written as eight 16-bit hex groups with leading zeros dropped and one run of zero groups shortened to ::. For example, 2001:db8:0:0:0:0:0:1 becomes 2001:db8::1. There's no realistic shortage: about 3.4 × 10³⁸ addresses. It has a simpler fixed header with hop limit instead of TTL, no fragmentation by routers, stateless address autoconfiguration (SLAAC), and no NAT needed. Major networks (mobile carriers, Google, Facebook, Jio in India) route a large share of their traffic over IPv6. Many services run dual-stack. Happy Eyeballs (RFC 8305) races IPv6 and IPv4 connections so a broken IPv6 path doesn't hurt users.
Special ranges every engineer should recognise:
| Range | Meaning |
|---|---|
127.0.0.0/8, ::1 |
Loopback (this host) |
10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 |
Private IPv4 (RFC 1918): not routed on the Internet |
100.64.0.0/10 |
Carrier-grade NAT shared space |
169.254.0.0/16, fe80::/10 |
Link-local. 169.254.169.254 is the cloud metadata service (a prime SSRF target, Part X) |
0.0.0.0, :: |
"Any address" when binding a server socket; "unspecified" otherwise |
224.0.0.0/4, ff00::/8 |
Multicast |
fc00::/7 |
IPv6 unique local (private) |
A server bound to 127.0.0.1 accepts only local connections. Bound to 0.0.0.0 it accepts connections on every interface. Inside a container, an app bound to 127.0.0.1 is unreachable from outside the container, even with ports published, which is a common "it works locally" bug.
Subnetting and CIDR
An IP address has two parts: a network prefix and a host part. CIDR notation writes the prefix length after a slash: 192.168.1.0/24 means the first 24 bits are the network and the remaining 8 identify hosts.
address 192.168.1.130 = 11000000.10101000.00000001.10000010
mask /24 255.255.255.0 = 11111111.11111111.11111111.00000000
network = address AND mask = 192.168.1.0
hosts = 2^(32−24) = 256 addresses: .0 is the network, .255 is broadcast, .1–.254 usable (254)
Being able to calculate quickly helps when you design VPCs and Kubernetes pod ranges:
| Prefix | Addresses | Typical use |
|---|---|---|
| /32 | 1 | One host (security group rules, routes) |
| /30 | 4 (2 usable) | Point-to-point link |
| /28 | 16 | Smallest AWS subnet (AWS reserves 5 addresses per subnet) |
| /24 | 256 | A classic LAN, a typical cloud subnet |
| /20 | 4,096 | A larger subnet; default VPC subnets in AWS |
| /16 | 65,536 | A whole VPC |
| /8 | 16.7 M | 10.0.0.0/8 |
| IPv6 /64 | 2⁶⁴ | Standard size of one IPv6 subnet |
Two hosts are on the same subnet if (a & mask) == (b & mask). The host then sends directly, using ARP to find the MAC. Otherwise it sends to its default gateway (router). Plan address space carefully in the cloud. Overlapping CIDRs between VPCs, or between a VPC and the office network, block peering and VPN connectivity later, and Kubernetes clusters can exhaust pod IP ranges (Part VIII).
_, subnet, _ := net.ParseCIDR("10.20.0.0/20")
ip := net.ParseIP("10.20.13.7")
fmt.Println(subnet.Contains(ip)) // true
ones, bits := subnet.Mask.Size()
fmt.Println(1 << (bits - ones)) // 4096 addresses
// netip (Go 1.18+) is the newer, allocation-free API: netip.MustParsePrefix("10.20.0.0/20")
Routing
Each router (and each host) has a routing table: entries of the form "destination prefix → next hop, out of interface." To forward a packet, the router picks the entry with the longest matching prefix, the most specific route. That's a radix-tree lookup (chapter 3), implemented in hardware on fast routers. The default route 0.0.0.0/0 matches everything.
$ ip route
default via 192.168.1.1 dev wlan0 ← everything else goes to the home router
10.0.0.0/8 via 10.8.0.1 dev tun0 ← VPN routes win for 10.x (longer prefix)
192.168.1.0/24 dev wlan0 scope link ← local subnet: deliver directly
$ traceroute example.com ← shows each router hop (uses TTL expiry + ICMP)
How routes get there:
- Static routes: configured by hand or by cloud route tables.
- Interior gateway protocols, within one organisation: OSPF and IS-IS are link-state protocols, where every router learns the full map and runs Dijkstra (chapter 4). Older RIP is distance-vector, a distributed Bellman–Ford.
- BGP (Border Gateway Protocol), between organisations: the Internet's routing glue. About 75,000+ autonomous systems (ISPs, clouds, large companies) announce which prefixes they can reach. BGP is policy-driven and trust-based, so mistakes and attacks propagate globally. Famous incidents include Pakistan Telecom accidentally hijacking YouTube in 2008, and Facebook withdrawing its own routes in October 2021, which took its DNS and everything else offline for about six hours. RPKI route origin validation is the slowly spreading defence.
- Anycast: the same IP prefix is announced from many locations, and BGP delivers each user to the nearest. Public DNS resolvers (1.1.1.1, 8.8.8.8), CDNs and DDoS-mitigation networks rely on it.
NAT
Network address translation lets many devices with private addresses share one public address. A NAT router rewrites the source IP and port of outgoing packets, remembers the mapping in a table, and rewrites replies back:
inside 192.168.1.20:51515 → 93.184.216.34:443
NAT rewrites to 203.0.113.7:40001 → 93.184.216.34:443 table: 40001 ↔ 192.168.1.20:51515
reply 93.184.216.34:443 → 203.0.113.7:40001 → rewritten to 192.168.1.20:51515
NAT is what stretched IPv4 through the address shortage. Home routers, mobile carriers (CGNAT, where thousands of customers share one IP) and cloud NAT gateways (private subnets reaching the Internet) all do it. It has side effects you'll meet:
- Inbound connections don't work by default, since there's no mapping until the inside host speaks first. Peer-to-peer apps and video calls use STUN/TURN/ICE and hole punching (WebRTC).
- Mappings time out: idle TCP connections through NAT or stateful firewalls get silently dropped after minutes, especially on AWS NAT gateways (350 s idle timeout) and mobile networks. Long-lived connections need keepalives (TCP keepalive, HTTP/2 PING, WebSocket ping, database pool validation).
- Port exhaustion: one public IP has about 64 K ports per destination IP and port. A busy service making many outbound connections through one NAT gateway can run out. Connection pooling and reuse avoid it.
- In Kubernetes, kube-proxy/iptables/IPVS and service meshes perform NAT to turn virtual Service IPs into pod IPs (Part VI).
ARP and IPv6 neighbour discovery
IP knows the next-hop IP address, but Ethernet needs a MAC address. ARP (address resolution protocol) asks the local network:
broadcast: "Who has 192.168.1.1? Tell 192.168.1.20 (3c:22:fb:9a:10:4e)"
unicast reply: "192.168.1.1 is at a4:91:b1:00:12:34"
Results are cached in the ARP table (ip neigh). ARP has no authentication, so any host can claim any IP. ARP spoofing lets an attacker on the LAN put themselves in the middle of other hosts' traffic. That's one reason encryption (TLS) must not depend on the local network being trustworthy. IPv6 replaces ARP with Neighbor Discovery (NDP), which uses ICMPv6 messages.
ICMP
ICMP (Internet Control Message Protocol) carries control and error messages for IP itself. It runs on top of IP but is part of the network layer. Important messages:
- Echo request/reply:
ping. It measures reachability and round-trip time. Many firewalls block it, so a failed ping doesn't prove a host is down. - Time exceeded: sent when TTL reaches 0.
traceroutesends packets with TTL 1, 2, 3… and collects these messages from each hop. - Destination unreachable: no route, port unreachable (UDP), administratively prohibited. Includes "fragmentation needed" (IPv4) and "packet too big" (ICMPv6), which path MTU discovery depends on.
DHCP
DHCP (Dynamic Host Configuration Protocol) gives a joining device its IP configuration automatically, in four messages known as DORA:
- Discover: the client broadcasts "I need an address" (from 0.0.0.0, over UDP port 67/68).
- Offer: a DHCP server offers an address.
- Request: the client requests the offered address.
- Acknowledge: the server confirms, along with the lease time, subnet mask, default gateway, and DNS servers.
Leases expire, and clients renew at about half the lease time. Cloud VPCs run DHCP for every instance (which is how EC2 learns its private IP and the VPC DNS resolver). IPv6 can use SLAAC instead, or DHCPv6. A rogue DHCP server on a LAN can hand out a malicious gateway or DNS server, so switches offer DHCP snooping to block that.
Transport: TCP and UDP
Ports and sockets
IP delivers packets to a host. The transport layer delivers data to a specific process on that host, using 16-bit port numbers. A connection is identified by the 5-tuple (protocol, source IP, source port, destination IP, destination port). That's why one server port (443) can hold millions of connections: each has a different client address and port.
- Well-known ports (0–1023, binding them traditionally needs root or
CAP_NET_BIND_SERVICE): 22 SSH, 25 SMTP, 53 DNS, 80 HTTP, 443 HTTPS. - Registered ports: 3306 MySQL, 5432 PostgreSQL, 6379 Redis, 9092 Kafka, 27017 MongoDB, 8080 alternate HTTP.
- Ephemeral ports (Linux default range 32768–60999): picked automatically for the client side of outgoing connections. A client making many short-lived connections to one destination can exhaust them. TIME_WAIT (below) makes that worse.
A socket is the OS's handle for one endpoint of communication: the file descriptor your program uses. The BSD sockets API (1983) is used, directly or wrapped, by every language.
UDP
UDP (User Datagram Protocol) adds almost nothing to IP: ports, a length, and a checksum, in an 8-byte header. Each send is one self-contained datagram. UDP gives you:
- No connection setup: send immediately, with no handshake latency.
- No reliability: datagrams may be lost, duplicated or reordered, and UDP won't notice.
- No congestion control: UDP will happily flood a network. Applications must behave themselves.
- Message boundaries are preserved: one send corresponds to one receive (unlike TCP).
- Multicast and broadcast support.
Use UDP when latency matters more than perfect delivery, or when you'll build your own reliability: DNS queries (one small request and response, with a retry on timeout), real-time voice and video (a late packet is useless, so skip it), online games (send the latest state, not retransmit old state), metrics (StatsD), discovery protocols, and, most importantly, as the substrate for QUIC / HTTP/3, which implements its own reliability and congestion control in user space over UDP (chapter 19).
TCP: the reliable byte stream
TCP (Transmission Control Protocol) turns IP's lossy packet delivery into a reliable, ordered, bidirectional byte stream between two processes, with flow control and congestion control. You write bytes in at one end, and the same bytes come out at the other end in order, or the connection reports an error. It's one of the most important pieces of software ever designed, and its behaviour explains many production latency problems.
The TCP header (20 bytes without options):
| src port (16) | dst port (16) |
| sequence number (32) |
| acknowledgement number (32) |
| hdr len | flags: CWR ECE URG ACK PSH RST SYN FIN | window size (16) |
| checksum (16) | urgent pointer (16) |
| options: MSS, window scale, SACK permitted, timestamps … |
TCP is a byte stream, not a message stream. Two send("hello") calls may arrive as one recv returning "hellohello", or as "hel" then "lohello". Every protocol over TCP must therefore define framing: a length prefix (TLS records, gRPC/HTTP/2 frames, Kafka, PostgreSQL's wire protocol), a delimiter (\r\n in HTTP/1.1 headers, Redis RESP lines), or a fixed size. Assuming one read equals one message is a classic beginner bug that works on localhost and fails in production.
Connection establishment: the three-way handshake
Before any data flows, both sides agree on initial sequence numbers (ISNs):
- SYN: the client picks a random ISN x and sends SYN.
- SYN-ACK: the server picks its ISN y, acknowledges x + 1, and allocates state.
- ACK: the client acknowledges y + 1. Both sides are now ESTABLISHED.
Why three messages? Each side must announce its own sequence number and confirm it received the other's. ISNs are random so an attacker can't inject forged segments, and so old duplicate segments from a previous connection on the same ports aren't mistaken for new data.
Consequences for latency and operations:
- A new connection costs one round-trip time (RTT) before data can flow, plus 1–2 more RTTs for TLS (below). Across continents (RTT ~150–250 ms), that's half a second before the first byte of the request. That's why connection reuse (HTTP keep-alive, connection pools for databases and HTTP clients) is one of the most important performance practices. TCP Fast Open and TLS 1.3 0-RTT shave round trips, and QUIC folds the transport and TLS handshakes together.
- SYN floods: an attacker sends many SYNs and never ACKs, filling the server's half-open connection queue. SYN cookies encode the connection state in the server's ISN, so no state is stored until the final ACK arrives.
- Backlog: completed connections wait in the accept queue (
listen(fd, backlog), capped bynet.core.somaxconn). If the application doesn't callacceptfast enough, the queue overflows and clients see connection timeouts.
Sequence numbers and acknowledgements
TCP numbers every byte, not every segment. The sequence number of a segment is the number of its first data byte. The receiver sends cumulative ACKs: "ack = N" means "I have every byte before N, send N next." With sequence numbers, the receiver can:
- Reorder segments that arrive out of order, buffering them until the gap is filled.
- Discard duplicates.
- Tell the sender exactly what's missing.
Refinements:
- Delayed ACKs: the receiver waits up to ~40 ms (Linux) or 200 ms (some stacks) to piggyback an ACK on response data or acknowledge two segments at once.
- SACK (selective acknowledgement, an option): "I have 1000–1999 and 3000–3999." The sender then retransmits only the hole, which matters a lot on lossy, high-bandwidth paths.
- Nagle's algorithm: the sender holds back small writes while there's unacknowledged data in flight, combining them into fuller segments. Nagle's algorithm plus delayed ACKs together produce the infamous 40 ms latency stall in request–response protocols that write a small header and then a small body. That's why latency-sensitive applications set
TCP_NODELAY. Most HTTP clients, database drivers, gRPC and Redis clients do this by default.
Retransmission
TCP detects loss in two ways:
- Retransmission timeout (RTO): if an ACK doesn't arrive in time, resend. The RTO is calculated from a smoothed RTT plus four times the RTT variance (RFC 6298), with a minimum of 200 ms on Linux. After each timeout, the RTO doubles (exponential backoff), up to about 2 minutes. Linux gives up after
tcp_retries2(15 retries, roughly 15 minutes). - Fast retransmit: if the sender receives three duplicate ACKs (the receiver keeps acknowledging the same byte because later segments arrived but one is missing), it retransmits the missing segment immediately without waiting for the timeout. Modern Linux also uses RACK (time-based loss detection).
Tail latency comes from here. Losing one packet early in a connection, or the last packet of a response (with no later packets to generate duplicate ACKs), costs a full RTO of 200 ms or more. On a service with thousands of requests per second and a little packet loss, that shows up as p99 latency spikes of exactly 200 ms or 1 s, a recognisable fingerprint in latency histograms. Losing a SYN costs the initial SYN timeout: 1 second on Linux, then 3, 7, and so on. Some client libraries' default connect timeouts are tuned with that in mind.
Flow control
Flow control stops a fast sender from overwhelming a slow receiver. Every ACK carries a receive window (rwnd): how many more bytes the receiver's buffer can accept. The sender may have at most rwnd unacknowledged bytes in flight. If the application stops reading, the buffer fills, rwnd drops to zero, and the sender stops. It sends periodic window probes until the receiver opens the window again.
The original 16-bit window field caps rwnd at 64 KB, which is far too small for fast, long paths. The window scale option (negotiated in the SYN) multiplies it by up to 2¹⁴, allowing windows up to 1 GB. The window needed to fill a path is the bandwidth-delay product (BDP):
BDP = bandwidth × RTT
1 Gb/s × 100 ms = 125 MB/s × 0.1 s = 12.5 MB must be "in flight" to use the full link.
With a 64 KB window: max throughput = 64 KB / 0.1 s = 640 KB/s ≈ 5 Mb/s, on a 1 Gb/s link.
Linux auto-tunes socket buffers (net.ipv4.tcp_rmem/tcp_wmem). If cross-region transfers are mysteriously slow, check that window scaling isn't stripped by a middlebox and that buffer maximums are large enough.
Flow control is also how backpressure propagates through TCP. A slow consumer fills its buffer, which closes the window, which fills the sender's socket buffer, which blocks the sender's write (or makes it return EAGAIN). Reactive frameworks and gRPC flow control build on the same idea at higher layers.
Congestion control
Flow control protects the receiver. Congestion control protects the network. Without it, senders would overflow router queues, packets would drop, everyone would retransmit, and throughput would collapse. That actually happened in 1986, when throughput on part of the early Internet fell from 32 kb/s to 40 b/s. Van Jacobson's fix (1988) gave each sender a congestion window (cwnd) in addition to rwnd:
bytes allowed in flight = min(cwnd, rwnd)
The classic algorithm (Reno/NewReno) has these phases:
- Slow start: begin with a small cwnd (initial window = 10 segments ≈ 14 KB today, RFC 6928) and double it every RTT (+1 segment per ACK), until reaching the slow-start threshold or seeing loss.
- Congestion avoidance: grow linearly, +1 segment per RTT.
- On loss (three duplicate ACKs): halve cwnd. This is AIMD, additive increase, multiplicative decrease. AIMD provably converges toward a fair share between competing flows.
- On timeout: reset cwnd to 1 segment and slow-start again.
Modern algorithms:
- CUBIC (the Linux default since 2006; also Windows and macOS): cwnd grows as a cubic function of the time since the last loss. It recovers quickly on high-BDP paths and probes cautiously near the previous maximum.
- BBR (Google, 2016; BBRv3 more recently): instead of treating loss as the congestion signal, BBR models the path's bottleneck bandwidth and minimum RTT and paces packets at that rate. It keeps queues short (low latency) and handles lossy links (Wi-Fi, long-haul) much better. Google uses it for YouTube and Google Cloud. Enable it with
sysctl net.ipv4.tcp_congestion_control=bbr. - ECN (explicit congestion notification): routers mark packets instead of dropping them, and the receiver echoes the mark. Congestion is signalled without loss. Data centre variants such as DCTCP use it.
Bufferbloat: oversized router and modem buffers let loss-based algorithms fill queues completely before any drop happens, adding hundreds of milliseconds of latency (a video call degrades while someone uploads). Active queue management (CoDel, fq_codel, which is now the Linux default qdisc) and BBR address it.
Why this matters for application engineers: a new connection starts slow. Its first RTT can carry only about 14 KB. A 1 MB response on a fresh connection takes several RTTs just to ramp up, but on a warm, reused connection it may take one. Another reason to reuse connections, keep critical resources small, and use CDNs (shorter RTT means faster ramp-up).
Connection teardown and TIME_WAIT
TCP connections are full-duplex, so each direction closes separately:
- One side calls
close()and sends FIN: "I'm done sending." - The other side ACKs it. It may keep sending data. This is the half-closed state, and
shutdown(SHUT_WR)does this deliberately. - When it's done, it sends its own FIN, which is ACKed.
The side that closes first enters TIME_WAIT for 2 × MSL (maximum segment lifetime: 60 seconds total on Linux). Two reasons: if the final ACK is lost, the peer will retransmit its FIN and must get an ACK back, not a reset; and delayed duplicate segments from this connection must die off before the same 5-tuple can be reused.
Operational consequences:
- A server that actively closes many short connections, or a client opening and closing many connections to the same destination, accumulates thousands of TIME_WAIT sockets, each holding a 5-tuple. On the client side this can exhaust ephemeral ports. Fixes: reuse connections (keep-alive, pools);
net.ipv4.tcp_tw_reuse=1for outgoing connections. Never use the removed, brokentcp_tw_recycle. - CLOSE_WAIT piling up means the peer closed but your application never called
close(). That's a resource leak in your code (an unclosed HTTP response body, a leaked JDBC connection), not a network problem.ss -tanp state close-waitfinds the culprit. - RST (reset) aborts a connection immediately. It's sent when data arrives for a socket that doesn't exist, or when a process exits with unread data, or by firewalls, load balancers and NATs that have forgotten the flow. Clients see "connection reset by peer." Idle timeouts on load balancers that don't match the client's pool idle timeout cause bursts of these. Set client idle timeouts shorter than the server's or load balancer's.
$ ss -tan state time-wait | wc -l # count TIME_WAIT sockets
$ ss -tanp state close-wait # who isn't closing their sockets?
$ ss -ti dst 10.0.0.5 # per-connection TCP internals: rtt, cwnd, retrans, rto
DNS
What DNS does and its hierarchy
The Domain Name System maps human-friendly names (api.example.com) to the data needed to reach them: IP addresses, mail servers, aliases, verification records. It's a globally distributed, hierarchical, cached database, and practically every network request starts with a DNS lookup.
Names form a tree read right to left: the root (.), then top-level domains (com, org, in, dev), then second-level domains (example), then subdomains (api). Each level can delegate a subtree (a zone) to different name servers. Nobody holds the whole database. Each zone is served by its own authoritative servers.
Recursive resolvers and authoritative servers
Two very different kinds of DNS server exist:
- An authoritative server holds the actual records for a zone and answers only for that zone: Route 53, Cloudflare DNS, or your registrar's name servers.
- A recursive resolver does the legwork for clients. It walks the hierarchy, caches results, and returns final answers: your ISP's resolver, 1.1.1.1, 8.8.8.8, the VPC resolver at the
.2address of the VPC CIDR, or a Kubernetes cluster's CoreDNS.
Resolving api.example.com from a cold cache:
- The app's stub resolver (in libc or the language runtime) sends a recursive query to the configured resolver (
/etc/resolv.conf). - The resolver asks a root server. There are 13 root server names (a–m), operated as hundreds of anycast instances. The root replies with a referral: "I don't know, but
.comis served by these servers." - The resolver asks a
.comTLD server, which refers it toexample.com's name servers. (These NS records plus glue A records live in the parent zone.) - The resolver asks the authoritative server, which returns the answer.
- The resolver caches every step and returns the answer to the client.
With warm caches, which is the normal case, step 1 is answered immediately from the resolver's cache.
Record types
| Type | Maps a name to | Example |
|---|---|---|
| A | An IPv4 address | api.example.com. 300 IN A 203.0.113.10 |
| AAAA | An IPv6 address | api.example.com. 300 IN AAAA 2001:db8::10 |
| CNAME | Another name (an alias) | www.example.com. CNAME example.com. (app.example.com. CNAME my-lb-123.elb.amazonaws.com.) |
| MX | Mail servers, with priority | example.com. MX 10 mx1.mailhost.com. |
| TXT | Arbitrary text | SPF (v=spf1 include:_spf.google.com ~all), DKIM keys, DMARC policy, domain verification for Google, ACME and Microsoft |
| NS | Authoritative name servers for a zone | example.com. NS ns1.dnsprovider.com. |
| SOA | Zone metadata: primary NS, serial, timers, negative-cache TTL | |
| SRV | Service location: host + port + priority/weight | _sip._tcp, Kubernetes headless services, some service discovery |
| CAA | Which certificate authorities may issue certificates for the domain | example.com. CAA 0 issue "letsencrypt.org" |
| PTR | Reverse lookup: IP → name | used for mail-server reputation and logs |
| HTTPS / SVCB | Connection hints: ALPN (h2/h3), IP hints, ECH keys | lets browsers try HTTP/3 directly |
CNAME rules: a name with a CNAME can't have any other records. So the zone apex (example.com itself, which must have SOA and NS records) can't be a CNAME. That's why DNS providers offer non-standard ALIAS/ANAME records or AWS Route 53 alias records, which resolve the target on the server side and return A/AAAA records, so you can point the apex at a load balancer or CDN.
TTL and caching
Every record has a TTL (time to live, in seconds): how long resolvers and clients may cache it. TTLs control the trade-off between resilience and load (long TTLs mean fewer queries and survival when the authoritative servers are down) and agility (short TTLs mean changes and failovers take effect quickly).
- Typical TTLs are 300 s (5 minutes) for service endpoints, 3600 s or more for stable records, and 30–60 s for failover-driven records.
- Lower the TTL days before a planned migration. The old TTL governs how long stale answers survive once you change the record. Then change the record, then raise the TTL again.
- Negative caching: an NXDOMAIN ("no such name") is also cached, for the SOA's negative TTL. Creating a record right after a lookup that failed can appear "not to work" for a while.
- Caches exist at many layers: the OS (systemd-resolved, nscd), browsers (Chrome's internal cache), language runtimes, and recursive resolvers. The JVM caches successful lookups for 30 s by default (
networkaddress.cache.ttl), and older setups with a security manager cached them forever. Long-running Java clients have historically kept talking to old IPs after a failover. Set the TTL explicitly. Connection pools also keep old connections open regardless of DNS changes, so set a maximum connection lifetime. - Kubernetes DNS:
ndots:5in pods'resolv.confmakes a lookup ofapi.example.com(which has two dots, fewer than 5) first tryapi.example.com.<namespace>.svc.cluster.localand the other search domains, multiplying DNS queries. Use fully qualified names with a trailing dot, or tunendots, for heavy external lookups.
DNS operations and security
- "It's always DNS": DNS failures look like everything else (timeouts, connection errors, "service down"). Diagnose with
dig:
$ dig api.example.com A +short # just the answer
$ dig api.example.com +trace # walk from the root yourself
$ dig @1.1.1.1 example.com MX # ask a specific resolver
$ dig example.com TXT +noall +answer # SPF/DKIM/verification records
- DNS is unauthenticated by default. A spoofed answer can redirect traffic. Cache poisoning (Dan Kaminsky's 2008 attack) was mitigated by randomising source ports and query IDs. DNSSEC adds signatures from the root down, so resolvers can verify answers. Adoption is partial.
- Privacy: classic DNS is plaintext UDP on port 53, visible to anyone on the path. DoT (DNS over TLS, port 853) and DoH (DNS over HTTPS) encrypt queries. Browsers support DoH.
- DNS-based load balancing and failover: multiple A records (clients pick one, roughly round-robin), weighted or latency-based or geo routing (Route 53, Cloudflare), and health-checked failover. It's coarse (TTL-bound, and clients cache), so it's mainly used for global traffic steering in front of real load balancers (Part VIII).
- Subdomain takeover: a CNAME pointing at a deleted cloud resource (an S3 bucket, a Heroku app) can be claimed by an attacker, who then serves content on your domain. Remove DNS records when you decommission resources.
TLS
What TLS provides
TLS (Transport Layer Security, the successor to SSL) sits between TCP and the application. It's what puts the S in HTTPS, and it secures SMTP, IMAP, database connections, gRPC and service-mesh traffic. It provides three guarantees:
- Confidentiality: eavesdroppers see only ciphertext.
- Integrity: any modification in transit is detected.
- Authentication: the client verifies it is really talking to
bank.example, not an impostor. With mutual TLS (mTLS), the server also verifies the client.
The current versions are TLS 1.3 (RFC 8446, 2018) and TLS 1.2. SSL 2/3 and TLS 1.0/1.1 are deprecated and insecure, and should be disabled everywhere.
Symmetric and asymmetric cryptography
TLS combines two kinds of cryptography, because each solves what the other can't:
| Symmetric | Asymmetric (public-key) | |
|---|---|---|
| Keys | One shared secret key | A key pair: a public key (share it freely) and a private key (never share it) |
| Speed | Very fast: GB/s with hardware AES | ~1000× slower |
| Problem it solves | Bulk encryption | Agreeing on secrets with a stranger; proving identity |
| Algorithms in TLS 1.3 | AES-GCM, ChaCha20-Poly1305 (both AEAD: encryption plus integrity in one) | ECDHE key exchange (X25519, P-256), signatures with RSA, ECDSA, Ed25519 |
How public keys work in practice:
- Key exchange (Diffie–Hellman): two parties each combine their own private key with the other's public key and arrive at the same shared secret, which never travelled over the wire. An eavesdropper who sees both public keys can't compute it (that's the computational Diffie–Hellman assumption). Modern TLS uses the elliptic-curve version (ECDHE).
- Signatures: the holder of a private key produces a signature over data, and anyone with the public key can verify that only that key's holder could have produced it, and that the data wasn't changed.
The secret from key exchange is fed through a key-derivation function (HKDF) to produce the symmetric keys, and all application data is then encrypted with fast AEAD ciphers. Asymmetric crypto sets up the session, and symmetric crypto carries the traffic.
Post-quantum: a large enough quantum computer would break RSA and elliptic-curve cryptography. "Harvest now, decrypt later" attacks mean traffic recorded today could be decrypted in future. Browsers and major servers (Chrome, Firefox, Cloudflare, Google, AWS) have deployed hybrid key exchange that combines X25519 with ML-KEM (Kyber, standardised by NIST in 2024), and it's increasingly the default in TLS 1.3.
Certificates, CAs and the chain of trust
Key exchange alone doesn't stop a man-in-the-middle: an attacker could do a separate key exchange with each side. The client must know that the public key it received really belongs to bank.example. That's the job of X.509 certificates.
A certificate binds a public key to an identity (domain names in the Subject Alternative Name extension), with a validity period and constraints, all signed by a Certificate Authority (CA). Trust is a chain:
To validate a certificate, the client checks that:
- Each certificate's signature verifies with the next certificate's public key, up to a root CA in the local trust store (OS, browser, or the JVM's
cacerts). - The leaf's SAN matches the hostname being connected to.
- Every certificate is within its validity dates.
- Key usage and basic constraints allow the use (only CA certificates may sign others).
- Nothing has been revoked. CRLs and OCSP are imperfect, which is why the industry is moving to short-lived certificates instead.
Certificate lifetimes are shrinking. Under a 2025 CA/Browser Forum decision, the maximum fell from 398 to 200 days in March 2026, falls to 100 days in March 2027, and reaches 47 days in March 2029. Let's Encrypt issues 90-day certificates, with shorter options. The upshot: automate renewal, with ACME clients (certbot), cert-manager in Kubernetes, AWS ACM, or reverse proxies like Caddy that do it themselves. Expired certificates remain one of the most common causes of outages.
Common production problems:
- Missing intermediate: the server sends only its leaf. Browsers may paper over it (they cache intermediates or fetch them), but API clients (Java, Go, curl) fail with "unable to find valid certification path" or "x509: certificate signed by unknown authority."
- Private or corporate CAs: internal services signed by a company CA require adding that root to each client's trust store. The JVM uses its own
cacerts, not the OS store, and container images need the CA certificate baked in or mounted. Disabling verification (InsecureSkipVerify,-k, trust-all managers) "fixes" the error by removing the security entirely. Never ship it. - Name mismatch: connecting by IP address, or by an internal name not in the SAN list.
- Clock skew: a VM with a wrong clock sees valid certificates as expired or not yet valid.
- TLS interception: corporate proxies re-sign traffic with their own CA. Certificate pinning breaks behind them.
The TLS 1.3 handshake
TLS 1.3 needs one round trip before encrypted application data can flow (TLS 1.2 needed two):
- ClientHello: the client lists its supported cipher suites and sends a key share right away, guessing the group the server will choose (almost always X25519 or a hybrid with ML-KEM). It also sends SNI (Server Name Indication: which hostname it wants, so one IP can serve many certificates) and ALPN (which application protocol:
h2,http/1.1). - ServerHello: the server picks the parameters and sends its own key share. Both sides can now compute the shared secret and derive handshake keys. Everything after this point is encrypted, including the certificate. TLS 1.2 sent certificates in the clear.
- The server sends its Certificate chain, a CertificateVerify (a signature over the whole handshake transcript with the certificate's private key, which proves it holds the key) and a Finished MAC over the transcript, which detects tampering with any earlier message.
- The client verifies the chain, the signature and the Finished message, sends its own Finished, and can send application data in the same flight.
Session resumption (pre-shared keys from an earlier session) skips the certificate work, and 0-RTT ("early data") lets a returning client send its request in its very first flight. 0-RTT data can be replayed by an attacker, so servers must accept only idempotent requests that way (GET, not POST /payments).
SNI is sent in plaintext, which reveals the hostname to the network. Encrypted Client Hello (ECH) encrypts it using a key published in the DNS HTTPS record, and it's being deployed by Cloudflare and supported in Chrome and Firefox.
Forward secrecy
Perfect forward secrecy (PFS) means compromising a server's long-term private key later doesn't let an attacker decrypt traffic recorded earlier.
- Old RSA key exchange (TLS 1.2 and earlier) had the client encrypt the session secret with the server's RSA public key. Anyone who later obtained the private key (by theft, legal order, or the 2014 Heartbleed bug) could decrypt every recorded session.
- Ephemeral Diffie–Hellman (the E in ECDHE) generates fresh key pairs for every handshake and discards them afterwards. The certificate key is used only to sign, proving identity, never to encrypt secrets. Once a session's ephemeral keys are deleted, nobody can recompute that session's keys.
TLS 1.3 requires forward secrecy: RSA key exchange was removed entirely, along with static DH, CBC-mode ciphers, RC4, SHA-1, compression and renegotiation. Most of TLS 1.2's historical attacks (BEAST, CRIME, POODLE, Lucky13, FREAK, Logjam) were removed with them.
TLS in each language
// Client: verifies the chain and hostname by default
resp, err := http.Get("https://api.example.com/health")
// Server with a minimum version
srv := &http.Server{
Addr: ":8443",
TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12},
}
log.Fatal(srv.ListenAndServeTLS("cert.pem", "key.pem"))
// mTLS: tls.Config{ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: pool}
// Go's crypto/tls is a pure-Go implementation; ML-KEM hybrid key exchange is on by default in recent versions.
// JDK HttpClient: TLS 1.3 by default, trust store = $JAVA_HOME/lib/security/cacerts
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> r = client.send(
HttpRequest.newBuilder(URI.create("https://api.example.com/health")).build(),
HttpResponse.BodyHandlers.ofString());
// Add a private CA: keytool -importcert -alias corp -file corp-ca.pem -cacerts
// Debug handshakes: -Djavax.net.debug=ssl:handshake
// Spring Boot 3.1+: "SSL bundles" (spring.ssl.bundle.*) configure keystores declaratively.
// reqwest with rustls (pure-Rust TLS) or native-tls (OpenSSL / SChannel / Security.framework)
let body = reqwest::get("https://api.example.com/health").await?.text().await?;
// Server side: axum/hyper with tokio-rustls, or terminate TLS at a proxy.
// OpenSSL client sketch (error handling omitted)
SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
SSL_CTX_set_default_verify_paths(ctx); // use the system trust store
SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
SSL *ssl = SSL_new(ctx);
SSL_set_tlsext_host_name(ssl, "api.example.com"); // SNI
SSL_set1_host(ssl, "api.example.com"); // hostname verification: easy to forget!
SSL_set_verify(ssl, SSL_VERIFY_PEER, NULL);
SSL_set_fd(ssl, sockfd);
if (SSL_connect(ssl) != 1) { /* handshake failed */ }
# The universal debugging tools
$ openssl s_client -connect api.example.com:443 -servername api.example.com -showcerts
$ curl -v https://api.example.com/ # shows the TLS version, cipher, cert chain, ALPN
$ openssl x509 -in cert.pem -noout -text # inspect a certificate: SAN, dates, issuer
In production, TLS is often terminated at a load balancer, ingress or proxy (AWS ALB, Nginx, Envoy), with traffic re-encrypted to backends or carried in a service mesh with automatic mTLS (Istio, Linkerd). Zero-trust architectures encrypt and authenticate every hop, not just the edge (Part X).
Sockets: putting it together
The sockets API
Every language's networking ends in the same handful of system calls:
server: socket() → bind(addr:port) → listen(backlog) → accept() → read/write … → close()
client: socket() → connect(addr:port) [three-way handshake happens here] → write/read … → close()
UDP: socket(SOCK_DGRAM) → bind() → sendto()/recvfrom() (no connection, no accept)
A minimal TCP echo server in each language. Roadmap project 8 extends this into a chat server.
func main() {
ln, err := net.Listen("tcp", ":9000") // socket + bind + listen
if err != nil { log.Fatal(err) }
for {
conn, err := ln.Accept()
if err != nil { continue }
go func(c net.Conn) { // one goroutine per connection (netpoller underneath)
defer c.Close()
io.Copy(c, c) // echo until EOF
}(conn)
}
}
use tokio::{io, net::TcpListener};
#[tokio::main]
async fn main() -> io::Result<()> {
let listener = TcpListener::bind("0.0.0.0:9000").await?;
loop {
let (mut sock, _addr) = listener.accept().await?;
tokio::spawn(async move {
let (mut r, mut w) = sock.split();
let _ = io::copy(&mut r, &mut w).await; // echo
});
}
}
// JDK 21+: blocking code, virtual thread per connection
try (var server = new ServerSocket(9000);
var exec = Executors.newVirtualThreadPerTaskExecutor()) {
while (true) {
Socket s = server.accept();
exec.submit(() -> {
try (s; var in = s.getInputStream(); var out = s.getOutputStream()) {
in.transferTo(out); // echo until EOF
}
return null;
});
}
}
int main(void) {
int srv = socket(AF_INET6, SOCK_STREAM, 0); // IPv6 socket also accepts IPv4 (dual-stack)
int on = 1;
setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &on, sizeof on); // restart without "address in use"
struct sockaddr_in6 a = { .sin6_family = AF_INET6, .sin6_port = htons(9000), .sin6_addr = in6addr_any };
bind(srv, (struct sockaddr *)&a, sizeof a);
listen(srv, 128);
for (;;) {
int c = accept(srv, NULL, NULL);
char buf[4096]; ssize_t n;
while ((n = read(c, buf, sizeof buf)) > 0) write(c, buf, n); // one client at a time!
close(c);
}
}
pub fn main() !void {
const addr = try std.net.Address.parseIp("0.0.0.0", 9000);
var server = try addr.listen(.{ .reuse_address = true });
defer server.deinit();
while (true) {
const conn = try server.accept();
defer conn.stream.close();
var buf: [4096]u8 = undefined;
while (true) {
const n = try conn.stream.read(&buf);
if (n == 0) break;
try conn.stream.writeAll(buf[0..n]);
}
}
}
// (std.net APIs move between Zig releases as the new Io interface lands.)
Socket options worth knowing:
| Option | Purpose |
|---|---|
SO_REUSEADDR |
Restart a server while old connections sit in TIME_WAIT |
SO_REUSEPORT |
Several processes or threads bind the same port, and the kernel load-balances incoming connections |
TCP_NODELAY |
Disable Nagle: send small writes immediately |
SO_KEEPALIVE + TCP_KEEPIDLE/INTVL/CNT |
Detect dead peers and keep NAT/LB mappings alive (default idle time: 2 hours, usually far too long) |
SO_RCVBUF / SO_SNDBUF |
Buffer sizes (affect the flow-control window) |
SO_LINGER |
What close() does with unsent data. linger=0 sends RST immediately |
Timeouts (SO_RCVTIMEO, or language-level) |
Always set connect and read timeouts. Without them, a stuck peer hangs your thread forever |
Timeouts and the network fallacies
Peter Deutsch's fallacies of distributed computing are worth memorising. Every one is a false assumption that causes bugs:
- The network is reliable.
- Latency is zero.
- Bandwidth is infinite.
- The network is secure.
- Topology doesn't change.
- There is one administrator.
- Transport cost is zero.
- The network is homogeneous.
The practical rules that follow (Part III, chapter 52, expands them): every network call needs a timeout (connect, read, and an overall deadline); retries need backoff and jitter and must only be used for idempotent operations; reuse connections; set keepalives shorter than every middlebox's idle timeout; and treat "no response" as unknown, not as failure. The request might have succeeded, which is why idempotency keys exist.
Lab: protocols you can watch
This book's sandbox can't reach the internet directly (its DNS and outbound traffic go through a proxy), which turns out to be a good teaching constraint: every protocol below is exercised on localhost with both ends visible. Everything ran on Python 3.13 and OpenSSL 3.0.
Subnetting a cloud network
A typical exercise when designing a VPC (Volume 7): one /16 for the environment, split into per-zone private and public subnets, then checked against a partner network that will be connected by VPN.
vpc = ip.ip_network("10.20.0.0/16")
subnets = list(vpc.subnets(new_prefix=20)) # 16 subnets of /20
office = ip.ip_network("10.20.16.0/22") # a partner office network to be connected via VPN
clash = [str(n) for n in subnets[:6] if n.overlaps(office)]
VPC 10.20.0.0/16: 65,536 addresses, netmask 255.255.0.0, private=True
private-a 10.20.0.0/20 usable 4094 (first 10.20.0.1, last 10.20.15.254, broadcast 10.20.15.255)
private-b 10.20.16.0/20 usable 4094 (first 10.20.16.1, last 10.20.31.254, broadcast 10.20.31.255)
private-c 10.20.32.0/20 usable 4094 (first 10.20.32.1, last 10.20.47.254, broadcast 10.20.47.255)
public-a 10.20.48.0/20 usable 4094 (first 10.20.48.1, last 10.20.63.254, broadcast 10.20.63.255)
public-b 10.20.64.0/20 usable 4094 (first 10.20.64.1, last 10.20.79.254, broadcast 10.20.79.255)
public-c 10.20.80.0/20 usable 4094 (first 10.20.80.1, last 10.20.95.254, broadcast 10.20.95.255)
office 10.20.16.0/22 overlaps: ['10.20.16.0/20']
10.20.37.200 belongs to: 10.20.32.0/20
is 100.64.1.1 private? False | shared CGNAT space? True
The arithmetic: a /20 leaves 32 − 20 = 12 host bits, 4,096 addresses, minus network and broadcast = 4,094 usable (cloud providers reserve more: AWS reserves 5 per subnet). The overlap is the production lesson: the partner's 10.20.16.0/22 sits inside private-b, so routing over a VPN would be ambiguous. Overlapping private ranges between companies, VPCs and Kubernetes pod networks are one of the most common, most expensive networking mistakes, because renumbering a live network is painful. Plan address space centrally (an IPAM), leave room to grow, and avoid the ranges everyone uses by default (10.0.0.0/16, 192.168.0.0/24, 172.17.0.0/16 for Docker). 100.64.0.0/10 is carrier-grade NAT space: not RFC 1918 private, but not publicly routed either.
DNS on the wire, both ends
A tiny authoritative server for tiffinbox.test and a client, both written against RFC 1035 using nothing but struct and UDP sockets:
def enc_name(name): return b"".join(bytes([len(p)]) + p.encode() for p in name.split(".")) + b"\0"
def dec_name(msg, off): # follows compression pointers (top two bits 11)
labels, jumped, end = [], False, None
while True:
n = msg[off]
if n & 0xC0 == 0xC0:
if not jumped: end = off + 2
off = ((n & 0x3F) << 8) | msg[off + 1]; jumped = True; continue
if n == 0: return ".".join(labels), (end if jumped else off + 1)
labels.append(msg[off + 1: off + 1 + n].decode()); off += 1 + n
# server: header with QR=1 and AA=1, the question echoed, then one resource record per answer
hdr = struct.pack("!HHHHHH", qid, 0x8400 | rcode, 1, len(answers), 0, 0)
body += b"\xc0\x0c" + struct.pack("!HHIH", qtype, 1, ttl, len(rdata)) + rdata # owner name = pointer to offset 12
# client: a 12-byte header (random id, RD=1, one question), the encoded name, QTYPE and QCLASS
q = struct.pack("!HHHHHH", random.randint(0, 65535), 0x0100, 1, 0, 0, 0) + enc_name(name) + struct.pack("!HH", qtype, 1)
A api.tiffinbox.test query 36 B, reply 68 B, NOERROR, authoritative=True
api.tiffinbox.test 60s A 203.0.113.10
api.tiffinbox.test 60s A 203.0.113.11
CNAME www.tiffinbox.test query 36 B, reply 65 B, NOERROR, authoritative=True
www.tiffinbox.test 300s CNAME cdn.example.net
MX tiffinbox.test query 32 B, reply 67 B, NOERROR, authoritative=True
tiffinbox.test 3600s MX (10, 'mail.tiffinbox.test')
A nope.tiffinbox.test query 37 B, reply 37 B, NXDOMAIN, authoritative=True
What the bytes teach:
- A whole DNS exchange is tens of bytes in one UDP datagram each way: no handshake, which is why DNS is fast and why resolvers must handle loss by retrying (and why spoofing was easy until source-port randomisation and DNSSEC). The random 16-bit id is how the client matches a reply to its query.
- Names are length-prefixed labels (
3api9tiffinbox4test0), and replies use compression pointers (0xC00C= "the name at byte offset 12", the question) instead of repeating names, the two high bits marking a pointer. A parser that follows pointers without a loop limit can be sent into an infinite loop by a malicious packet: a classic DNS-parser vulnerability. Production code must cap the jumps. - TTL (60 s, 300 s, 3,600 s) is per record: resolvers cache each answer for that long, which is why DNS changes "propagate" slowly and why you lower TTLs before migrations (Volume 16, ch. 188).
- NXDOMAIN is a definite "this name doesn't exist", itself cached (negative caching, governed by the zone's SOA record).
- AA (authoritative answer) distinguishes the zone's own server from a recursive resolver relaying a cached answer.
TLS: a certificate chain from scratch
A three-level PKI built with OpenSSL: a root CA, an intermediate (issuing) CA signed by the root, and a server certificate for api.tiffinbox.test signed by the intermediate:
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -keyout root.key -out root.crt -days 3650 \
-subj "/CN=TiffinBox Lab Root CA" -addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign"
openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -keyout int.key -out int.csr -subj "/CN=TiffinBox Lab Issuing CA"
openssl x509 -req -in int.csr -CA root.crt -CAkey root.key -CAcreateserial -out int.crt -days 1825 \
-extfile <(printf "basicConstraints=critical,CA:TRUE,pathlen:0\nkeyUsage=critical,keyCertSign,cRLSign")
openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -keyout srv.key -out srv.csr -subj "/CN=api.tiffinbox.test"
openssl x509 -req -in srv.csr -CA int.crt -CAkey int.key -CAcreateserial -out srv.crt -days 90 \
-extfile <(printf "subjectAltName=DNS:api.tiffinbox.test\nextendedKeyUsage=serverAuth\nbasicConstraints=CA:FALSE")
openssl s_server -accept 18443 -cert srv.crt -key srv.key -cert_chain int.crt -www
openssl s_client -connect 127.0.0.1:18443 -servername api.tiffinbox.test -CAfile root.crt -verify_hostname api.tiffinbox.test
$ openssl verify -CAfile root.crt -untrusted int.crt srv.crt
srv.crt: OK
$ openssl verify -CAfile root.crt srv.crt # without the intermediate
error 20 at 0 depth lookup: unable to get local issuer certificate
$ openssl s_client ... (trusting the root, correct hostname)
depth=2 CN = TiffinBox Lab Root CA
depth=1 CN = TiffinBox Lab Issuing CA
depth=0 CN = api.tiffinbox.test
Peer signature type: ECDSA
Server Temp Key: X25519, 253 bits
New, TLSv1.3, Cipher is TLS_AES_256_GCM_SHA384
Verify return code: 0 (ok)
--- wrong hostname: Verify return code: 62 (hostname mismatch)
--- without trusting the root: Verify return code: 20 (unable to get local issuer certificate)
Each failure mode is a production incident somewhere every week:
- Missing intermediate (error 20): the server must send its intermediate certificates. Browsers sometimes paper over this by caching or fetching intermediates (AIA fetching), so the site "works in Chrome" while API clients, mobile apps and
curlfail. Always deploy the full chain (fullchain.pemfrom ACME clients). - Hostname mismatch (error 62): the certificate's subjectAltName must match the name the client connected to; the Common Name is ignored by modern clients. Wildcards (
*.tiffinbox.test) match one label only. - Untrusted root: private PKIs (internal services, service meshes) need their root distributed to every client's trust store; a missing trust store entry looks identical to an attack.
- Expiry: this leaf lasts 90 days; public certificates are heading to 47 days by 2029 (Volume 16, ch. 188), so renewal must be automated.
The handshake summary also shows the modern defaults: TLS 1.3, an ECDSA signature from the server's key (proving possession of the certificate's private key), an X25519 ephemeral Diffie-Hellman key exchange, and AES-256-GCM authenticated encryption. Because the session keys come from ephemeral keys discarded after the handshake, stealing the server's certificate key later can't decrypt recorded traffic: forward secrecy, mandatory in TLS 1.3.
Flow control you can see
TCP never lets a sender overrun a receiver: the receiver advertises a window of free buffer space. A sender writing to a receiver that accepts the connection but never reads:
c.setblocking(False)
while True:
try: sent += c.send(chunk)
except BlockingIOError: break
sent 159,744 bytes before send() would block (receiver's window and sender's buffer are full)
kernel buffers: SO_SNDBUF=131,072 SO_RCVBUF=131,072
receiver drained 159,744 bytes; the sender can now continue
About 156 KB fit into the receiver's receive buffer plus the sender's send buffer; then the receiver's advertised window hit zero and the sender's send() would block. (Linux doubles the requested 64 KB buffer sizes to leave room for bookkeeping, hence 131,072.) This is backpressure at the transport layer, and the reason a slow consumer eventually stalls a fast producer instead of losing data. It's also why a server that stops reading a client's socket (busy, deadlocked) makes that client's writes block, and why every network write in production needs a timeout (chapter 9, Volume 17, ch. 194D).
Revision sheet: networking
Key ideas
- Layering: application (HTTP, DNS), transport (TCP, UDP, QUIC), internet (IP), link (Ethernet, Wi-Fi). Each layer adds a header (encapsulation).
- IP delivers packets best-effort between addresses; routing forwards by longest-prefix match; CIDR notation (
10.0.0.0/8); NAT lets private networks share public addresses; ARP (IPv4) / NDP (IPv6) map IP to MAC on a link. - TCP: three-way handshake, sequence numbers and acknowledgements, retransmission, flow control (receive window), congestion control (slow start, CUBIC, BBR), four-way close and TIME_WAIT. It's a byte stream: applications must frame messages.
- UDP: datagrams, no connection or reliability; QUIC builds reliable, multiplexed, encrypted streams over UDP and underlies HTTP/3.
- DNS: hierarchical, cached by TTL; record types A, AAAA, CNAME, MX, TXT, NS; resolution via recursive resolvers.
- TLS 1.3: one round-trip handshake, ephemeral key exchange (forward secrecy), certificates chained to trusted roots, SNI and ALPN.
- HTTP: methods, status codes, headers, bodies; HTTP/1.1 keep-alive, HTTP/2 multiplexing over one TCP connection, HTTP/3 over QUIC.
- Sockets: the OS API (
socket,bind,listen,accept,connect,send,recv) every language wraps.
Numbers to remember
- Ethernet MTU 1,500 bytes; minimum IPv4 header 20 bytes, TCP header 20 bytes.
- Ports: 22 SSH, 53 DNS, 80 HTTP, 443 HTTPS, 5432 PostgreSQL, 6379 Redis; ephemeral range on Linux 32768–60999.
- Light in fibre: about 200 km per millisecond, so Mumbai to London (~7,200 km) is at least ~36 ms one way, ~72 ms round trip.
- New HTTPS connection over TCP + TLS 1.3: about 2 round trips before the first request byte (1 with QUIC, 0 with resumption).
Pitfalls
- Assuming one
sendequals onerecvon TCP. - No timeouts on connects and reads: one slow peer hangs your threads.
- Forgetting DNS caching and TTLs during migrations.
- Disabling certificate verification "temporarily".
- Opening a new connection per request instead of pooling (handshake cost, TIME_WAIT buildup).
- Ignoring Nagle's algorithm and delayed ACK interaction for small request/response protocols.
Glossary
- MTU: maximum transmission unit, the largest packet a link carries.
- RTT: round-trip time.
- Head-of-line blocking: one lost packet stalling everything behind it in the same ordered stream.
- SNI: the hostname a client sends in the TLS handshake so one IP can serve many sites.
- Ephemeral port: the temporary local port the OS picks for an outgoing connection.
- Anycast: one IP address announced from many locations; packets go to the nearest.