Chapters

NAT: sharing one public IP

Every home and office in this course uses private addresses, yet all of them reach kade-api. This chapter explains the swap that makes that work, its limits and side effects, and how it is done in GCP. It is a big reason IPv4 is still in use.

Addressing and local delivery · chapter 10 of 34 · 13 min read

Part AHow NAT works

The problem

IPv4 has about 4.3 billion addresses, far fewer than the number of devices online (chapter 2). The fix has two parts: reserve some ranges for private use, and let many private devices share one public address. That sharing is NAT (Network Address Translation).

The private ranges, which are never routed on the public internet:

#RangeAddressesTypical useIn the Kadé scenario
110.0.0.0/816,777,216Large networks, cloud VPCskade-vpc 10.10.0.0/16
2172.16.0.0/121,048,576Medium networks, officesKadé office 172.16.0.0/16
3192.168.0.0/1665,536Homes and small officesYour home 192.168.1.0/24

Why a private source cannot go out as it is

Suppose the laptop's packet reached kade-api with source 192.168.1.23. kade-api would reply to 192.168.1.23, and that reply could never find its way back: internet routers do not route private ranges, and millions of homes use that exact address anyway. So the source must be changed before the packet leaves the home.

The swap, out and back

The home router rewrites the source to its own public IP on the way out, and reverses the change on the way back. With the form of NAT used at home, it rewrites the source port too:

home LAN (private)internet (public)Laptop192.168.1.23Home routerdoes NATWAN 203.0.113.45kade-api34.87.120.151 · out, beforesrc 192.168.1.23:52814dst 34.87.120.15:4432 · out, aftersrc 203.0.113.45:40001dst 34.87.120.15:4433 · replydst 203.0.113.45:400014 · reply, afterdst 192.168.1.23:52814

kade-api only ever sees 203.0.113.45. It has no idea the laptop exists.

Wide by design - scroll it sideways.

What exactly is rewritten

NAT changes more than one field. Here is one packet, drawn as the chapter 1 envelopes, just before and just after the home router. Switch to the reply to see the same swap in reverse:

Before · on the home LAN

Ethernet header

dst 3c:84:6a:10:ee:01home router, LAN side

src a4:83:e7:2b:91:0claptop

IP header

src 192.168.1.23

dst 34.87.120.15

TTL 64

checksum valid

TCP header

src port 52814

dst port 443

checksum valid

Data

HTTPS, encrypted

never touched

FCS

checks this frame

Home router · NAT

  1. Writes a row in the NAT table: 192.168.1.23:52814 ↔ 203.0.113.45:40001 (section 5).
  2. Replaces the private source IP and port with its public ones.
  3. Recalculates both checksums, because the values they cover changed.

After · on the internet side (WAN)

Ethernet headerrebuilt every hop

dst 00:1f:ca:88:10:01ISP router

src 3c:84:6a:10:ee:02home router, WAN side

IP header

src 203.0.113.45

dst 34.87.120.15

TTL 63every hop

checksum recalculated

TCP header

src port 40001

dst port 443

checksum recalculated

Data

HTTPS, encrypted

never touched

FCS

new for this frame

every hop

  • value rewritten by NAT
  • every hop changed by any router, NAT or not
  • frame
  • IP
  • TCP
  • data (chapter 1)
A checksum is a small number computed from the header so the receiver can spot damage. Change any field and the checksum must be recomputed, or the packet is thrown away as corrupt.

Two details follow from this:

  • NAT only rewrites headers, never the data. Keep this in mind for section 12.
  • Ping has no ports. ICMP (the protocol behind ping) has no port numbers, so NAT uses the ping's ID number in the same way instead.

The NAT table

To send each reply to the right device, the router records every connection in a NAT table. Here the laptop has two browser tabs open to Kadé, the phone runs the Kadé app, and the TV is streaming:

DevicePrivate sidePublic sideTalking to
Laptop, tab 1192.168.1.23:52814203.0.113.45:4000134.87.120.15:443
Laptop, tab 2192.168.1.23:52815203.0.113.45:4000234.87.120.15:443
Phone, Kadé app192.168.1.40:61022203.0.113.45:4000334.87.120.15:443
Smart TV192.168.1.52:49200203.0.113.45:40004a streaming service
Three connections go to exactly the same place, kade-api on 443. After the swap they all share one public IP. Only the public port tells them apart.

