Networking Tutorial · Routing and Network Services · Lesson 17 of 28
NAT
How network address translation lets many private hosts share public addresses, and its limits.
What NAT does
NAT (Network Address Translation) rewrites addresses in packets as they pass through a router. The common kind, source NAT (also called PAT or masquerading), lets many hosts with private addresses share one public address:
- A private host
10.0.1.15:51000connects to93.184.215.14:443. - The NAT device replaces the source with its public address and a free port:
198.51.100.7:40001. - It remembers the mapping in a translation table, and rewrites replies back to
10.0.1.15:51000.
import itertools
PUBLIC_IP = "198.51.100.7"
ports = itertools.count(40001)
table = {}
def outbound(src, dst):
if (src, dst) not in table:
table[(src, dst)] = (PUBLIC_IP, next(ports))
return table[(src, dst)]
for src in [("10.0.1.15", 51000), ("10.0.2.30", 51000), ("10.0.1.15", 51001)]:
print(f"{src[0]}:{src[1]} -> {outbound(src, ('93.184.215.14', 443))}")
reverse = {v: k for k, v in table.items()}
reply_to = (PUBLIC_IP, 40002)
print("reply for", reply_to, "goes back to", reverse[reply_to][0])
Output
10.0.1.15:51000 -> ('198.51.100.7', 40001)
10.0.2.30:51000 -> ('198.51.100.7', 40002)
10.0.1.15:51001 -> ('198.51.100.7', 40003)
reply for ('198.51.100.7', 40002) goes back to ('10.0.2.30', 51000)Consequences
- Hosts behind NAT can start connections out, but nobody outside can connect in unless you add port forwarding (destination NAT) or use a load balancer.
- One public IP has about 64,000 ports per destination address, port and protocol. Many connections from many
hosts to the same destination can exhaust them. AWS NAT gateways support up to 55,000 simultaneous
connections to each unique destination and report
ErrorPortAllocationwhen they run out. - Idle mappings are removed after a timeout. AWS NAT gateways drop TCP connections idle for 350 seconds, so long-lived idle connections need keep-alives.
In the cloud, private subnets reach the internet through a NAT gateway (AWS), NAT gateway (Azure) or Cloud NAT (Google Cloud).
Test yourself
Why can't someone on the internet open a connection to a server in a private subnet behind a NAT gateway?
NAT only creates mappings for connections started from insidePrivate IPs are encryptedThe server has no portsDNS doesn't work for private hosts
Show answer
Answer: NAT only creates mappings for connections started from inside
Without an existing mapping, the NAT device has no idea which private host an incoming packet is for. Use a load balancer in a public subnet instead.