NAT
Network Address Translation lets many devices with private addresses (like 192.168.1.x) share one public IPv4 address. Your home router does it: every phone and laptop in the house reaches the Internet, but websites only ever see the router's single public address. NAT is the main reason IPv4 survived long past the point where addresses ran out.
Kinds of NAT
| Kind | Mapping | Use |
|---|---|---|
| Static NAT | one private IP ↔ one public IP, permanently | publishing a server |
| Dynamic NAT | private IPs borrow public IPs from a pool | rare today |
| PAT / NAPT ("NAT overload", masquerade) | many private IP:port pairs ↔ one public IP, different ports | every home router |
| Port forwarding (DNAT) | public port → a fixed private IP:port | running a game server at home |
| CGNAT | the ISP does PAT again for many customers | mobile networks, IPv4-short ISPs |
How PAT works
When an inside host sends a packet out, the router:
- rewrites the source IP to its public address,
- rewrites the source port to a free port on that address (if needed),
- records the mapping in its translation table,
- recomputes the IP and TCP/UDP checksums.
When a reply comes back to the public IP and that port, the router looks up the table and rewrites the destination back to the inside host.
class PatRouter:
def __init__(self, public_ip, first_port=40000):
self.public_ip = public_ip
self.next_port = first_port
self.out_map = {} # (proto, inside_ip, inside_port) -> public_port
self.in_map = {} # (proto, public_port) -> (inside_ip, inside_port)
def outbound(self, proto, src, sport, dst, dport):
key = (proto, src, sport)
if key not in self.out_map:
self.out_map[key] = self.next_port
self.in_map[(proto, self.next_port)] = (src, sport)
self.next_port += 1
pport = self.out_map[key]
print(f"OUT {proto} {src}:{sport} -> {dst}:{dport} becomes {self.public_ip}:{pport} -> {dst}:{dport}")
return pport
def inbound(self, proto, src, sport, dport):
inside = self.in_map.get((proto, dport))
if inside is None:
print(f"IN {proto} {src}:{sport} -> {self.public_ip}:{dport} no mapping: DROP")
return
print(f"IN {proto} {src}:{sport} -> {self.public_ip}:{dport} becomes {src}:{sport} -> {inside[0]}:{inside[1]}")
nat = PatRouter("203.0.113.7")
p1 = nat.outbound("tcp", "192.168.1.20", 51514, "93.184.215.14", 443)
p2 = nat.outbound("tcp", "192.168.1.31", 51514, "93.184.215.14", 443) # same port, other host
p3 = nat.outbound("udp", "192.168.1.20", 33000, "8.8.8.8", 53)
nat.inbound("tcp", "93.184.215.14", 443, p2)
nat.inbound("udp", "8.8.8.8", 53, p3)
nat.inbound("tcp", "198.51.100.66", 4444, 40100) # unsolicited
print("translation table:")
for (proto, ip, port), pport in nat.out_map.items():
print(f" {proto} {ip}:{port} <-> {nat.public_ip}:{pport}")OUT tcp 192.168.1.20:51514 -> 93.184.215.14:443 becomes 203.0.113.7:40000 -> 93.184.215.14:443
OUT tcp 192.168.1.31:51514 -> 93.184.215.14:443 becomes 203.0.113.7:40001 -> 93.184.215.14:443
OUT udp 192.168.1.20:33000 -> 8.8.8.8:53 becomes 203.0.113.7:40002 -> 8.8.8.8:53
IN tcp 93.184.215.14:443 -> 203.0.113.7:40001 becomes 93.184.215.14:443 -> 192.168.1.31:51514
IN udp 8.8.8.8:53 -> 203.0.113.7:40002 becomes 8.8.8.8:53 -> 192.168.1.20:33000
IN tcp 198.51.100.66:4444 -> 203.0.113.7:40100 no mapping: DROP
translation table:
tcp 192.168.1.20:51514 <-> 203.0.113.7:40000
tcp 192.168.1.31:51514 <-> 203.0.113.7:40001
udp 192.168.1.20:33000 <-> 203.0.113.7:40002
Two laptops used the same source port 51514 at the same time; PAT kept them apart by giving each a different public port. The unsolicited packet from outside was dropped because no inside host had started that conversation.
Port forwarding
To run a server behind NAT, you add a static inbound rule: "traffic to public port 8443 goes to 192.168.1.50:443".
forwards = {("tcp", 8443): ("192.168.1.50", 443), ("udp", 25565): ("192.168.1.60", 25565)}
def inbound(proto, dport):
target = forwards.get((proto, dport))
return f"-> {target[0]}:{target[1]}" if target else "-> dropped (no rule)"
for proto, port in [("tcp", 8443), ("udp", 25565), ("tcp", 22)]:
print(f"{proto} to 203.0.113.7:{port:<6} {inbound(proto, port)}")tcp to 203.0.113.7:8443 -> 192.168.1.50:443
udp to 203.0.113.7:25565 -> 192.168.1.60:25565
tcp to 203.0.113.7:22 -> dropped (no rule)
How many hosts can share one address?
Ports are 16 bits, and some are reserved, so one public IP supports roughly 64,000 simultaneous connections per protocol and per destination. Carrier-grade NAT gives each customer a block of ports:
usable_ports = 65536 - 1024
for ports_per_customer in [512, 1024, 2048, 4096]:
customers = usable_ports // ports_per_customer
print(f"{ports_per_customer:>5} ports each -> {customers:>3} customers per public IPv4 address") 512 ports each -> 126 customers per public IPv4 address
1024 ports each -> 63 customers per public IPv4 address
2048 ports each -> 31 customers per public IPv4 address
4096 ports each -> 15 customers per public IPv4 address
A modern web page can open dozens of connections, so a too-small block shows up as mysterious failures for heavy users.
The downsides of NAT
- Breaks end-to-end connectivity: outside hosts can't start connections to inside hosts. Peer-to-peer apps and video calls need tricks such as STUN (discover your public address), TURN (relay through a server) and ICE (try everything) to get through, or hole punching.
- Protocols that carry addresses in their payload (FTP's active mode, SIP) need helper modules ("ALGs") that rewrite the payload too.
- State: the router must remember every connection; tables can fill up, and mappings time out on idle connections (keep-alives help).
- Logging: with CGNAT, an abuse report about a public IP is useless without the port number and exact time.
Note: NAT hides inside addresses, which gives some incidental protection, but it is not a firewall. A stateful firewall policy should still decide what's allowed. IPv6 networks normally don't use NAT at all: every device gets a global address and a firewall controls inbound traffic.
sudo iptables -t nat -L POSTROUTING -n -v
sudo conntrack -L -p tcp | head -3Sample output:
Chain POSTROUTING (policy ACCEPT 1520 packets, 98K bytes)
pkts bytes target prot opt in out source destination
412 27860 MASQUERADE all -- * eth0 192.168.1.0/24 0.0.0.0/0
tcp 6 431999 ESTABLISHED src=192.168.1.20 dst=93.184.215.14 sport=51514 dport=443 src=93.184.215.14 dst=203.0.113.7 sport=443 dport=40000 [ASSURED] mark=0 use=1Test yourself
With PAT, how does the router tell apart replies for two inside hosts sharing one public IP?
- By their MAC addresses
- By the public port number in the translation table
- By the TTL
- It can't, so only one host may connect
Why can't an outside host normally start a connection to a laptop behind a home router?
- Private addresses are encrypted
- There is no translation entry for the unsolicited packet
- TCP doesn't work through routers
- The TTL is too low
Which fields does a NAT router change on an outbound packet?
- Destination IP and port
- Source IP (and often source port), plus checksums
- Only the TTL
- The MAC address only