Ports do the telling-apart, so this common form is called PAT (Port Address Translation), or "NAT overload". When people say NAT at home, they mean PAT.

Two more details about the table:

  • Each row is keyed by 5 values: protocol (TCP or UDP), source IP, source port, destination IP, destination port. These are the four values from chapter 1 plus the protocol. Tracking all of them is called connection tracking.
  • Port preservation. Many routers keep the original port if it is free (52814 stays 52814) and only pick a new one when two devices clash. This chapter uses 4000x to make the change easy to see.

Part BKinds and limits

Kinds of NAT

NAT is described in two ways: by how addresses are shared, and by which field it changes.

#KindMappingHow it worksWhere you see it
1Static NAT1 private ↔ 1 public, fixedOne private IP always maps to the same public IP, both ways.kade-api's external IP 34.87.120.15 ↔ 10.10.1.10
2Dynamic NAT1 ↔ 1, from a poolA device borrows a public IP from a pool while it is active. Rare today.Old enterprise networks
3PATmany ↔ 1, by portMany devices share one IP; ports tell them apart.Home and office routers, Cloud NAT

SNAT · source NAT

Changes the source of packets going out. Lets private devices reach the internet.

src 192.168.1.23 → 203.0.113.45

DNAT · destination NAT

Changes the destination of packets coming in. Lets the internet reach a private device.

dst 203.0.113.45:8443 → 192.168.1.23:3000

Everything in Part A is SNAT. Port forwarding (section 10) is DNAT. GCP's external IP for kade-api does both: DNAT for traffic coming in, SNAT for traffic going out. Load balancers also use DNAT, which comes in a later chapter.

Port limits

How many connections can share one public IP? Three steps:

  1. There are about 64,500 ports to hand out. NAT normally uses ports 1024 to 65535: 64,512 per public IP, and TCP and UDP each get their own set.
  2. A port can be used more than once. Each NAT row also records where the connection is going (section 5). So the same public port can carry two connections at once, as long as they go to different places:
Private sidePublic sideGoing to
192.168.1.23:52814laptop203.0.113.45:4000134.87.120.15:443kade-api
192.168.1.40:61022phone203.0.113.45:40001198.51.100.7:443another site
Same public port, different destinations: a reply from each one still matches exactly one row.
  1. So ports only run out toward one busy destination. Every connection to the same destination IP and port needs a different public port.

How close real setups get:

SituationConnections through one public IPOK?
Your home4 devices, a few hundred connectionsplenty of room
Kadé office20 staff × ~30 connections to kade-api = ~600plenty of room
kade-api → PayGate via Cloud NATCloud NAT gives each VM only a slice of ports. The default minimum is 64, so kade-api can hold 64 connections to PayGate:443 at once.can run out

When the ports run out, new connections fail while old ones keep working. In GCP this shows up as dropped connections with the reason OUT_OF_RESOURCES in the Cloud NAT logs. The fixes: reuse connections (HTTP keep-alive, connection pools), give each VM more ports, turn on dynamic port allocation, or add more NAT IPs.

Timeouts: when a NAT row disappears

The router cannot keep every row forever. It deletes a row when a connection closes, or when it has been idle for too long. After that, a late packet on that connection has no row and is dropped, even though both ends think the connection is still open.

no keepaliveidle 20 minutes: no packets either way✕row removedlate reply: droppedkeepalivea small packet every 5 minutes keeps the row alive051015202530 min

Green = row exists. The limit shown is 20 minutes, Cloud NAT's default for an open TCP connection.

Wide by design - scroll it sideways.

Connection typeCloud NAT default idle timeoutHome routers
TCP, open connection1,200 s (20 min)Varies a lot, from minutes to hours
TCP, opening or closing30 sShort
UDP30 sOften 30 s to a few minutes
ICMP (ping)30 sShort

Part CGetting in from outside

Outbound is easy, inbound is hard

