16. NAT: One Public Address for the Whole House

How R1 lets a dozen private devices share 198.51.100.23, rewriting addresses, ports and checksums on every packet, and what that sharing quietly breaks

Picture an office building with a single postal address. Hundreds of people work inside, each at a desk with an internal number, but the outside world only knows the building. When someone posts a letter, the mailroom crosses out "Desk 10" on the return address, writes the building's address instead, adds a reference number, and makes a note in a ledger: reference 47130: Desk 10, writing to Acme Ltd. When the reply comes back addressed to "the building, reference 47130", the mailroom looks up the ledger and walks it up to Desk 10.

Now imagine a letter arrives that quotes no reference anyone recognises: a stranger writing out of the blue. The mailroom has no idea which desk it's for. Unless someone has left a standing instruction ("anything marked archive goes to room 30"), it goes in the bin.

That is NAT, Network Address Translation, and almost every home and office on IPv4 has one. In our house it's R1. The DHCP article ended with R1 holding exactly one public address, 198.51.100.23, from the ISP, while handing out private 192.168.x.x addresses to everything indoors. Those private addresses mean nothing on the Internet; no server could ever reply to one. So R1 rewrites every packet that leaves, keeps a ledger of who's talking to whom, and rewrites the replies on the way back in.

This page follows the laptop's TCP SYN from the TCP article through R1 byte by byte, including both checksums. Then it looks at what happens when two devices pick the same port, how long R1 remembers each conversation, how two devices behind different NATs can still reach each other directly, and what NAT breaks along the way. It ends with IPv6, which doesn't need NAT at all, and the firewall that remains.

Why NAT Exists

IPv4 addresses are 32 bits, a little over four billion of them, and as IPv4 Addressing told it, that was never going to be enough. On 3 February 2011, IANA handed its last five /8 blocks to the regional registries, and the regions ran down their own supplies over the following years.

By then a workaround had been in use for well over a decade. RFC 1918 (1996) set aside three private blocks, 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16, that anyone may use inside their own network and that are never routed on the public Internet. Millions of homes use 192.168.10.0/24 at the same moment, and it doesn't matter, because none of those addresses ever leave the house. Something at the edge has to translate.

That something was first written down in RFC 1631, "The IP Network Address Translator", by Kjeld Egevang and Paul Francis in May 1994. It described itself as a short-term solution to address depletion, to tide the Internet over until something better arrived. Thirty years on, the something better (IPv6) is used by only about half of Google's users, and the short-term fix is in nearly every home router on the planet.

Four kinds of translation

RFC 1631 described rewriting addresses only. Its successors, the terminology document RFC 2663 (1999) and RFC 3022 (2001, "Traditional NAT"), separated a few variants that are still worth keeping apart:

Kind What it maps Typical use
Static NAT, or 1:1 One private address ↔ one public address, permanently A server that needs a fixed public face
Basic NAT Private addresses ↔ a pool of public ones, first come, first served Early corporate networks with a few spare addresses
NAPT Many private addresses and ports ↔ one public address, different ports Every home router
Twice NAT Source and destination rewritten Joining two networks that use the same private range

NAPT, Network Address and Port Translation, is the one that matters. Basic NAT can only let as many devices out at once as it has public addresses. NAPT lets a whole house share one, by also rewriting the port: each conversation gets its own port on the public address, and the port is what tells R1 which device a reply belongs to. Linux called its implementation IP masquerading, which is why the rule we'll write later says masquerade. Cisco calls it PAT, port address translation, or "NAT overload". In everyday speech, "NAT" almost always means NAPT, and so does the rest of this page.

INSIDE · private (RFC 1918) OUTSIDE · public Laptop 192.168.10.10 Desktop 192.168.10.40 NAS 192.168.10.30 TV (IoT) 192.168.20.50 Guest laptop 192.168.30.100 R1 · NAT LAN 192.168.x.1 WAN 198.51.100.23 the only public address The Internet ISP, routers R2–R4 Web server 203.0.113.80 Five devices inside; to the server, every one of them is 198.51.100.23.

How NAPT Works

At the heart of R1's NAT is a translation table. Each entry ties together two views of one conversation: how it looks from inside, and how it looks from outside. Here's the entry R1 creates when the laptop opens its TCP connection to the web server:

Side Source Destination
Inside (as the laptop sends it) 192.168.10.10:47130 203.0.113.80:80
Outside (as the server sees it) 198.51.100.23:47130 203.0.113.80:80

Add the protocol, TCP, and each side is a five-tuple. The whole job of NAPT is to turn one five-tuple into the other, in both directions:

INSIDE (VLAN 10) OUTSIDE (WAN) R1's NAT table tcp in 192.168.10.10:47130 out 198.51.100.23:47130 rem 203.0.113.80:80 src 192.168.10.10:47130 dst 203.0.113.80:80 src 198.51.100.23:47130 dst 203.0.113.80:80 src 203.0.113.80:80 dst 198.51.100.23:47130 src 203.0.113.80:80 dst 192.168.10.10:47130 ① rewrite source, create entry ② look up destination, rewrite it back dst 198.51.100.23:5000 ③ no entry: dropped The red fields are the ones R1 rewrites; everything else passes through.
  1. Outbound: a new conversation

    A packet arrives on a LAN interface, bound for the Internet. R1 routes it as usual (default route, out of eth1). Because it's leaving by the WAN, R1 looks for an existing entry for this five-tuple. There isn't one, so it picks an outside port, here the same 47130 the laptop used, writes the entry, and rewrites the source address and port.

  2. Outbound: the same conversation again

    Every later packet of this connection matches the entry and gets the same rewrite. No decisions, just a lookup.

  3. Inbound: a reply

    A packet arrives on eth1 for 198.51.100.23:47130 from 203.0.113.80:80. R1 looks up that outside five-tuple, finds the entry, and rewrites the destination back to 192.168.10.10:47130. Now the ordinary routing table takes over and sends it out of eth0.10.

  4. Inbound: a stranger

    A packet for 198.51.100.23:5000 that matches no entry has no inside address to go to. Unless there's a port-forwarding rule for it (we'll get to those), R1 drops it or, for packets addressed to R1 itself, hands it to R1's own sockets.

Notice the asymmetry. Outbound packets create entries; inbound packets can only use them. That's why devices behind NAT can reach anything on the Internet but can't be reached, and nearly every problem later on this page comes from that one fact.

The SYN Through R1, Byte by Byte

The TCP article decoded the laptop's SYN exactly as it left the laptop. Here it is again, and below it the same packet as R1 sends it out of eth1. Only the  TTL and the two checksums  and the  source address  change. The port, 47130 (b8 1a), was free on the outside, so R1 kept it.

Hex dump: the SYN as the laptop sends it

0000  45 00 00 3c 8e 4d 40 00 40 06 a5 6b c0 a8 0a 0a  E..<.M@[email protected]....
0010  cb 00 71 50 b8 1a 00 50 6b 2f 91 c4 00 00 00 00  ..qP...Pk/......
0020  a0 02 fa f0 06 4a 00 00 02 04 05 b4 04 02 08 0a  .....J..........
0030  0c 4a 7e 19 00 00 00 00 01 03 03 07              .J~.........

Hex dump: the same SYN as R1 sends it

