Part 2 · Addresses and routing
Routing, NAT and DHCP: how packets find their way
Course contents
In the IPv4 lesson a machine made one decision: is the destination on my own subnet, or do I send the packet to the router? This lesson follows the packet into the router and answers three questions you have been carrying since lesson 1:
- How does a router, or any machine, decide where to send a packet? (Routing tables.)
- How can every home use the same private addresses, like
192.168.1.20, and still reach the Internet with one public address? (NAT.) - Where did your laptop’s address come from in the first place? (DHCP.)
At the end you build two subnets, a router between them and NAT out to the Internet, from the same namespace building blocks as the LAN lab in lesson 3.
How a host decides where to send a packet
A router is a machine with interfaces on two or more networks that passes packets from one to another. But every device, from a laptop to a big router, decides where to send a packet in the same way: with a routing table, a list of “for destinations in this prefix, go this way” entries. For each outgoing packet:
- The kernel finds every route whose prefix contains the destination IP.
- Among those, it picks the longest prefix (the most specific one): longest prefix match. If both
10.0.0.0/8and10.1.2.0/24contain the destination, the/24wins. - If the route is “directly connected” (the destination is in the interface’s own subnet), the sender uses ARP to find the destination’s own MAC address and sends the frame straight to it.
- If the route has a next hop (a gateway), the packet is sent to the gateway’s MAC address; the destination IP is still the final destination.
- The default route (
0.0.0.0/0) is the shortest possible prefix and matches everything: “if nothing better matches, give it to the default gateway.”
ip route # the whole routing table
default via 192.168.1.1 dev wlan0 proto dhcp metric 600
172.17.0.0/16 dev docker0 proto kernel scope link src 172.17.0.1
192.168.1.0/24 dev wlan0 proto kernel scope link src 192.168.1.20
# ask the kernel: which route, interface and source IP for one destination?
ip route get 8.8.8.8
8.8.8.8 via 192.168.1.1 dev wlan0 src 192.168.1.20 uid 1000
cache
ip route get 172.17.0.5 # a destination in a directly-connected subnet
172.17.0.5 dev docker0 src 172.17.0.1 uid 1000
cache
8.8.8.8 doesn’t match any local subnet, so it goes out through default and the gateway (via 192.168.1.1). But 172.17.0.5 is in the docker0 subnet, so it is sent directly (dev docker0, no via). ip route get is the best command for answering “which way will this packet go?”
Where routes come from
- Connected: created automatically for every address you configure on an interface.
- Static: added by hand (
ip route add 10.50.0.0/16 via 10.0.0.254). - Dynamic: learned automatically from other routers, which tell each other which networks they can reach. The protocols for this (OSPF inside a company, BGP between the networks of the Internet) are the subject of the lesson on how the Internet is wired.
- When two routes have exactly the same prefix, the one with the lower metric (a cost number; you saw
metric 600inip route) wins. Big networks also use several equal routes at once to spread the load (ECMP, equal-cost multi-path).
Linux as a router
A normal machine throws away packets that aren’t addressed to it. A router passes them on. On Linux, the difference is one setting:
sysctl net.ipv4.ip_forward # 0 = behave like a host, 1 = behave like a router
You’ll switch it on inside the lab below; there’s no need to change it on your own machine. (Linux can also keep several routing tables and pick one by source address or other criteria, called policy-based routing; VPNs and Kubernetes use it, and you’ll see it in those lessons.)
NAT: Network Address Translation
In lesson 1 you saw that your laptop has a private address like 192.168.1.20, while websites see your home’s public address. Private addresses are never routed on the Internet (thousands of homes use the same ones), so something has to translate. That’s NAT (Network Address Translation): the router rewrites addresses, and usually ports, as packets pass through it. It exists because there aren’t enough IPv4 addresses to give every device a public one: a whole home or company shares one.
| Type | What gets rewritten | Used for |
|---|---|---|
| SNAT / masquerade / PAT | Source IP (and source port) | A private network going out to the Internet |
| DNAT / port forwarding | Destination IP (and destination port) | Publishing an internal server; Docker port publishing |
| 1:1 NAT | One fixed private IP to one fixed public IP | Elastic IPs in the cloud |
| CGNAT | A second NAT at the ISP, on 100.64.0.0/10 | ISPs short on IPv4; mobile networks |
PAT step by step
192.168.1.20:51000sends to203.0.113.7:443.- The router rewrites the source to its own public IP and a free port,
198.51.100.5:40001, and records the mapping in its translation table. - The reply arrives at
198.51.100.5:40001; the router looks it up in the table and rewrites it back to192.168.1.20:51000. - A packet from outside that arrives on a port that isn’t in the table is dropped. That is why NAT “looks like” a firewall, but it is not a firewall.
On Linux, NAT is configured with iptables (or its successor, nftables): the kernel’s built-in system for inspecting and changing packets, which the firewalls lesson covers properly. For now you need one rule: -j MASQUERADE means “replace the source address of these packets with my own address”. The translation table that remembers each mapping is called conntrack (connection tracking). Both can be looked at without changing anything:
sudo iptables -t nat -S # the NAT rules (if Docker is installed, you'll see its rules here)
sudo conntrack -L | head # the translation table: one line per tracked connection
The problems with NAT
- End-to-end connectivity is lost: nobody outside can call a device behind NAT directly. P2P, VoIP and games need NAT traversal techniques (STUN, TURN, ICE, hole punching), covered in the lesson on other protocols.
- Protocols that put IP addresses inside the payload (old-style FTP, SIP) need an ALG (application-level gateway).
- The NAT table is finite and its entries time out, so long-idle TCP connections can be dropped silently. That is why TCP keepalive and WebSocket ping/pong exist.
- With CGNAT, thousands of subscribers share one public IP. Blocking that IP blocks all of them, and per-IP rate limiting on websites stops making sense.
- Hairpin NAT: an internal host calls its own network’s public IP. Not every router handles this correctly.
DHCP: getting an address automatically
When your laptop joins a network it has no address at all, yet a moment later it has one, plus a default gateway and a DNS server. It got them from a DHCP server (Dynamic Host Configuration Protocol, RFC 2131); at home that’s another job of the home router. That’s what proto dhcp meant in your ip route output. DHCP runs over UDP (server port 67, client port 68) and takes four messages, remembered as DORA:
- Discover: the client, which has no IP yet, sends from
0.0.0.0to the broadcast address255.255.255.255: “Where is a DHCP server?” - Offer: a server offers an address.
- Request: the client requests that address (as a broadcast, so the other servers learn their offers were declined).
- Ack: the server confirms. The client now holds the address for the length of the lease, and renews it at roughly the halfway point.
Along with the address come options: subnet mask (1), router, i.e. the default gateway (3), DNS server (6), domain name (15), NTP server (42) and static routes (121).
- DHCP relay: DHCP depends on broadcast, and broadcasts don’t cross routers, so the router relays the messages to a central DHCP server (
ip helper-address). Option 82 adds information about the switch and port. - Reservation: a fixed address for a specific MAC address.
- Threats: a rogue DHCP server (someone handing out a fake gateway and DNS server) and DHCP starvation (exhausting the pool). The defense is DHCP snooping on the switch.
- If no DHCP server answers, the operating system picks a
169.254.x.x(link-local) address. Seeing one means “DHCP didn’t work.”
Good to know: other kinds of delivery
Almost all traffic is unicast: one sender, one receiver. You have also met broadcast (ARP, DHCP). For completeness, the four kinds:
| Type | Who receives it | Examples |
|---|---|---|
| Unicast | One specific device | Almost all traffic |
| Broadcast | Every device in the broadcast domain (IPv4 only) | ARP Request, DHCP Discover |
| Multicast | The devices that joined the group | IPTV, mDNS on 224.0.0.251, routing protocols, stock market feeds |
| Anycast | The nearest of several devices sharing one address | DNS root servers, 1.1.1.1, CDNs |
Multicast needs machines to announce which groups they want to receive (with a protocol called IGMP) and switches and routers that understand it, so it’s used inside company and provider networks (TV streams, finance data) but is practically unavailable across the public Internet. Anycast is the opposite trick: many servers in different places share one address, and routing delivers each packet to the nearest one; you’ll see it in the BGP lesson.
Gateway redundancy: VRRP
If a network’s only default gateway fails, everyone loses connectivity. VRRP (and its Cisco counterpart, HSRP) puts two or more routers behind one virtual IP. One is the master; if it fails, another takes over the virtual IP and announces it with a gratuitous ARP. On Linux you implement it with keepalived.