A reply always matches a row, because the connection was started from inside. A request that starts on the internet has no row, so the router does not know which device should get it, and drops it. Try a few incoming packets:

RowPrivate sidePublic side
Laptop, tab 1192.168.1.23:52814203.0.113.45:40001
Laptop, tab 2192.168.1.23:52815203.0.113.45:40002
Phone, Kadé app192.168.1.40:61022203.0.113.45:40003
Smart TV192.168.1.52:49200203.0.113.45:40004

Pick an incoming packet above.

Port forwarding

Every row so far was made by a connection that started inside. Port forwarding is a row you write yourself, ahead of time, into the router's NAT table. You add it on the router's admin page: open its LAN address, 192.168.1.1, in a browser and look for a menu called "Port forwarding" (some routers say "Virtual server"). A packet that arrives from outside then finds a match instead of being dropped.

You are building Kadé's checkout and testing it on your laptop, where kade-api runs on port 3000. When a payment settles, PayGate sends a webhook: its server makes a request to a Kadé URL to say "payment done". This time the connection starts on the internet, not on your laptop. So you add this rule in the router's settings:

203.0.113.45:8443→192.168.1.23:3000
Anyone who connects to 203.0.113.45:8443 now reaches your laptop. Remove the rule when you are done: it is an open door into your home network.

Follow one packet from PayGate:

  1. PayGate's server sends a packet to 203.0.113.45:8443, your router's public IP. That is the address you gave PayGate as your webhook URL.
  2. The router looks for a row whose public side is 203.0.113.45:8443. Nothing inside started this connection, so without the rule there is no such row and the packet is dropped, as in section 9.
  3. With the rule, the row is there. The router changes the destination to 192.168.1.23:3000 and sends the packet to your laptop.
  4. Your laptop replies. On the way out, the router changes the source back to 203.0.113.45:8443, so PayGate sees the reply come from the address it connected to.

How this row differs from the ones in Part A:

Normal rowForwarded row
Added byThe router, when a device inside connects outYou, in the router's settings
Who connectsThe device insideAnyone on the internet
LastsUntil the connection closes or goes idle (section 8)Until you remove it
RewritesThe source: SNATThe destination: DNAT (section 6)

You have met a forwarded row already: kade-api's external IP (section 6). GCP keeps a fixed row that sends 34.87.120.15 to 10.10.1.10, and the VM itself only knows its private address. Section 15 shows it in full.

Without port forwarding: tunnels and hole punching

Port forwarding needs access to the router, and does not work at all behind carrier-grade NAT. Two other ways are used every day.

Reverse tunnels

The laptop opens an outgoing connection to a tunnel service and keeps it open. Visitors connect to the service's public URL, and it sends their traffic back down that open connection. Outgoing connections always get a NAT row, so this works through any NAT. Here is the PayGate webhook from section 10 again, this time with no port forwarding:

home (private)internet (public)Your laptopkade-api on :3000Home router203.0.113.45row made by step 1Tunnel serviceCloudflare, ngrokgives a public URLPayGatesends webhook✕straight to 203.0.113.45: no row, dropped1231 · the laptop connects out and keeps the connection open. Like any outgoing connection, it gets a NAT row.2 · PayGate sends the webhook to the tunnel's public URL, not to your router.3 · the service sends it back down the open connection. It matches the row, so the router lets it in.

Wide by design - scroll it sideways.

Examples: Cloudflare Tunnel, ngrok, or ssh -R to a server you own.

Why does the direct webhook fail while the tunnelled one gets in? Step 1 leaves one row in the router:

Private sidePublic sideTalking to
192.168.1.23:51200203.0.113.45:40020tunnel service:443
  • Straight to 203.0.113.45:8443: no row has port 8443, and none is talking to PayGate. The router cannot tell which device it is for, so it drops it.
  • Even on port 40020: most home routers also check who is sending. PayGate is not the tunnel service, so it is still dropped.
  • Through the tunnel: the webhook arrives inside the tunnel service's own connection, from the tunnel service to port 40020. That matches the row exactly, so it goes to the laptop.

A NAT row is not an open port. It lets in only the replies of one conversation.

Hole punching (peer to peer)

