There are not enough public IPv4 addresses for every device. Network Address Translation (NAT) lets a router rewrite addresses as packets pass, so that many private hosts can share one public address.
How it works
Your laptop 192.168.1.50 connects from port 51000 to a web server. The router rewrites the source before sending it on:
| | Source | Destination | |---|---|---| | Inside | 192.168.1.50:51000 | 198.51.100.10:443 | | Outside | 203.0.113.5:51000 | 198.51.100.10:443 |
The router remembers this in a connection table. When the reply arrives at 203.0.113.5:51000, it looks up the entry and sends it to the laptop. If two connections would clash, for example two hosts using the same source port to reach the same server, the router changes one of the ports.
Kinds of NAT
- Source NAT changes the source address, typically for outgoing traffic.
- Masquerade is source NAT that uses whatever address the outgoing interface has. It is handy when that address changes.
- Destination NAT, or port forwarding, changes the destination so that outside connections reach an inside server.
- Static NAT maps one address to one other address.
Sharing one address by using ports is often called NAPT or PAT.
NAT on Linux
Linux does NAT in the kernel's netfilter, configured with nft or iptables. With nftables, where eth0 faces outward:
$ sudo nft add table ip nat
$ sudo nft add chain ip nat postrouting '{ type nat hook postrouting priority 100; }'
$ sudo nft add rule ip nat postrouting oifname "eth0" masqueradeIP forwarding must also be on (sysctl net.ipv4.ip_forward=1), and the firewall must allow the forwarded traffic. These rules are lost at reboot unless saved. Firewall managers such as firewalld or ufw have their own way to do this, so do not mix methods without care.
The costs
Outside hosts cannot start a connection to an inside host without a forwarding rule or static mapping. Some protocols that carry addresses inside their data need help. NAT is not a firewall: use real filtering rules. Providers may add a second layer, called carrier-grade NAT, often using 100.64.0.0/10.
The networking basics guide covers ports and addresses.
Try it
Compare the address from ip -4 address with the one shown as WAN or internet address on your router's status page. Are they different? Is the router's one private or in 100.64.0.0/10? If so, another NAT sits further out. Try the rules above only on a test machine.
Check your understanding
Network Address Translation (NAT)
All 4 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.