0000  45 00 00 3c 8e 4d 40 00 3f 06 46 d3 c6 33 64 17  E..<.M@.?.F..3d.
0010  cb 00 71 50 b8 1a 00 50 6b 2f 91 c4 00 00 00 00  ..qP...Pk/......
0020  a0 02 fa f0 a6 b1 00 00 02 04 05 b4 04 02 08 0a  ................
0030  0c 4a 7e 19 00 00 00 00 01 03 03 07              .J~.........

c6 33 64 17 is 198.51.100.23. The TTL drops from 40 (64) to 3f (63) because R1 is a router; that part has nothing to do with NAT. The IPv4 header checksum goes from a5 6b to 46 d3, and the TCP checksum from 06 4a to a6 b1.

Why does the TCP checksum change, when R1 didn't touch a single byte of the TCP header? The answer is the UDP article's pseudo‑header: TCP's checksum covers the source and destination addresses as well as the segment. Change the address and the checksum is wrong, so a NAT has to fix both checksums, always, even when it keeps the port. If it changes the port too, the TCP checksum has two reasons to change.

Fixing the checksums: the long way

The straightforward approach is to recompute both from scratch. The IPv4 header's ten words, with the new TTL and source and the checksum field as zero:

4500+003c+8e4d+ 4000+3f06+0000+ c633+6417+ cb00+7150= 3b929\begin{aligned} & \texttt{4500} + \texttt{003c} + \texttt{8e4d} \\ +\ & \texttt{4000} + \texttt{3f06} + \texttt{0000} \\ +\ & \texttt{c633} + \texttt{6417} \\ +\ & \texttt{cb00} + \texttt{7150} \\ =\ & \texttt{3b929} \end{aligned}

Fold the carry and flip the bits:

b929+3=b92c¬ b92c=46d3\begin{aligned} & \texttt{b929} + \texttt{3} = \texttt{b92c} \\ & \lnot\,\texttt{b92c} = \texttt{46d3} \end{aligned}

For TCP, only the pseudo-header changed. The 40-byte segment still sums to 3f280, as it did in the TCP article (3504f for the fixed header plus a231 for the options). The new pseudo-header:

c633+6417+cb00+ 7150+0006+0028= 266c8\begin{aligned} & \texttt{c633} + \texttt{6417} + \texttt{cb00} \\ +\ & \texttt{7150} + \texttt{0006} + \texttt{0028} \\ =\ & \texttt{266c8} \end{aligned}

Add the segment, fold and flip:

266c8+3f280=659485948+6=594e¬ 594e=a6b1\begin{aligned} & \texttt{266c8} + \texttt{3f280} = \texttt{65948} \\ & \texttt{5948} + \texttt{6} = \texttt{594e} \\ & \lnot\,\texttt{594e} = \texttt{a6b1} \end{aligned}

That works, but it means reading the entire segment for every packet, and a full-sized segment is 1,460 bytes of data that the NAT otherwise never needs to look at. Worse, for a fragmented UDP datagram, the NAT might not even have the rest of the data when the first fragment passes through.

Fixing the checksums: the short way

Routing Basics introduced RFC 1624's incremental update, which every router uses for the TTL: for each 16-bit word that changes from m to m′,

HC′=¬(¬HC+¬m+m′)HC' = \lnot(\lnot HC + \lnot m + m')

and for several changed words, you just keep adding a ¬m and an m′ for each one. NAT changes three words of the IPv4 header: the TTL/protocol word 4006 → 3f06, and the two halves of the source address, c0a8 → c633 and 0a0a → 6417.

¬HC=¬ a56b=5a94TTL:bff9+3f06addr hi:3f57+c633addr lo:f5f5+6417sum=3b929→b92cHC′=¬ b92c=46d3\begin{aligned} \lnot HC &= \lnot\,\texttt{a56b} = \texttt{5a94} \\ \text{TTL} &: \texttt{bff9} + \texttt{3f06} \\ \text{addr hi} &: \texttt{3f57} + \texttt{c633} \\ \text{addr lo} &: \texttt{f5f5} + \texttt{6417} \\ \text{sum} &= \texttt{3b929} \to \texttt{b92c} \\ HC' &= \lnot\,\texttt{b92c} = \texttt{46d3} \end{aligned}