Video calls and WebRTC apps connect two devices that are both behind NAT, with no server in the middle carrying the traffic:

STUN server"your public ip:port is …"Home NAT203.0.113.45:40010Their NAT203.0.113.88:51022Your laptop192.168.1.23:5000Their laptop192.168.1.23:5000112 · swap ip:portthrough any server3 · both send at the same timeeach NAT now has a row for the other side,so the other side's packets are let in1 · each asks STUN "what is my public ip:port?" 2 · they swap those through any server both can reach

Wide by design - scroll it sideways.

Whether step 3 works depends on how each NAT behaves. The classic names:

#NAT typePublic portWho can send in on itHole punching
1Full coneSame for every destinationAnyoneWorks
2Restricted coneSame for every destinationOnly IPs you have sent toWorks
3Port-restricted coneSame for every destinationOnly IP:port pairs you have sent toUsually works
4SymmetricNew one for each destinationOnly the exact destinationFails: STUN saw a different port
When hole punching fails, apps fall back to a TURN relay server that carries the traffic. ICE is the method WebRTC uses to try direct first, then the relay. Symmetric NAT is common in company networks and mobile carriers.

Part DSide effects

Problems NAT causes

#ProblemWhyIn the Kadé scenario
1Devices cannot be reached from outsideEvery connection must start from inside (section 9)You need a tunnel or forwarding to demo your laptop's Node app
2Protocols that put IPs in the data breakNAT only rewrites headers (section 4). FTP (active mode) and SIP phone calls write the private IP inside the message. Routers use an ALG (Application Layer Gateway) to patch these, and ALGs cause their own bugs.An office VoIP phone with one-way audio is the classic symptom
3Many people, one IPA per-IP limit or ban hits everyone behind the NATIf kade-api allows 100 requests per minute per IP, the whole office (198.51.100.20) shares that limit. Limit by user or API key instead.
4Logs lose the deviceThe server only sees the public IPkade-api's logs show 198.51.100.20, not which staff PC. Finding it needs the router's NAT log (time + public port).
5Double NATTwo NATs in a row (your router + carrier-grade NAT, chapter 2)Port forwarding at home stops working; some games and calls fail
6State to keepEvery connection costs memory and can time out (section 8)Idle database connections through Cloud NAT drop after 20 minutes

NAT is not a firewall, and IPv6

NAT

Built to save addresses. Blocking unknown inbound traffic is a side effect, and a single port forwarding rule undoes it.

Stateful firewall

Built to protect. It lets replies in and blocks unknown traffic on purpose, with rules you control. This is the useful part of NAT's side effect, done properly.

With IPv6 there are enough addresses for every device to have its own public one, so home networks normally do not use NAT at all. Protection then comes from the router's firewall. This is one reason to learn firewalls as their own topic, not as "what NAT does".

Part ENAT in the cloud

Cloud NAT

