Sub topic 12
How NAT Lets Private Hosts Reach the Internet
This chapter assumes you can read dotted-decimal addresses, apply a prefix length to find a network, and recognize the three RFC 1918 private ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16). It explains how network address translation (NAT) lets hosts with those private addresses talk to the public internet, and where that mechanism breaks down.
The problem NAT solves
Private addresses are not routed on the public internet. Internet routers drop packets whose destination is an RFC 1918 address, and ISPs filter packets with private source addresses. A host at 192.168.1.10 can send a packet to 8.8.8.8, but the reply would be addressed to 192.168.1.10, which no internet router knows how to reach.
NAT fixes this at the border between the private network and the public one. A device at that border rewrites the addresses in packet headers. Outbound packets leave with a public source address. Inbound replies are rewritten back to the private address and delivered inside.
The border device is usually a home router, a firewall, or a cloud gateway. It has at least two interfaces:
- An inside interface with a private address, such as 192.168.1.1.
- An outside interface with a public address, such as 203.0.113.25.
Types of NAT
Several variants share the name "NAT". They differ in how many private hosts can share public addresses at once.
| Type | Mapping | Public addresses needed | Typical use |
|---|---|---|---|
| Static NAT | One private address to one fixed public address | One per host | Publishing an internal server |
| Dynamic NAT | Private addresses to a pool of public addresses, first come first served | One per simultaneous host | Older enterprise networks |
| PAT (port address translation, also called NAT overload or masquerade) | Many private addresses to one public address, told apart by port | One for the whole network | Home routers, most corporate and cloud egress |
When people say "NAT" without qualification, they almost always mean PAT. The rest of this chapter focuses on it.
Why ports make one address enough
A connection is identified by five values: protocol, source address, source port, destination address, and destination port. A router can let many hosts share one public address because the source port keeps their connections apart.
Suppose two laptops behind the same router both browse to the same web server. Each uses its own source port, but they could pick the same one. The router handles this by keeping a translation table. It records each outbound connection and assigns a unique public-side port.
The table for two such connections might look like this:
| Protocol | Inside address:port | Outside (translated) address:port | Destination |
|---|---|---|---|
| TCP | 192.168.1.10:51000 | 203.0.113.25:40001 | 198.51.100.7:443 |
| TCP | 192.168.1.11:51000 | 203.0.113.25:40002 | 198.51.100.7:443 |
Both laptops used source port 51000. The router rewrote one to 40001 and the other to 40002, so the server sees two distinct connections from 203.0.113.25.
Walking through one connection
The sequence below shows an outbound request and its reply.
The steps are:
- The laptop sends a packet to its default gateway, the router's inside address.
- The router sees that the destination is outside the private network. It creates a table entry and rewrites the source address and port.
- The router recalculates the IP header checksum and the TCP or UDP checksum, because both cover the addresses and ports that changed.
- The server replies to 203.0.113.25:40001. It never learns that 192.168.1.10 exists.
- The router matches the reply to its table entry, rewrites the destination back, and forwards the packet inside.
The router can only match a reply if an entry already exists. For this reason, NAT behaves like a basic stateful filter: unsolicited inbound packets have no entry and are dropped. This is a side effect and not a designed security feature. A firewall policy should still be written explicitly.
What happens to the table entries
Each entry has a lifetime. TCP entries are removed shortly after the connection closes (FIN or RST), or after a long idle timeout if the connection goes quiet. UDP has no connection state, so entries expire after a short idle timeout, often 30 to 120 seconds. DNS queries and VoIP traffic rely on this behavior, and long-lived UDP flows often send keepalive packets to hold the entry open.
The table is also finite. Each public address provides roughly 64,000 usable ports per protocol for each destination. A busy gateway that makes many connections to one destination can run out of ports. This is called port exhaustion, and its symptom is that new connections fail while existing ones keep working.
Configuring NAT on Linux
Linux implements NAT in the kernel through netfilter. The following commands turn a Linux host with two interfaces into a PAT router. They assume eth0 faces the internet and eth1 faces the private LAN.
# Allow the kernel to forward packets between interfaces
sudo sysctl -w net.ipv4.ip_forward=1
# Rewrite the source of packets leaving eth0 to eth0's current address
sudo iptables -t nat -A POSTROUTING -o eth0 -s 192.168.1.0/24 -j MASQUERADE
# Allow forwarding from the LAN, and replies back in
sudo iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
sudo iptables -A FORWARD -i eth0 -o eth1 -m state --state ESTABLISHED,RELATED -j ACCEPTMASQUERADE reads the outside interface address each time a packet leaves. It suits connections with an address that changes, such as DHCP. If the public address is fixed, -j SNAT --to-source 203.0.113.25 is slightly cheaper.
To inspect the live translation table, use the conntrack tool:
sudo conntrack -L -p tcpEach line shows the original tuple and the reply tuple, which is the NAT mapping.
Inbound connections: port forwarding
PAT works for connections that start inside. To let someone on the internet reach a server inside, you create a static mapping in advance. This is destination NAT (DNAT), commonly called port forwarding.
# Send TCP port 8080 on the router's public address to an internal web server
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8080 \
-j DNAT --to-destination 192.168.1.50:80Now a request to 203.0.113.25:8080 is rewritten to 192.168.1.50:80. The router reverses the translation on the reply.
Modelling a translation table in Python
The sketch below models the core of PAT. It keeps a table keyed by the inside endpoint and assigns each new connection a public port.
import itertools
class Pat:
def __init__(self, public_ip, first_port=40000):
self.public_ip = public_ip
self._ports = itertools.count(first_port)
self.out = {} # (inside_ip, inside_port, dst_ip, dst_port) -> public_port
self.back = {} # (public_port, dst_ip, dst_port) -> (inside_ip, inside_port)
def outbound(self, src_ip, src_port, dst_ip, dst_port):
key = (src_ip, src_port, dst_ip, dst_port)
if key not in self.out:
port = next(self._ports)
self.out[key] = port
self.back[(port, dst_ip, dst_port)] = (src_ip, src_port)
return self.public_ip, self.out[key]
def inbound(self, public_port, remote_ip, remote_port):
# Returns None for unsolicited traffic: no entry means drop
return self.back.get((public_port, remote_ip, remote_port))
nat = Pat("203.0.113.25")
print(nat.outbound("192.168.1.10", 51000, "198.51.100.7", 443)) # ('203.0.113.25', 40000)
print(nat.outbound("192.168.1.11", 51000, "198.51.100.7", 443)) # ('203.0.113.25', 40001)
print(nat.inbound(40001, "198.51.100.7", 443)) # ('192.168.1.11', 51000)
print(nat.inbound(40001, "203.0.113.99", 443)) # NoneThe last line shows the stateful-filter behavior: a packet from an unknown remote host matches nothing, so it is dropped. A real implementation also expires entries and handles ICMP, but the lookup structure is the same.
Limitations and edge cases
NAT breaks the original end-to-end model of IP, where any host can address any other host directly. Common consequences are:
- Protocols that carry addresses in the payload. FTP active mode, SIP, and some game protocols embed IP addresses inside application data. A plain NAT only rewrites headers, so these need an application layer gateway (ALG) that also rewrites the payload, or the protocol must use a different technique.
- Peer-to-peer connections. Two hosts, each behind its own NAT, cannot connect directly because neither has an entry for the other. Applications use techniques such as STUN, hole punching, or a relay server.
- Logging and attribution. A server sees only the public address. Thousands of users can share it, so an abuse report needs the NAT log (inside address, port, and timestamp) to identify one user.
- Fragmentation. Only the first IP fragment carries the TCP or UDP header with ports. A NAT must reassemble or track fragments, and some implementations handle this poorly.
- Troubleshooting. A capture on the inside shows different addresses than a capture on the outside. Capture on both sides of the router when tracing a problem.
- Overlapping address space. If two networks joined by NAT or VPN both use 192.168.1.0/24, routing is ambiguous. This is covered further in the chapter on private range pitfalls.
Relationship to IPv6
NAT became widespread because IPv4 has only about 4.3 billion addresses. IPv6 has enough addresses for every device to be globally unique, which removes the need for address-sharing NAT. Many networks still run both, and IPv6 firewalls take over the filtering role that NAT incidentally played.
Exercise
Two laptops at 192.168.1.10 and 192.168.1.11 both connect from source port 52000 to 198.51.100.7:443 through a PAT router with public address 203.0.113.25. (a) How does the router keep the two connections apart? (b) A reply arrives at 203.0.113.25:40002 from 198.51.100.7:443. What does the router do with it if no table entry has public port 40002?
Show answer
(a) The router creates a separate translation entry for each connection and assigns each a unique public source port, for example 40001 and 40002. The server sees two connections from 203.0.113.25 on different ports, and the router uses the destination port of each reply to find the right inside host. (b) With no matching entry, the router cannot know which inside host the packet belongs to, so it drops it (or, if a port-forwarding rule exists for that port, applies that rule instead).
Exercise
A home router shows the public address 100.72.14.9 on its outside interface, yet web services report your address as 203.0.113.80. What does this suggest, and what is the consequence for hosting a server at home?
Show answer
The 100.72.14.9 address is in 100.64.0.0/10, the shared address space used for carrier-grade NAT. The ISP runs a second NAT in front of your router, and 203.0.113.80 is the ISP's shared public address. Port forwarding on your own router will not work, because inbound connections reach the ISP's NAT first, which has no entry for them. You would need a public address from the ISP, IPv6, or a tunnel or relay service.