The TCP checksum sees only the two address words (TTL isn't in the pseudo-header):

¬HC=¬ 064a=f9b5addr hi:3f57+c633addr lo:f5f5+6417sum=3594b→594eHC′=¬ 594e=a6b1\begin{aligned} \lnot HC &= \lnot\,\texttt{064a} = \texttt{f9b5} \\ \text{addr hi} &: \texttt{3f57} + \texttt{c633} \\ \text{addr lo} &: \texttt{f5f5} + \texttt{6417} \\ \text{sum} &= \texttt{3594b} \to \texttt{594e} \\ HC' &= \lnot\,\texttt{594e} = \texttt{a6b1} \end{aligned}

Same answers, without reading a byte of the segment. Real NATs, Linux's included, do it this way, and it's why NAT can run at line rate on a cheap home router.

One delta, two checksums

There's an even simpler way to see it. The two address words summed to c0a8 + 0a0a = cab2 before, and to c633 + 6417 = 12a4a, which folds to 2a4b, after. In ones'-complement arithmetic that's a rise of 5f98. A checksum is the complement of a sum, so when the sum rises by 5f98, the checksum falls by 5f98, in both headers:

  • IPv4: a56b − 5f98 = 45d3, then +0100 for the TTL = 46d3.
  • TCP: 064a − 5f98 wraps round to a6b1.

Every packet the laptop sends through R1 gets the same 5f98 knocked off its TCP or UDP checksum, and every reply gets it added back. The Routing Basics walkthrough showed it too: its HTTP request's IPv4 checksum went 17 62 → b8 c9 at R1, which is 1762 − 5f98 + 0100. Run the formula above with ¬1762 = e89d and you get 44732 → 4736 → b8c9.

The reply comes back

The server answers with its SYN-ACK: sequence number 3558738487 (d4 1e 0a 37), acknowledging 1798279621 (6b 2f 91 c5), window 65,160, and the same four options. It leaves the server with TTL 64 and arrives at R1 with 61, after R4, R3 and R2. As it arrives on eth1, and as R1 sends it on to the laptop:

The SYN-ACK at R1: in on eth1, out on eth0.10

in   45 00 00 3c 00 00 40 00 3d 06 d7 20 cb 00 71 50 c6 33 64 17
     00 50 b8 1a d4 1e 0a 37 6b 2f 91 c5 a0 12 fe 88 da 82 00 00
out  45 00 00 3c 00 00 40 00 3c 06 37 b9 cb 00 71 50 c0 a8 0a 0a
     00 50 b8 1a d4 1e 0a 37 6b 2f 91 c5 a0 12 fe 88 3a 1b 00 00

The first 40 bytes of each: the IPv4 header and the fixed TCP header. The 20 bytes of options that follow (02 04 05 b4 04 02 08 0a 9b 2e 4f 01 0c 4a 7e 19 01 03 03 07, echoing the laptop's TSval 0c 4a 7e 19) pass through untouched.

This time it's the destination that changes, c6 33 64 17 → c0 a8 0a 0a, so the sum falls by 5f98 and both checksums rise by it: TCP da82 + 5f98 = 13a1a, which folds to 3a1b. The IPv4 checksum gets the same 5f98 plus 0100 for the TTL, d720 → 37b9. The laptop's kernel checks the SYN-ACK against its own addresses and finds everything in order. As far as the laptop knows, it's talking directly to 203.0.113.80.

Examples from the article

The packet

R1's table before this packet

Tick an entry to put it in the table. A new conversation can't have an outside port (or identifier) whose reply would look exactly like an existing entry's.

Outbound


    


    

Inbound


      


    

The checksums, two ways

Full recompute

RFC 1624: only the changed words

When Two Devices Pick the Same Port

Keeping the inside port, as R1 did, is called port preservation, and most NATs try it first. It makes life easier for applications and for anyone reading logs. But it can't always work.

Suppose the desktop, 192.168.10.40, also running Linux, opens a connection to the same web server a moment later, and its kernel happens to pick the same ephemeral port, 47130. (With about 28,000 ports to choose from that's unlikely for any two given connections, but a busy house makes thousands of connections a day. And some programs use fixed source ports: two game consoles in one house both talking from UDP 3074 to the same game server is a classic.) If R1 preserved the port again, it would create this:

Inside Outside Remote
192.168.10.10:47130 198.51.100.23:47130 203.0.113.80:80
192.168.10.40:47130 198.51.100.23:47130 ✗ 203.0.113.80:80

Both outside five-tuples are identical. When the server replies to 198.51.100.23:47130, R1 would have no way to know which device it's for. So R1 must pick a different outside port for the desktop. It chooses 38511 (96 6f), and the second entry becomes 192.168.10.40:47130 ↔ 198.51.100.23:38511. The server sees two connections from the same address on two different ports, which is perfectly ordinary.

The desktop's SYN through R1, first 40 bytes:

The desktop's SYN at R1, remapped

in   45 00 00 3c 5c 21 40 00 40 06 d7 79 c0 a8 0a 28 cb 00 71 50
     b8 1a 00 50 2d 9a 6e 13 00 00 00 00 a0 02 fa f0 98 04 00 00
out  45 00 00 3c 5c 21 40 00 3f 06 78 ff c6 33 64 17 cb 00 71 50
     96 6f 00 50 2d 9a 6e 13 00 00 00 00 a0 02 fa f0 5a 35 00 00

Options (unchanged): 02 04 05 b4 04 02 08 0a 3e 8f 1b 42 00 00 00 00 01 03 03 07. Source address 192.168.10.40 → 198.51.100.23, source port 47130 → 38511, TTL 64 → 63.

Now the TCP checksum changes for both reasons, and the incremental update simply has three words to account for instead of two:

¬HC=¬ 9804=67fbaddr hi:3f57+c633addr lo:f5d7+6417port:47e5+966fsum=3a5c7→a5caHC′=¬ a5ca=5a35\begin{aligned} \lnot HC &= \lnot\,\texttt{9804} = \texttt{67fb} \\ \text{addr hi} &: \texttt{3f57} + \texttt{c633} \\ \text{addr lo} &: \texttt{f5d7} + \texttt{6417} \\ \text{port} &: \texttt{47e5} + \texttt{966f} \\ \text{sum} &= \texttt{3a5c7} \to \texttt{a5ca} \\ HC' &= \lnot\,\texttt{a5ca} = \texttt{5a35} \end{aligned}

The IPv4 checksum doesn't care about ports: d779 → 78ff, from the TTL and the address alone.

How R1 picks a port

Linux, which runs most home routers, makes the choice in a few steps:

  1. Reuse an existing mapping for this inside address and port

    If 192.168.10.10:47130 already has an outside address and port for some other conversation, use the same one again, if that doesn't clash.

  2. Otherwise, keep the port

    Try the inside port unchanged. The test is whether the reply five-tuple is already taken: a reply from 203.0.113.80:80 to 198.51.100.23:47130. For the laptop it wasn't; for the desktop it was.

  3. Otherwise, search from a random starting point

    Pick a random offset into the allowed range and walk forward until a port gives a unique reply tuple. The range depends on the original port: 1–511 for ports below 512, 600–1023 for 512–1023, and 1024–65535 for everything else, so a privileged port stays privileged.

Notice what Linux checks: the whole reply five-tuple, not just the port. So the desktop could have kept 47130 if it had been talking to a different server, or even to port 443 on the same one. One outside port can carry many conversations at once, as long as their remote ends differ. That's how a single address can hold far more than 65,536 connections.

Other NATs use other strategies: some always allocate sequentially, some always randomly (which makes ports harder for an attacker to guess), some keep port parity (an even inside port gets an even outside port, which RFC 4787 recommends for the benefit of RTP and RTCP), and carrier-grade NATs hand out ports in fixed blocks per customer, as we'll see later. The one thing a NAT must never do, says RFC 4787, is "port overloading": preserving the port even when it collides, so that two devices share a mapping and replies go to the wrong one.

How Long R1 Remembers

Every entry in the table costs memory, and a home router may have room for a few thousand. Entries have to be thrown away when their conversation is over. The trouble is knowing when that is.

TCP: watch the flags

For TCP, R1 can follow the connection's life, because the state machine is written in the flags. Linux's connection tracker, conntrack, keeps its own copy of the state for every connection: it sees the SYN go out, the SYN-ACK come back, the FINs and the final ACK, or a RST. Each state has its own idle timeout:

conntrack state Entered when R1 sees Linux timeout
SYN_SENT the SYN go out 120 s
SYN_RECV the SYN-ACK come back 60 s
ESTAB­LISHED the hand­shake's final ACK 5 days
FIN_WAIT a FIN in one direction 120 s
TIME_WAIT both FINs, and the last ACK 120 s
CLOSE a RST 10 s

So R1 knows exactly when a TCP connection begins and ends, and only an idle established connection needs a timer at all. RFC 5382 (2008) says that timer must be at least 2 hours 4 minutes: two hours because TCP keepalives, when enabled, default to one every two hours (RFC 1122), so a NAT that waits slightly longer will always see one; four minutes for packets still in flight. Linux's five days comfortably exceeds it. Plenty of other NATs, including some carrier-grade ones and cloud load balancers, are far less patient, which is why long-lived connections like SSH sessions or BGP peerings send their own keepalives well inside an hour.

If an entry does vanish while both ends think the connection is alive, the next packet from outside matches nothing and is dropped, and the next one from inside creates a fresh entry that may well get a different outside port, which the server has never heard of. Either way, the connection hangs until a retransmission timer gives up or a RST cuts it off.

UDP: guess

UDP has no flags, so as the UDP article explained, R1 can only guess: an entry is created by the first datagram out, refreshed by every datagram after it, and deleted after a period of silence. RFC 4787's floor is two minutes and its recommendation five; Linux uses 30 seconds for a flow that's only been seen one way and 120 seconds once it has seen replies. Two more details from RFC 4787 matter here:

  • Outbound packets must refresh the timer. Inbound ones may, but needn't. That way the inside device decides whether the mapping lives, not a stranger who keeps sending packets.
  • ICMP must not kill a mapping. A port unreachable or a time exceeded for one datagram doesn't mean the conversation is over.

ICMP queries: the identifier is the port

A ping has no ports either. An ICMP echo request carries a 16-bit identifier and a sequence number, and the reply echoes both. So NAPT treats the identifier exactly like a port: the laptop's ping to the server, identifier 4d2a, becomes an entry like icmp 192.168.10.10 id 4d2a ↔ 198.51.100.23 id 4d2a, and if another device is already using 4d2a towards the same server, R1 picks a new identifier and translates it back in the reply. RFC 5508 asks that these entries last at least 60 seconds; Linux's default is 30.

There's a neat consequence for the checksums. The ICMP checksum covers only the ICMP message, with no pseudo-header, so rewriting the address doesn't touch it. Take an 84-byte echo request from the laptop, IPv4 identification 7b 1d, with 56 bytes of data counting 00 01 02 … 37:

An echo request at R1: the IPv4 and ICMP headers

in   45 00 00 54 7b 1d 40 00 40 01 b8 88 c0 a8 0a 0a cb 00 71 50
     08 00 b3 c1 4d 2a 00 01
out  45 00 00 54 7b 1d 40 00 3f 01 59 f0 c6 33 64 17 cb 00 71 50
     08 00 b3 c1 4d 2a 00 01

Type 8 (echo request), code 0, checksum b3 c1, identifier 4d 2a, sequence 1. The IPv4 checksum changes; the ICMP one doesn't.

The IPv4 checksum changed, b8 88 → 59 f0, but the ICMP checksum, b3 c1, went through untouched. Only if R1 has to change the identifier, say to 9c41, does the ICMP checksum change too: b3c1 → 64aa.

ICMP errors: look inside

Errors are the subtle case. When something goes wrong with a packet the laptop sent, the ICMP error doesn't come from the server the laptop was talking to, and it isn't a reply on any port. It comes from whoever noticed the problem, addressed to 198.51.100.23, and it carries a quote: the IP header of the offending packet plus at least the first 8 bytes after it, which is exactly enough for the ports. The UDP article promised to explain how R1 copes, and traceroute depends on it:

  1. An error arrives for R1's public address

    Say the laptop's traceroute probe, UDP from 198.51.100.23 after translation, expires at R2. R2 sends ICMP Time Exceeded (type 11) from 198.51.100.1 to 198.51.100.23. The outer header alone doesn't match any entry: R1 has never sent anything to 198.51.100.1.

  2. R1 reads the quote

    Inside the ICMP message is the probe's own IP and UDP header: 198.51.100.23:sport → 203.0.113.80:33434. R1 looks that up as if it were an outbound packet, and finds the laptop's entry. Linux marks such a packet as RELATED to the connection.

  3. R1 rewrites both layers

    The outer destination becomes 192.168.10.10. The quoted source address and port are reverted to the laptop's, the quoted IPv4 checksum is fixed, and so is the ICMP checksum, which covers the quote. RFC 5508 requires the rewrite, and requires that processing the error doesn't refresh or delete the entry.

  4. The laptop recognises its own packet

    The laptop's kernel sees a quote of a packet it really sent, from its own address and port, and hands the error to the right socket. Traceroute prints R2's address; a connected UDP socket gets ECONNREFUSED; TCP's path MTU discovery learns that its packets are too big.

A NAT that skips this step makes errors vanish. Traceroute shows nothing but stars past the first hop, and, worse, "fragmentation needed" messages never arrive, so connections whose path has a smaller MTU stall the moment they send a full-sized segment: a PMTU black hole.

Mapping and Filtering: How NATs Differ

So far, "R1 creates an entry and accepts replies" sounds like one well-defined behaviour. It isn't. NATs differ in two independent ways, and the differences decide whether two devices behind NATs can ever talk directly. RFC 4787 (2007) gave them precise names.

Mapping: when does the outside port change?

Suppose the laptop sends UDP from one socket, 192.168.10.10:61002, first to a server S1 and then to a different server S2. Does R1 use the same outside port for both?

Endpoint-independent mapping Address-and-port-dependent Laptop …10.10:61002 R1 S1 …113.53:3478 S2 …100.77:50500 …23:61002 …23:61002 Laptop …10.10:61002 R1 S1 …113.53:3478 S2 …100.77:50500 …23:61002 …23:40917 One mapping for every destination: what S1 saw is what S2 will see. A new mapping per destination: what S1 saw is useless to S2.

RFC 4787 names three mapping behaviours:

  • Endpoint-independent mapping (EIM): one inside address and port gets one outside address and port, whoever it's talking to. RFC 4787 makes this a must for UDP, and RFC 5382 for TCP.
  • Address-dependent mapping: the same mapping is reused for every port on one remote address, but a new remote address gets a new mapping.
  • Address-and-port-dependent mapping: every distinct remote address and port gets its own mapping.

Linux behaves endpoint-independently in the common case, thanks to step 1 and step 2 of its port choice above: it reuses an existing mapping for the same inside socket, and keeps the port when it can. Only when there's a collision does a new destination get a different port.

Filtering: who may send packets in?

The second question is which inbound packets an existing mapping accepts. Once the laptop has sent from 198.51.100.23:61002 to S1:

  • Endpoint-independent filtering: anyone, from any address and port, can now send to 198.51.100.23:61002 and reach the laptop.
  • Address-dependent filtering: only hosts the laptop has sent to, on any of their ports.
  • Address-and-port-dependent filtering: only the exact address and port the laptop sent to. This is what Linux's conntrack does by default, because an inbound packet that doesn't match an existing connection's reply tuple simply isn't a reply.

RFC 4787 recommends endpoint-independent filtering where application transparency matters most, and address-dependent filtering where security matters more. Mapping and filtering are independent: Linux, typically, is EIM with address-and-port-dependent filtering.

Cones and symmetric NATs

You'll still see an older vocabulary everywhere, from game consoles reporting "NAT type: strict" to router settings pages. It comes from RFC 3489 (2003), the original STUN, which sorted NATs into four types:

RFC 3489 name RFC 4787 behaviour
Full cone Independent mapping, independent filtering
Restricted cone Independent mapping, address-dependent filtering
Port-restricted cone Independent mapping, address-and-port-dependent filtering
Symmetric Address-and-port-dependent mapping and filtering

The trouble was that real NATs didn't stay in one box. A NAT might preserve ports until a collision, then switch behaviour; another might be address-dependent in mapping, a combination the four names have no word for; a third might change with load or time. RFC 4787 says the cone terminology "has proven inadequate at describing real-life NAT behavior", and its replacement, STUN's 2008 rewrite (RFC 5389), dropped NAT classification altogether, noting that "many NATs did not fit cleanly into the types defined there". The two axes, mapping and filtering, are what you need to reason about.

Hairpinning

One more behaviour. Suppose the desktop knows the laptop only by its outside address and port, 198.51.100.23:61002, perhaps because a game server told it so, and sends a packet there. The packet goes to R1, its gateway; R1 sees a destination that is its own public address, finds the laptop's mapping, and must turn the packet straight back into the LAN. That U-turn is hairpinning (or "NAT loopback"). RFC 4787 and RFC 5382 require it, and require that the laptop sees the packet coming from the desktop's outside address and port, so both ends see consistent addresses. Plenty of cheap NATs still get it wrong, and it matters most when thousands of customers share one carrier-grade NAT.

Letting Connections In

The table only fills from the inside. If you want the NAS, 192.168.10.30, to serve its web interface to the outside world, you have to put an entry in by hand.

Port forwarding

A port forward is a static rule: "TCP arriving on the WAN for port 8443 goes to 192.168.10.30:443." Technically it's destination NAT (DNAT), the mirror image of what we've seen: R1 rewrites the destination of an inbound packet, and conntrack records the connection so that the NAS's replies have their source rewritten back to 198.51.100.23:8443.

  1. A friend connects

    A friend at 198.51.100.77 opens https://198.51.100.23:8443/. The SYN arrives at R1 for 198.51.100.23:8443.

  2. DNAT, before routing

    The rule matches, so R1 rewrites the destination to 192.168.10.30:443 and creates a conntrack entry. Only now does it look up the route, which sends the packet out of eth0.10.

  3. Replies are un-DNATed

    The NAS answers 198.51.100.77 from 192.168.10.30:443. R1 matches the entry and rewrites the source to 198.51.100.23:8443, so the friend sees replies from exactly the address they connected to.

Port forwarding has a hairpinning trap of its own. If the laptop tries 198.51.100.23:8443, R1 DNATs it to the NAS as before. But the NAS sees the laptop's private address as the source, and both are on VLAN 10, so it replies to 192.168.10.10 directly, without passing through R1. The laptop receives a SYN-ACK from 192.168.10.30:443 when it was expecting one from 198.51.100.23:8443, and its kernel answers with a RST. The fix is for R1 to also rewrite the source of hairpinned connections to its own LAN address, so the NAS's replies come back through R1. The rule set at the end of this page does exactly that. (The other common fix is split DNS: give inside devices the NAS's private address for the same name.)

The DMZ host

Many home routers offer a "DMZ" setting: one inside device that receives every unsolicited inbound packet, on every port. The name is borrowed from firewall design, where a demilitarised zone is a separate, isolated network for public servers. The home-router version is nothing of the sort: it's one ordinary device on your LAN, fully exposed, with an unrestricted path to everything else in the house. It's sometimes used to make a game console "open"; a few specific port forwards nearly always do the job with far less exposure.

Asking the router: UPnP, NAT-PMP and PCP

Typing in port forwards doesn't suit software that needs a port for a few minutes, like a game hosting a match or a peer-to-peer app. So protocols appeared that let devices ask the router themselves:

  • UPnP IGD (Internet Gateway Device), from the UPnP Forum around 2001. A device finds the router with SSDP multicast on 239.255.255.250:1900 (the UDP article listed it), then sends it an AddPortMapping request over HTTP and SOAP.
  • NAT-PMP, designed by Apple and published as RFC 6886 in 2013: a small binary request to the gateway on UDP port 5351, with a lifetime the device must keep renewing.
  • PCP, the Port Control Protocol (RFC 6887, April 2013), NAT-PMP's standardised successor on the same port. It also works with IPv6 firewalls and can, in principle, ask an ISP's carrier-grade NAT for a mapping.

These protocols have a poor security record, and UPnP's is the worst. Classic UPnP IGD has no authentication at all: any program on any device in the house, including malware or a compromised smart plug, can ask the router to open any port to any inside address, and the router obliges without asking you. Worse, some routers have shipped with the UPnP control service reachable from the Internet side. In 2018 Akamai found tens of thousands of such routers whose NAT tables had been injected with mappings by attackers, turning them into proxies for other traffic, and in some cases into open doors to Windows file-sharing ports on machines inside. The usual advice for home networks is to leave UPnP off unless something specific needs it, and if your router supports PCP or NAT-PMP, prefer those.

NAT Traversal: Getting Two NATs to Talk

Now the hard problem. The laptop wants a video call with a friend, Peer B, whose machine at 192.168.1.20 sits behind their home NAT, with public address 198.51.100.77. Neither can reach the other: each NAT drops unsolicited packets, and neither peer even knows its own public address and port. Relaying everything through a server would work, but it costs the server bandwidth and adds latency. Can they get a direct path?

Usually, yes, and UDP makes it surprisingly easy. The UDP article promised STUN on port 3478 and hole punching; here they are.

STUN: "what do I look like from outside?"

STUN, Session Traversal Utilities for NAT (RFC 8489, 2020, after RFC 5389 and the original RFC 3489), is a simple request and response, normally on UDP port 3478. The laptop sends a Binding request from the very socket it will use for the call, 192.168.10.10:61002, to a STUN server at 203.0.113.53:3478. R1 maps it to 198.51.100.23:61002, and the server replies with what it saw, in an attribute called XOR-MAPPED-ADDRESS.

Why the address is XORed

The server doesn't send c6 33 64 17 and port ee 4a (61002) as they are. It XORs the port with 21 12 and the address with 21 12 a4 42, STUN's fixed "magic cookie", which also sits in every STUN header:

port     ee 4a  XOR  21 12        = cf 58
address  c6 33 64 17  XOR  21 12 a4 42  = e7 21 c0 55

The laptop XORs them back. The reason is a story about NAT itself: the original STUN sent the address in the clear, and some NATs, trying to be helpful, spotted their own public address in the payload and "fixed" it to the private one, a misguided generic ALG. RFC 8489 says so explicitly. Scrambling the bytes keeps middleboxes' hands off.

Now the laptop knows its server-reflexive address, 198.51.100.23:61002. Thanks to endpoint-independent mapping, that's what any host on the Internet will see, as long as the laptop keeps using the same socket. Peer B does the same and learns 198.51.100.77:50500.

Hole punching

The two peers swap their addresses through some server they can both already reach: the signalling channel, often a WebSocket to the video-call service. Then both start sending UDP to each other at once:

Peer A (laptop) 192.168.10.10:61002 R1 (NAT A) 198.51.100.23 STUN server 203.0.113.53:3478 NAT B 198.51.100.77 Peer B 192.168.1.20:50500 ① Binding request you are 198.51.100.23:61002 ② Binding request you are 198.51.100.77:50500 ③ swap addresses via the signalling server ④ A → 198.51.100.77:50500 ✕ R1 now expects …77:50500 dropped: unsolicited ⑤ B → 198.51.100.23:61002 matches ④'s entry: in NAT B now expects …23:61002 ⑥ every packet now gets through, both ways Each peer's first outgoing packet is what opens its own NAT for the other's.
  1. A's first packet opens R1, and dies at NAT B

    The laptop sends to 198.51.100.77:50500 from the same socket. R1 reuses the mapping 198.51.100.23:61002 (endpoint-independent) and now accepts packets from 198.51.100.77:50500 on it. At NAT B the packet is unsolicited: B hasn't sent anything to the laptop yet, so it's dropped.

  2. B's packet finds a hole waiting

    B sends to 198.51.100.23:61002. NAT B maps it to 198.51.100.77:50500, and starts accepting from …23:61002. At R1, it matches exactly what the laptop sent to a moment ago, so it's a "reply", and it goes in.

  3. Both holes are open

    From now on, packets in either direction match an entry at both NATs. The peers have a direct UDP path, and they keep it alive with a packet every few seconds, well inside even the shortest UDP timeout.

Hole punching works because neither NAT is being tricked: each one sees its own device send first, exactly as for any outbound conversation. That's also why it doesn't weaken anything; a peer can only get in by being the one the inside device chose to talk to.

When it fails

The key ingredient was endpoint-independent mapping. The laptop told B to send to …23:61002 because that's what STUN saw. If R1 were address-and-port-dependent, its packets to B would leave from some other port, and B would be aiming at the wrong hole. Filtering matters less: whichever side's first packet is dropped, the other side's packet gets through. With R1 as A's NAT, here's how the combinations work out (APDM is address-and-port-dependent mapping, RFC 3489's "symmetric" NAT):

A's NAT B's NAT Direct path?
EIM, any filtering EIM, any filtering Yes
APDM EIM, address-dependent filtering Yes: once B has sent to A's address, B's filter accepts A from any port, and B learns A's real port from the first packet that arrives
APDM EIM, address-and-port-dependent filtering No: B only accepts the port STUN saw, and A never uses it
APDM APDM No, short of guessing ports

Measurements back this up. When Bryan Ford, Pyda Srisuresh and Dan Kegel tested deployed NATs for their 2005 USENIX paper on hole punching, about 82% supported it for UDP. When only one side's NAT is "hard" (address-and-port-dependent), there's still guessing: that side opens a few hundred sockets, the other probes a few hundred random ports, and the birthday paradox makes a match likely surprisingly quickly. Tailscale's well-known write-up on NAT traversal walks through exactly this trick. With two hard NATs every probe also leaves from an unpredictable port, the odds collapse, and only a relay will do.

TCP is harder

The same trick for TCP needs both peers to send a SYN to each other at the same moment, a simultaneous open, which the TCP article noted is legal but almost never happens on purpose. It's fragile: if one SYN arrives before the other side's NAT has seen its own outbound SYN, that NAT may answer with a RST or an ICMP error and kill the attempt (RFC 5382 asks NATs to wait at least 6 seconds before reacting to an unsolicited SYN, partly for this reason), and operating systems make it awkward to connect from a port you're also listening on. Ford, Srisuresh and Kegel found about 64% of NATs supported TCP hole punching. That's one more reason modern peer-to-peer systems run everything over UDP, with QUIC or their own reliability layer on top.

TURN: when all else fails, relay

For the remaining cases there's TURN, Traversal Using Relays around NAT (RFC 8656, 2020). The peer asks a TURN server, usually on the same port 3478, for a relayed address on the server itself, and everything is forwarded through it. It always works, as long as the peer can reach the TURN server at all, but it costs the operator bandwidth and adds a detour, so it's the last resort.

ICE: try everything, keep the best

Real applications don't decide in advance which technique to use. ICE, Interactive Connectivity Establishment (RFC 8445, 2018), gathers every possible address, called candidates, and tests them all:

  1. Gather

    Host candidates (the device's own addresses, like 192.168.10.10:61002 and its IPv6 address), server-reflexive candidates from STUN (198.51.100.23:61002), and relayed candidates from TURN.

  2. Exchange

    Send them to the peer over the signalling channel, and receive the peer's.

  3. Check

    Pair every local candidate with every remote one and send STUN Binding requests along each pair, highest priority first. These checks are the hole punching. A check that arrives from an address nobody listed reveals a peer-reflexive candidate: exactly what happens in the second row of the table above.

  4. Nominate

    One side, the controlling agent, picks a working pair, and the media flows over it.

Priority favours the most direct path. Each candidate's priority is

priority=224⋅type+28⋅local+(256−component)\begin{aligned} \text{priority} = {} & 2^{24} \cdot \text{type} \\ & + 2^{8} \cdot \text{local} \\ & + (256 - \text{component}) \end{aligned}

with recommended type preferences of 126 for host, 110 for peer-reflexive, 100 for server-reflexive and 0 for relayed. A relay is only used when nothing else works. Two devices on the same LAN find each other's host candidates and never touch R1 at all.

ICE is what WebRTC uses in every browser, so any video call in a web page goes through exactly these steps. Games, voice apps and mesh VPNs do the same with their own variations. Tailscale, for example, uses STUN-style probing and hole punching for direct WireGuard connections, with its own relays (DERP) as the fallback, and keeps mappings alive with WireGuard's keepalive, for which 25 seconds is the usual setting behind NAT.

Devices in the house open connections, pings and UDP flows through R1. Each bar is one entry in R1's table, from the packet that created it until its timer runs out. Bold amber labels are entries whose port R1 had to change. Click the chart to jump to a moment. Timeouts run from seconds to days, so the Auto speed plays busy moments in real time and skips each quiet stretch in about a second.

R1's table at this moment

Every packet so far

What NAT Breaks

NAT works so well for browsing that it's easy to forget it's a hack. Every problem below comes from the same source: something, somewhere, assumed that an IP address names one machine and means the same thing everywhere.

The end-to-end principle

The Internet was designed around the end-to-end principle: the network just moves packets, any host can send to any other, and the intelligence lives in the hosts. NAT breaks the "any host to any other" part. Devices behind a NAT are second-class citizens: they can make calls but not receive them, so every new protocol that wants to receive (voice, games, file sharing, home servers) needs one of the workarounds above. RFC 2993 (2000), "Architectural Implications of NAT", catalogued the damage at length. It also broke a deeper assumption: that the address in the IP header is the address the application sees.

Protocols that carry addresses inside

Some protocols write IP addresses and ports into their payload, and NAT only rewrites headers. Classic FTP in active mode is the textbook case. The client opens a control connection to the server's port 21, then tells the server where to connect back for the data with a PORT command: four address bytes and two port bytes, in decimal:

FTP's PORT command, through a NAT

PORT 192,168,10,10,195,80      laptop: "connect to me at 192.168.10.10:50000"

195 × 256 + 80 = 50000. The server dutifully tries to connect to 192.168.10.10, a private address that leads nowhere from where it sits.

The traditional fix is an ALG, an application layer gateway: a piece of the NAT that understands FTP, spots the PORT command, rewrites it to PORT 198,51,100,23,195,80, and creates a mapping so the server's incoming data connection gets through. Here the two addresses happen to be the same length in decimal, 13 characters each. When they aren't, the ALG changes the length of the TCP stream, and from then on it has to shift the sequence numbers of every later segment in that direction, and the acknowledgment numbers coming back, for the rest of the connection. (FTP's passive mode, and EPSV from RFC 2428, avoid the problem by having the client make both connections.)

SIP, the signalling protocol for most voice-over-IP, is worse: addresses appear in several headers and in the SDP body that says where to send the audio. SIP ALGs exist in many routers and are notorious for mangling calls; VoIP providers routinely tell customers to turn them off and rely on STUN and ICE instead. RFC 4787 says ALGs for UDP protocols should be off by default, and modern Linux no longer attaches its FTP and SIP helpers automatically: you have to ask for them.

ALGs have also been abused. In 2020 Samy Kamkar showed NAT Slipstreaming: a web page could make a browser send a request that the router's SIP ALG misread as SIP signalling (a REGISTER), tricking the router into opening an inbound port to the victim's machine. Browsers responded by blocking connections to the SIP ports 5060 and 5061, and to further ports after a follow-up variant in 2021. It's another argument for leaving ALGs off.

IPsec

IPsec's AH (Authentication Header, RFC 4302) authenticates the IP header's addresses, by design. A NAT that rewrites the source address makes every packet fail verification: AH and NAT simply can't coexist. ESP encrypts the TCP or UDP header, so a NAT can't see the ports it would need to tell connections apart, or fix the inner checksum. The fix is NAT traversal: IKE detects that a NAT is in the path (RFC 3947) and both ends wrap ESP inside UDP on port 4500 (RFC 3948), giving the NAT a port to work with. Every IPsec VPN client does this today, mostly without anyone noticing.

Servers at home

Running a server behind NAT means port forwarding, and port forwarding means one inside device per outside port. Two web servers can't both have port 443 on 198.51.100.23; the second has to live on 8443 or behind a reverse proxy. The outside address may change whenever the DHCP lease does, which is why dynamic DNS services exist. And behind a carrier-grade NAT, as we'll see next, you can't forward ports at all.

Logs and attribution

To the web server, everything from our house is 198.51.100.23. If one device misbehaves, the server can only block the whole house, and if someone needs to find out which device sent a request, the answer is in R1's translation table, which forgot it two minutes after the flow ended. At home that's an inconvenience; at the scale of an ISP it becomes a legal and operational problem. Which brings us to the ISP.

Carrier-Grade NAT

Our ISP gave R1 a public address. Many ISPs can no longer afford to: they have more customers than IPv4 addresses. Their answer is to put a NAT in their network too, a carrier-grade NAT (CGN, or CGNAT), and give each home router an address that is only meaningful inside the ISP.

Which addresses? Not RFC 1918: the ISP has no idea which private range each customer uses at home, and if R1's WAN address were 192.168.10.5, it would collide with the house's own VLAN 10. So RFC 6598 (April 2012) set aside 100.64.0.0/10, "shared address space", for exactly this, as IPv4 Addressing mentioned. If our ISP used CGNAT, the laptop's packets would be translated twice:

Laptop 192.168.10.10 R1 (home NAT) WAN 100.72.14.9 ISP's CGN 198.51.100.240 Web server 203.0.113.80 source on the wire: after R1: after the CGN: 192.168.10.10:47130 100.72.14.9:47130 198.51.100.240:20517 private RFC 1918, home shared 100.64.0.0/10, ISP public ports 20480–21503: ours NAT444: IPv4 private → IPv4 shared → IPv4 public, two translations.

The arrangement is nicknamed NAT444, for the three IPv4 address realms the packet passes through. Nothing about R1 changes; it doesn't even know there's another NAT upstream.

Sharing ports between customers

One public address has 64,512 ports above 1023, per protocol, and a CGN shares them among many customers. Allocating ports one connection at a time would mean logging every single connection, and ISPs are often legally required to say which customer used a given address and port at a given moment. Instead, CGNs usually do port block allocation: each customer gets a block, say 1,024 ports, the first time they need one, and the CGN logs just that one event: "customer 4711 has 198.51.100.240 ports 20480–21503 from 09:14:03". With blocks of 1,024, one address serves 63 customers. RFC 7422 (2014) goes further with deterministic CGN: a fixed formula maps each inside address to its address and port range, so no per-customer events need logging at all.

That's also why RFC 6302 (2011) asks servers on the Internet to log the source port and an accurate timestamp, not just the address. Without the port, a complaint about 198.51.100.240 points at 63 households.

What CGNAT means for you

  • No inbound connections. You can't configure the ISP's CGN, so port forwarding on R1 does nothing. Hosting a game, a server or a camera feed needs a relay or a tunnel. PCP could, in principle, ask the CGN for a mapping, but few ISPs support it.
  • Hole punching depends on the CGN. RFC 6888 (2013), the requirements for CGNs, asks for "paired" pooling (a customer always appears from the same public address) and recommends endpoint-independent filtering, but many CGNs are stricter, and two customers behind the same CGN need it to hairpin.
  • Shared reputation. If a neighbour behind the same address gets it blocked or flagged, you get the CAPTCHAs too.
  • Port exhaustion. A device that opens hundreds of connections at once can run out of ports in its block, and new connections stall.

Many ISPs pair CGNAT with native IPv6, so that most traffic to big services avoids the CGN entirely. That leads to the real fix.

IPv6: The Firewall Was the Point

On IPv6 our house has a /56 from the ISP, 2001:db8:1234::/56, and VLAN 10 alone is a /64 with 264 addresses. There is nothing to share and nothing to translate. When the laptop connects from 2001:db8:1234:10:0:ff:feaa:bb01 to 2001:db8:113::80, the server sees that address (or, more likely, one of the laptop's temporary addresses), R1 just routes, and as Routing Basics showed, there are no checksums for it to fix. The IPv6 article promised the rest of the story: what NAT did, and why the firewall was always the part that mattered.

NAT is not a firewall

People often say NAT "protects" a home network. What actually protects it is the stateful rule that came bundled with it: let replies in, drop everything unsolicited. NAT and that rule happen to live in the same table, so it's easy to mix them up. They're different things:

What NAT does

Rewrites addresses and ports on packets that match a mapping, so private addresses can share a public one. A packet that matches nothing isn't translated, but translation alone says nothing about whether it's forwarded. NAT rules only decide how to rewrite; dropping is the filter chain's job.

What the firewall does

Decides what is forwarded: replies to connections that started inside (conntrack state established or related) are accepted, and new inbound connections are dropped unless a rule allows them. That works identically for IPv4 and IPv6, with or without NAT.

The difference shows at the edges. Suppose a machine on the ISP's access network sends a packet addressed straight to 192.168.10.30, the NAS, and delivers it to R1's MAC address. R1 has a connected route for 192.168.10.0/24. Nothing in the NAT table matches, so nothing is translated, and plain routing would forward it to the NAS. Only a firewall rule stops it. Such packets can't come from far away, since private addresses aren't routed across the Internet, but anything on R1's upstream segment that can reach its MAC address could send them. Meanwhile, port forwards, UPnP, DMZ hosts and hole punching are all ways to let traffic past the NAT on purpose, so "it's behind NAT" was never a security policy.

On IPv6, home routers run exactly the same stateful rule without the translation. RFC 6092 (2011) recommends it as the default for home gateways: outbound connections and their replies pass, unsolicited inbound ones don't, unless you open a port, by hand or with PCP. One extra care: IPv6 depends on ICMPv6, so the firewall must let through errors like Packet Too Big (conntrack treats them as related) and never block ICMPv6 wholesale.

The difference from NAT is that opening a port is now simple and unambiguous. Two devices can both run a web server on port 443, each on its own address, and a peer-to-peer connection between two IPv6 hosts behind stateful firewalls needs only the hole-punching step, with no STUN, because each side already knows the other's real address and port.

Translation in IPv6, when it happens

There are still places where IPv6 meets translation:

  • NPTv6 (RFC 6296, 2011, experimental) rewrites only the prefix, statelessly and one to one: inside fd00::/48-style addresses become outside global ones, with no ports involved. It's chosen to be checksum-neutral, adjusting one 16-bit word of the address so that TCP and UDP checksums don't need touching at all. Some enterprises use it to avoid renumbering when they change ISPs.
  • NAT64 with DNS64 lets IPv6-only networks reach IPv4-only servers by translating between the two protocols, as the IPv6 article described. It's a stateful NAPT, with the same table and the same port-sharing as R1's, just with an IPv6 inside.

NAT on Linux

R1, like most home routers, runs Linux. Here's everything this page has described, as an nftables rule set: masquerading for the WAN, the port forward to the NAS with its hairpin fix, and the stateful firewall that does the actual protecting, for IPv4 and IPv6 at once.

/etc/nftables.conf on R1 (the NAT and forwarding parts)

table ip nat {
    chain prerouting {
        type nat hook prerouting priority dstnat; policy accept;
        fib daddr type local tcp dport 8443 dnat to 192.168.10.30:443
    }
    chain postrouting {
        type nat hook postrouting priority srcnat; policy accept;
        oifname "eth1" masquerade
        oifname "eth0.10" ip saddr 192.168.10.0/24 ct status dnat masquerade
    }
}
table inet filter {
    chain forward {
        type filter hook forward priority filter; policy drop;
        ct state established,related accept
        ct state invalid drop
        iifname { "eth0.10", "eth0.20", "eth0.30" } oifname "eth1" accept
        ct status dnat accept
    }
}

fib daddr type local matches packets addressed to any of R1's own addresses, so the port forward works from inside the house too, without naming the WAN address. masquerade means "source NAT to whatever address eth1 has right now", and Linux forgets all the mappings if that address goes away: just right for a WAN address from DHCP. With a fixed address you'd write snat to 198.51.100.23. The second masquerade line is the hairpin fix: port-forwarded connections from VLAN 10 back into VLAN 10 get R1's LAN address as their source. The forward chain's policy drop is the firewall; it applies to IPv6 too, because the inet table covers both. (A real configuration would also keep the VLANs apart from each other and enable net.ipv4.ip_forward.)

The older iptables spelling of the first two rules is still everywhere in tutorials:

iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE
iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 8443 \
         -j DNAT --to-destination 192.168.10.30:443

Reading the table

The conntrack tool, from conntrack-tools, lists every tracked connection. Here's R1 shortly after the laptop and desktop connected, with the laptop's QUIC flow from the UDP article and its ping (each entry is one long line; they're wrapped here):

conntrack -L on R1

tcp      6 431998 ESTABLISHED
         src=192.168.10.10 dst=203.0.113.80 sport=47130 dport=80
         src=203.0.113.80 dst=198.51.100.23 sport=80 dport=47130
         [ASSURED] mark=0 use=1
tcp      6 431996 ESTABLISHED
         src=192.168.10.40 dst=203.0.113.80 sport=47130 dport=80
         src=203.0.113.80 dst=198.51.100.23 sport=80 dport=38511
         [ASSURED] mark=0 use=1
udp      17 117
         src=192.168.10.10 dst=203.0.113.80 sport=52114 dport=443
         src=203.0.113.80 dst=198.51.100.23 sport=443 dport=52114
         [ASSURED] mark=0 use=1
icmp     1 27
         src=192.168.10.10 dst=203.0.113.80 type=8 code=0 id=19754
         src=203.0.113.80 dst=198.51.100.23 type=0 code=0 id=19754
         mark=0 use=1
conntrack v1.4.8 (conntrack-tools): 4 flow entries have been shown.

Each entry has the protocol name and number, the seconds left before it expires, the TCP state, and then two tuples. The first is the original direction, exactly as the inside device sent it. The second is the reply direction, exactly as R1 expects the replies to arrive. NAT is the difference between them: in the first entry the reply goes to 198.51.100.23, not 192.168.10.10, so R1 is translating the source. In the second, the reply port is 38511, not 47130: that's the desktop's remapped port. [ASSURED] means traffic has been seen both ways, so the entry won't be the first evicted if the table fills. The ICMP entry's id=19754 is our identifier 4d2a in decimal.

A few other places worth looking:

  • conntrack -L -p tcp --dport 47130 filters; conntrack -E prints events as entries are created, updated and destroyed, which is the clearest way to watch NAT happen live.
  • sysctl net.netfilter.nf_conntrack_count and nf_conntrack_max show how full the table is. A full table drops new connections, and the kernel log says "nf_conntrack: table full, dropping packet".
  • From inside the house, curl https://ifconfig.me (or any "what's my IP" service) shows the outside address the world sees. If it doesn't match R1's WAN address, there's another NAT upstream; if R1's WAN address is in 100.64.0.0/10, you already know which kind.

Where to Go Next

  • DNS: the next article. R1 also answers the laptop's name lookups as a forwarder, and the answer is where 203.0.113.80 came from in the first place.
  • TCP: the SYN we translated, the state machine conntrack follows, and why keepalives matter for long idle connections.
  • UDP: pseudo-state and timeouts from the other side, and the port unreachable whose translation we followed.
  • Routing Basics: the hop-by-hop walk where NAT first appeared, RFC 1624, and traceroute.
  • IPv6: the address space that makes NAT unnecessary, and NAT64 for reaching what's left of IPv4.
  • IPv4 Addressing: RFC 1918, 100.64.0.0/10 and the story of running out.
  • DHCP: how R1 got 198.51.100.23 in the first place.

Key Takeaways

  • NAT lets private RFC 1918 addresses share public ones. RFC 1631 (May 1994) called it a short-term fix; RFC 2663 and RFC 3022 define basic NAT (addresses only) and NAPT (addresses and ports), which is what home routers do. Linux calls it masquerading.
  • R1 keeps a translation table pairing an inside five-tuple with an outside one. Outbound packets create entries and get their source rewritten; inbound packets can only match existing entries and get their destination rewritten back. Unsolicited inbound packets have nowhere to go.
  • Changing an address changes the TCP/UDP checksum too, through the pseudo-header. The laptop's SYN at R1: IPv4 checksum a5 6b → 46 d3, TCP 06 4a → a6 b1. RFC 1624's HC′ = ¬(¬HC + ¬m + m′), applied per changed word, gets there without reading the payload; here the address change is a ones'-complement delta of 5f98 on both.
  • NATs try to preserve the port. If the outside five-tuple would collide, they pick another: the desktop's 47130 became 38511 (TCP checksum 98 04 → 5a 35). Linux only needs the reply tuple to be unique, and searches from a random offset in 1024–65535.
  • TCP entries follow the flags; RFC 5382 asks for at least 2 h 4 min for idle established connections (Linux: 5 days). UDP entries live on timers (RFC 4787: at least 2 min, 5 recommended; Linux 30/120 s). ICMP echo identifiers are translated like ports (RFC 5508: at least 60 s), and ICMP errors are matched and translated by the packet quoted inside them.
  • RFC 4787 describes NATs by mapping (endpoint-independent, address-dependent, address-and-port-dependent) and filtering (the same three). RFC 3489's full cone, restricted, port-restricted and symmetric are combinations of these that real NATs didn't stick to. NATs must support hairpinning.
  • Inbound access needs port forwarding (DNAT), a DMZ host, or UPnP IGD, NAT-PMP or PCP (RFC 6887, UDP 5351). UPnP has no authentication and a long history of abuse.
  • STUN (RFC 8489, port 3478) tells a device its outside address, XORed with the magic cookie 2112a442 so ALGs leave it alone. UDP hole punching works when mappings are endpoint-independent; TCP needs simultaneous open and works less often. TURN (RFC 8656) relays as a last resort, and ICE (RFC 8445) tries every candidate, as in WebRTC.
  • NAT breaks end-to-end reachability, protocols that carry addresses in their payload (FTP, SIP, needing ALGs), IPsec AH (ESP needs NAT traversal over UDP 4500), home servers, and attribution in logs.
  • Carrier-grade NAT uses 100.64.0.0/10 (RFC 6598) for a second translation, NAT444, with port blocks per customer to keep logs manageable. RFC 6302 asks servers to log source ports.
  • IPv6 needs no NAT. The protection people credit to NAT comes from the stateful firewall rule beside it, which IPv6 home routers keep (RFC 6092). NPTv6 and NAT64 are the remaining kinds of IPv6 translation.

R1 now shares one address between every device in the house, and the laptop's packets reach 203.0.113.80 and find their way back. But nobody types 203.0.113.80 into a browser. When the laptop asked R1, its DNS forwarder, for a name, something had to turn that name into an address, and R1 had to ask someone else. That's DNS.