8 min
  • TCP/IP
  • Topology

NAT and private addresses

IPv4 has about four billion addresses and the world has rather more than four billion connected devices. That arithmetic stopped working in the 1990s, and the workaround almost every home network on Earth runs on is NAT.

The idea is small. Machines inside use private addresses that no public router will carry, and the boundary router rewrites the sender as packets leave:

text
Leaving the house:  from 192.168.1.24:51820  ->  from 203.0.113.7:40001                                            ^ chosen by the router, recorded in a table Coming back:  to   203.0.113.7:40001   ->  to   192.168.1.24:51820                                            ^ the exact reverse, from the same table

The router keeps one entry per conversation, and the reply is matched against it. That is the whole mechanism — and everything odd about NAT follows from it.

Loading the Network Map simulation…

Ports are what make it work

The translation needs somewhere to record which inside machine a returning packet belongs to, and it uses the port number for that. Which means NAT works for TCP and UDP, and does not work for anything without ports — the reason a plain ICMP echo needs special handling rather than falling out of the design.

Watch the rewrite happen and be reversed on the return trip:

Loading the Packet Journey simulation…
Check yourself
Why does NAT rewrite the port number as well as the address?

What NAT quietly took away

The end-to-end principle held that any host could address any other host. NAT ends that, and the consequences are everywhere:

  • An unsolicited inbound connection has no table entry, so there is nowhere to send it. That is why hosting a service at home needs a port forward.
  • Two machines both behind NAT cannot connect directly without help, which is why video-call and peer-to-peer software carries an entire subsystem — STUN, TURN, ICE — to negotiate around it.
  • Table entries expire. An idle connection whose entry is evicted stops working with no notification to either end, which is the exact reason a WebSocket needs a heartbeat.
Predict what happens next
A connection sits idle for ten minutes behind a home router. What happens to it?

Key takeaways

  • NAT exists because IPv4 ran out of addresses, and it works by rewriting the source of packets leaving a boundary.
  • The port number is what records which inside machine a reply belongs to, which is why NAT needs a transport with ports.
  • Private ranges are unique only inside one network, so they can be reused everywhere and break when two such networks meet.
  • Unsolicited inbound connections have no table entry and nowhere to go — hence port forwarding, and hence STUN and TURN.
  • Translation entries expire silently, which is the most common reason a long-lived connection needs a keepalive.

Take it further