Later in the course, kade-api moves behind a load balancer and loses its external IP (chapter 0's plan). kade-db never had one. Both still need to call out: kade-api to PayGate, kade-db for OS updates. Cloud NAT is GCP's PAT for VMs without external IPs:

kade-vpc · asia-southeast1kade-api (later)10.10.1.10 · no external IPkade-db10.10.2.5 · no external IPCloud NATset up on a Cloud Routerstatic IP 34.87.200.7PayGate APIallow list: 34.87.200.7/32OS update serverspackage mirrors

Wide by design - scroll it sideways.

Not a boxThere is no NAT VM to size or patch. GCP's software network does the translation on each VM's host, so it has no single bottleneck.
RegionalSet up on a Cloud Router in one region, for chosen subnets (or all of them).
Outbound onlyReplies come back; new inbound connections never do. Inbound traffic needs a load balancer or an external IP.
Static or automatic IPsUse reserved static IPs when a partner keeps an allow list, as PayGate does. Automatic IPs can change.
Ports per VMDefault minimum 64 ports per VM (section 7). Raise it, or turn on dynamic port allocation, for busy callers.
Only VMs without external IPsA VM that has its own external IP uses that (1:1 NAT) and skips Cloud NAT.
LogsCan log each translation and each drop (like OUT_OF_RESOURCES), which answers "which VM made this call?"
Serverless services such as Cloud Run can use the same static IP by sending their outbound traffic through the VPC.

NAT across the Kadé scenario

#WhereKindWhat happens
1Home routerPAT (SNAT), many → 1192.168.1.x devices share 203.0.113.45
2Office routerPAT (SNAT), many → 1Both office networks (172.16.1.x and 172.16.2.x) share 198.51.100.20 (chapter 6, case 3)
3kade-api's external IPStatic 1 → 1 (DNAT in, SNAT out)GCP translates 34.87.120.15 ↔ 10.10.1.10. The VM's OS only knows 10.10.1.10: run ip addr on it and the external IP is not there.
4Cloud NAT (planned)PAT (SNAT), many → 1kade-api (after the load balancer) and kade-db share static 34.87.200.7 for outgoing calls
5Some ISPsCarrier-grade NATIf your router's WAN IP is 100.64.x.x to 100.127.x.x (chapter 2), your ISP runs another NAT in front of yours

Where this leaves us

This completes the addressing part of the course: IP addresses, networks and masks, the gateway, MAC and ARP for local delivery, and NAT for leaving a private network. The steps from chapter 1 now all have a name and a reason. Next come the layers above: hop-by-hop routing, TCP, TLS and HTTP.

Summary

#IdeaIn one lineNew terms
1WhyNot enough IPv4 addresses; private ranges + sharingNAT, private range
3The swapSource rewritten on the way out, reversed on the way back
4RewrittenIP, port, checksums; never the data; ping uses its IDchecksum
5NAT tableRows keyed by 5 values; ports tell connections apartPAT, connection tracking, port preservation
6KindsStatic 1:1, dynamic pool, PAT many:1; SNAT out, DNAT inSNAT, DNAT
7Limits~64,500 ports per IP per destination; Cloud NAT: 64 per VM by defaultport exhaustion
8TimeoutsIdle rows are deleted; keepalives prevent silent dropsidle timeout, keepalive
9-10InboundNo row → dropped; port forwarding adds a fixed row that rewrites the destinationport forwarding
11TraversalTunnels go out and stay open; hole punching needs a cone NATSTUN, TURN, ICE, symmetric NAT
12Side effectsBreaks inbound, IPs in data, shared limits, lost device in logsALG, double NAT
13Not a firewallProtection is a side effect; IPv6 usually has no NATstateful firewall
14CloudCloud NAT: regional, outbound only, static IPs, ports per VMCloud NAT, Cloud Router

Try it yourself

Your private IP, then your public IP

  • Steps: ipconfig getifaddr en0 then curl ifconfig.me
  • What to look for: Two different addresses: NAT sits between them.
  • Runs on: Linux: hostname -I · Windows: ipconfig
  • From section: 3. The swap, out and back
ipconfig getifaddr en0curl ifconfig.me

The first few hops

  • What to look for: Two private hops in a row (192.168.x.x then 10.x or 100.64.x) mean double NAT.
  • From section: 12. Problems NAT causes
traceroute 1.1.1.1

Your open connections

  • What to look for: Your side shows the private IP. The router's public ports are never visible here.
  • Runs on: Linux · macOS: netstat -an -p tcp
  • From section: 5. The NAT table
ss -tn

A real NAT table

  • What to look for: Each row shows the original and the translated address and port.
  • Runs on: on a Linux machine acting as a router
  • From section: 5. The NAT table
sudo conntrack -L

A NAT timeout

sysctl net.netfilter.nf_conntrack_udp_timeout

A reverse tunnel to your local app

cloudflared tunnel --url http://localhost:3000

The VM's interfaces

ip addr

A Cloud NAT's settings

  • What to look for: IP allocation (manual = static), min ports per VM, timeouts.
  • From section: 14. Cloud NAT
gcloud compute routers nats describe NAT --router=ROUTER --region=REGION

Which VM holds which NAT ports

  • What to look for: Port ranges per VM interface.
  • From section: 14. Cloud NAT
gcloud compute routers get-nat-mapping-info ROUTER --region=REGION

Spotted a mistake, or something unclear? Suggest an edit on GitHub