NAT, PAT & Port Forwarding; DHCP Lease Flow; CGNAT; Hairpin NAT
"...which would permit multiple nodes in a local network to simultaneously access remote networks using the single IP address assigned to their router." — Srisuresh & Egevang, RFC 3022, Traditional IP Network Address Translator (Traditional NAT), 2001 (on NAPT)
Summary: NAT lets many private hosts share a few public addresses by rewriting IP addresses and ports in flight and remembering each rewrite in a table; DHCP is how those private hosts got their addresses in the first place. Focus: The translation table and conntrack, source vs destination NAT, port forwarding, hairpin, double NAT and CGNAT, NAT traversal, NAT in Docker, Kubernetes and the cloud, losing the client IP and getting it back, and the DHCP DORA exchange with leases and options. Learning goal: Predict what source address every hop sees, explain why "it works on my LAN but not from the internet" happens, read the NAT and conntrack state of a machine, and write the code and configuration that survive NAT.
This chapter is the complete reference for how a developer meets NAT and DHCP: a home router, a cloud NAT gateway, docker run -p, a Kubernetes NodePort, a carrier that shares one public IPv4 among thousands of customers. It builds on IP addressing, private ranges and CIDR (the address space NAT hides) and network models (where NAT sits in the stack). Sockets, ephemeral ports and ss live in ports, sockets and connections; DNS in DNS resolution for developers; filtering rules in firewalls; the container models in Docker networking and Kubernetes networking; tunnels and WireGuard in VPNs and tunnels; a symptom-first view in the troubleshooting playbook. Load balancers, proxies and rate limiting as design topics stay in system design: forward vs reverse proxies, load balancing, rate limiting, TCP and UDP.
Page map
| If you are looking for | Go to |
|---|---|
| The one-page tables to memorise | Everything in one minute |
| Why NAT exists and what it costs | Why NAT and DHCP exist |
| RFCs, history, NAT terminology | Where it comes from |
| Static, dynamic, PAT, source vs destination NAT | NAT types |
| The translation table, conntrack, 5-tuple, timeouts | The translation table and conntrack |
| How a reply finds its way back | Reply path |
Port forwarding, docker run -p | Port forwarding (DNAT) |
| Container cannot reach itself through the public port | Hairpin NAT |
| Double NAT, 100.64.0.0/10, why self-hosting fails | Double NAT and CGNAT |
| STUN, TURN, ICE, hole punching, WireGuard keepalive | NAT traversal |
| FTP, SIP, ALGs | Protocols that embed IPs |
Pods, NodePort, externalTrafficPolicy, egress IPs | NAT in Kubernetes |
| NAT gateway, Internet gateway, Elastic IP, cost | NAT in the cloud |
| Everything is one client IP: X-Forwarded-For, PROXY protocol | Lost client IPs |
| DHCP DORA, leases, options, relay, rogue servers | DHCP |
| DHCPv6 and SLAAC | DHCPv6 vs SLAAC |
| Static vs dynamic addresses, ephemeral ports | Addressing choices |
iptables, nft, conntrack, ipconfig getpacket | Seeing NAT |
| Go code: forwarder, PROXY protocol, XFF, hole punch | Solving the classic problems |
| Laravel: TrustProxies, rate limits, webhooks | Laravel |
| Which design for which situation | Choosing |
| Monolith to distributed | In architecture |
| Reproduce it | Lab |
| Bugs, misconceptions, cheat sheet, glossary | Common bugs, Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The picture. Every row is unpacked later.
| Thing | In plain words | Tiny example | Where it lives |
|---|---|---|---|
| NAT | A device rewrites addresses in packets as they pass | 192.168.1.10 becomes 203.0.113.7 on the way out | Router, firewall, cloud gateway, Docker host |
| PAT / NAPT / masquerade | Many private hosts share one public IP; ports tell them apart | Three laptops, one public IP, ports 40000-40002 | Every home router |
| Source NAT (SNAT) | Rewrite who the packet claims to be from | Container to the internet leaves as the host | POSTROUTING |
| Destination NAT (DNAT) | Rewrite where the packet is going | Public :8080 becomes 172.17.0.2:80 | PREROUTING / OUTPUT |
| Port forward | A permanent DNAT rule so the outside can reach one inside service | Router: WAN :443 goes to 192.168.1.10:443 | Router UI, docker run -p |
| conntrack | The kernel's table of flows that makes NAT reversible | One row per connection, both directions | Linux netfilter |
| Hairpin NAT | An inside client using the outside address of an inside server | Laptop opens http://203.0.113.7:8080 which is its own LAN server | Router, Docker bridge |
| CGNAT | The ISP does NAT for you on top of yours | WAN address 100.64.12.9, not a public IP | ISP |
| DHCP | A server hands out address, gateway, DNS for a limited time | Laptop joins Wi-Fi, gets 10.84.50.174 for an hour | Router, cloud, dnsmasq |
The four DHCP messages and the three timers.
| Message / timer | Direction | What it carries | When |
|---|---|---|---|
| DISCOVER | client to broadcast | "I need an address", parameter request list | Boot, link up |
| OFFER | server to client | yiaddr, lease time, options | Answer to DISCOVER |
| REQUEST | client to broadcast | Chosen address and server identifier | Accepts one offer; renews at T1/T2 |
| ACK | server to client | Final lease and options | Lease starts |
| T1 (renewal) | client to the same server (unicast) | REQUEST | 50% of the lease by default |
| T2 (rebinding) | client to any server (broadcast) | REQUEST | 87.5% of the lease by default |
| Lease expiry | client | Must stop using the address | 100% |
The three things to do.
| Situation | Do this |
|---|---|
| Your app logs or rate-limits by client IP behind a load balancer or NAT | Configure TrustProxies (Laravel) or a trusted-proxy resolver (Go) and read the rightmost untrusted hop, never the leftmost |
| You must be reachable from the internet | Public IP plus a port forward, or an outbound tunnel (cloudflared, ngrok, WireGuard to a VPS) when you are behind CGNAT |
| A hard-coded private IP keeps breaking | Use DNS names, or a DHCP reservation, or a static address outside the DHCP pool |
Why NAT and DHCP exist
IPv4 has 2^32 addresses, about 4.3 billion. The internet outgrew that. RFC 3022 describes the first remedy in its own words: many users have "multiple Network nodes in their office" but "a single IP address assigned to their remote access router", and NAPT lets them all use it. NAT turned "one address per device" into "one address per household or per company", which is why IPv4 is still alive. IPv6 (128-bit) removes the shortage, but both worlds will coexist for years, so every developer meets NAT daily.
DHCP exists for a neighbouring reason: if every device behind that router needed a hand-typed address, gateway and DNS, nothing would work out of the box. The router runs a DHCP server so a laptop joining Wi-Fi gets a working configuration with no typing.
| Without it | With it |
|---|---|
| One public IPv4 per device | One public IPv4 per site; private addresses inside |
| Every host typed its own IP, mask, gateway, DNS | A server hands out configuration for a limited lease |
| Anything on the internet can open a connection to any host | Hosts behind NAT are unreachable until you forward a port (a side effect, not a firewall) |
| End-to-end addressing: the sender's IP is the real sender | The IP you see may be a shared gateway; the real client is hidden |
The everyday picture. A company switchboard. Employees have internal extensions (private IPs). Outside callers see one phone number (public IP). When an employee calls out, the switchboard remembers "extension 12 is on line 3". When line 3 rings back, it connects to extension 12. If a stranger calls the main number and asks for extension 12, the switchboard has no idea what line to use unless you configured a rule ("calls to the main number's option 2 go to extension 12": a port forward). DHCP is the reception desk handing a new employee an extension for the day.
Three misunderstandings, up front.
| Misunderstanding | Reality |
|---|---|
| "NAT is a firewall" | NAT blocks unsolicited inbound packets only because no table row exists. It is a side effect, easily bypassed (hole punching, UPnP, a forward) and says nothing about outbound. Use a real firewall |
| "My server's IP is what clients see" | Behind NAT, clients see the gateway's address; your server sees the gateway or load balancer's address, not the client's |
| "A port forward is enough to host from home" | Not if your ISP uses CGNAT: the packet never reaches your router |
Where it comes from
| Source | What it gave us |
|---|---|
| RFC 1918 (1996) | The private ranges 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 that are never routed on the internet |
| RFC 2663 (1999) | The vocabulary: address realm, NAT, NAPT, ALG, "transparent routing" |
| RFC 3022 (2001) | Traditional NAT: Basic NAT and NAPT (the one with ports), the table and the checksum updates |
| RFC 3027 (2001) | "Protocol Complications with the IP Network Address Translator": why FTP and others break |
| RFC 4787 (2007) | NAT behaviour for UDP: mapping types, filtering, hairpinning, the 2 minute UDP timer |
| RFC 5382 (2008) | The same for TCP: the "established connection idle-timeout" must be at least 2 hours 4 minutes |
| RFC 6598 (2012) | 100.64.0.0/10, "Shared Address Space" for Carrier-Grade NAT |
| RFC 8445 / 8489 / 8656 | ICE, STUN and TURN: how WebRTC and games cross NATs |
| RFC 2131 / 2132 (1997) | DHCP and its options; RFC 3046 relay agent information; RFC 8415 DHCPv6; RFC 4862 SLAAC |
| HAProxy PROXY protocol spec | The de facto way a TCP proxy hands the real client address to the next hop |
RFC 3022 itself says the cost plainly: the approach has "the disadvantage of taking away the end-to-end significance of an IP address, and making up for it with increased state in the network", and RFC 6598 is explicit that Shared Address Space "is distinct from RFC 1918 private address space because it is intended for use on Service Provider networks".
The concept catalogue
Static (1:1) NAT Good to know
In plain words: One private address is permanently mapped to one public address, both directions, no ports involved.
Common misunderstanding: "1:1 NAT saves addresses." It does not; it spends one public IP per private host. It exists for reachability and renumbering, not for saving addresses.
Definition: Basic NAT in RFC 3022: only the IP address is rewritten, the transport ports are untouched. The AWS Internet gateway does exactly this: it "logically provides the one-to-one NAT on behalf of your instance", so the instance only knows its private address while the internet sees its public or Elastic IP.
Outbound 10.0.1.25:44000 -> 93.184.216.34:443 becomes 54.0.0.9:44000 -> 93.184.216.34:443
Inbound 93.184.216.34:443 -> 54.0.0.9:44000 becomes 93.184.216.34:443 -> 10.0.1.25:44000Real scenarios: an EC2 instance with a public IPv4; a DMZ server mapped to a published address; merging two companies that both used 10.0.0.0/8 (1:1 NAT hides one side behind a translated range).
| Product | How you do 1:1 NAT |
|---|---|
| Linux | iptables -t nat -A PREROUTING -d 54.0.0.9 -j DNAT --to 10.0.1.25 plus -A POSTROUTING -s 10.0.1.25 -j SNAT --to 54.0.0.9, or nft dnat to / snat to |
| AWS | Internet gateway plus public IPv4 or Elastic IP on the instance |
| Home router | "DMZ host" (forwards everything to one device) |
| Cisco IOS | ip nat inside source static |
Dynamic NAT Good to know
In plain words: A pool of public addresses is handed out to private hosts as they need one and taken back when idle.
Common misunderstanding: "Dynamic NAT is what my home router does." Your router does PAT, which shares one address by port. Dynamic NAT uses one public address per active host, so it runs out when the pool is smaller than the number of active hosts.
Definition: Basic NAT with a pool; entries are created on first outbound packet and removed on timeout. Rare today because it needs many public addresses; seen in corporate edge devices with a small public block.
pool 203.0.113.10-12
t0 10.0.0.5 -> internet : takes 203.0.113.10
t1 10.0.0.6 -> internet : takes 203.0.113.11
t2 10.0.0.7 -> internet : takes 203.0.113.12
t3 10.0.0.8 -> internet : no free address, packet droppedPAT / NAPT / masquerade Must-know
In plain words: Many private hosts share ONE public IP. The router also rewrites the source port so it can tell the flows apart.
Common misunderstanding: "My port 51000 stays 51000 on the internet." It may not: if two hosts use the same source port, the router changes one of them. The outside world only ever sees the router's port.
Definition: NAPT (Network Address Port Translation) in RFC 3022; "PAT" is Cisco's name; "masquerade" is Linux's flavour of SNAT that takes the outgoing interface's current address (so it keeps working when a DHCP-assigned WAN address changes).
The diagram shows the table as the router sees it. A runnable toy version follows; its output is real.
// A toy PAT (NAPT) table: the heart of every home router and NAT gateway.
// It maps (private IP, private port, protocol) to a public port, expires idle
// entries, and runs out of ports exactly like a real conntrack/NAT table.
package main
import (
"errors"
"fmt"
"time"
)
type Key struct {
Proto string
SrcIP string
SrcPort uint16
DstIP string // part of the 5-tuple: same private socket to a different server can reuse a port
DstPort uint16
}
type Entry struct {
PublicPort uint16
LastSeen time.Time
}
type PAT struct {
PublicIP string
Timeout time.Duration
lo, hi uint16
table map[Key]*Entry
inUse map[uint16]Key
next uint16
now func() time.Time
}
var ErrExhausted = errors.New("no free public port: table exhausted")
func NewPAT(publicIP string, lo, hi uint16, timeout time.Duration, now func() time.Time) *PAT {
return &PAT{PublicIP: publicIP, Timeout: timeout, lo: lo, hi: hi, next: lo,
table: map[Key]*Entry{}, inUse: map[uint16]Key{}, now: now}
}
// Outbound translates a packet leaving the private network (source NAT).
func (p *PAT) Outbound(k Key) (string, uint16, error) {
p.expire()
if e, ok := p.table[k]; ok {
e.LastSeen = p.now()
return p.PublicIP, e.PublicPort, nil
}
for i := 0; i <= int(p.hi-p.lo); i++ {
port := p.lo + uint16((int(p.next-p.lo)+i)%(int(p.hi-p.lo)+1))
if _, taken := p.inUse[port]; taken {
continue
}
p.table[k] = &Entry{PublicPort: port, LastSeen: p.now()}
p.inUse[port] = k
p.next = port + 1
return p.PublicIP, port, nil
}
return "", 0, ErrExhausted
}
// Inbound finds the private socket for a reply. No entry means the packet is
// dropped: that is why an unsolicited packet from the internet never gets in.
func (p *PAT) Inbound(proto, remoteIP string, remotePort, publicPort uint16) (Key, bool) {
p.expire()
k, ok := p.inUse[publicPort]
if !ok || k.Proto != proto || k.DstIP != remoteIP || k.DstPort != remotePort {
return Key{}, false
}
p.table[k].LastSeen = p.now()
return k, true
}
func (p *PAT) expire() {
for k, e := range p.table {
if p.now().Sub(e.LastSeen) > p.Timeout {
delete(p.inUse, e.PublicPort)
delete(p.table, k)
}
}
}
func main() {
clock := time.Unix(0, 0)
now := func() time.Time { return clock }
nat := NewPAT("203.0.113.7", 40000, 40002, 30*time.Second, now) // tiny range on purpose
a := Key{"udp", "192.168.1.10", 51000, "198.51.100.5", 3478}
b := Key{"udp", "192.168.1.11", 51000, "198.51.100.5", 3478} // same private port, other host
c := Key{"tcp", "192.168.1.12", 49152, "93.184.216.34", 443}
for _, k := range []Key{a, b, c} {
ip, port, err := nat.Outbound(k)
fmt.Printf("OUT %-3s %s:%d -> %s:%d mapped to %s:%d err=%v\n", k.Proto, k.SrcIP, k.SrcPort, k.DstIP, k.DstPort, ip, port, err)
}
_, _, err := nat.Outbound(Key{"tcp", "192.168.1.13", 50000, "93.184.216.34", 443})
fmt.Println("4th flow with 3 ports:", err)
if k, ok := nat.Inbound("udp", "198.51.100.5", 3478, 40001); ok {
fmt.Printf("IN reply to :40001 delivered to %s:%d\n", k.SrcIP, k.SrcPort)
}
_, ok := nat.Inbound("udp", "203.0.113.99", 9999, 40001)
fmt.Println("IN unsolicited packet from another host delivered:", ok)
clock = clock.Add(31 * time.Second) // idle timeout passes
_, ok = nat.Inbound("udp", "198.51.100.5", 3478, 40001)
fmt.Println("IN reply after idle timeout delivered:", ok)
ip, port, err := nat.Outbound(Key{"tcp", "192.168.1.13", 50000, "93.184.216.34", 443})
fmt.Printf("4th flow after expiry: %s:%d err=%v\n", ip, port, err)
}OUT udp 192.168.1.10:51000 -> 198.51.100.5:3478 mapped to 203.0.113.7:40000 err=<nil>
OUT udp 192.168.1.11:51000 -> 198.51.100.5:3478 mapped to 203.0.113.7:40001 err=<nil>
OUT tcp 192.168.1.12:49152 -> 93.184.216.34:443 mapped to 203.0.113.7:40002 err=<nil>
4th flow with 3 ports: no free public port: table exhausted
IN reply to :40001 delivered to 192.168.1.11:51000
IN unsolicited packet from another host delivered: false
IN reply after idle timeout delivered: false
4th flow after expiry: 203.0.113.7:40000 err=<nil>| Product | Flavour | Command or setting |
|---|---|---|
| Linux netfilter | MASQUERADE | iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE |
| Linux netfilter | SNAT --to-source | Same, with a fixed address: faster, for static WAN IPs |
| nftables | masquerade / snat to | nft add rule ip nat postrouting oifname "eth0" masquerade |
| Cisco IOS | PAT | ip nat inside source list 1 interface Gi0/0 overload |
| pfSense / OPNsense / OpenBSD pf | Outbound NAT | nat on em0 from 192.168.1.0/24 to any -> (em0) in pf |
| macOS | Internet Sharing | uses pf NAT under the hood |
| AWS | NAT gateway | managed, fixed Elastic IP |
| Docker | MASQUERADE for each bridge subnet | written automatically |
Source NAT vs destination NAT Must-know
In plain words: SNAT changes who a packet says it is from. DNAT changes where it says it is going. Which one you need depends on who starts the conversation.
Common misunderstanding: "NAT only rewrites the source." Outbound access for many hosts is SNAT, but every port forward, every load balancer VIP and every Kubernetes Service is DNAT.
Definition: netfilter does SNAT in POSTROUTING (the packet is already routed, "anything else on the Linux box itself ... will see the packet unchanged", as the netfilter NAT HOWTO puts it) and DNAT in PREROUTING (for traffic arriving from outside) and OUTPUT (for locally generated traffic). Masquerading is "a specialized case of Source NAT ... only be used for dynamically-assigned IP addresses".
Who starts it? Rewrite Chain Example
inside -> outside source (SNAT/masq) POSTROUTING laptop browses the web
outside -> inside destination (DNAT) PREROUTING port forward, LB VIP
local process -> VIP destination (DNAT) OUTPUT curl localhost:8080 on a Docker host| Direction | Netfilter hook | iptables syntax | nftables syntax |
|---|---|---|---|
| SNAT | postrouting | -t nat -A POSTROUTING -o eth0 -j SNAT --to-source 203.0.113.7 | snat to 203.0.113.7 |
| Masquerade | postrouting | -t nat -A POSTROUTING -o eth0 -j MASQUERADE | masquerade |
| DNAT | prerouting | -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 172.17.0.2:80 | tcp dport 8080 dnat to 172.17.0.2:80 |
| REDIRECT | prerouting | -j REDIRECT --to-ports 3128 (DNAT to the local box) | redirect to :3128 |
The translation table and conntrack Must-know
In plain words: The router keeps a notebook of every conversation it has rewritten, so it can undo the rewrite on the answer. On Linux that notebook is the kernel's connection tracking table, conntrack.
Common misunderstanding: "conntrack is part of the firewall only." It is the state that makes NAT possible at all; the stateful firewall rule ESTABLISHED,RELATED is just a consumer of the same table.
Definition: A conntrack entry is keyed by the 5-tuple (protocol, source IP, source port, destination IP, destination port) of the original direction and stores the expected reply tuple, with the NAT rewrite included. Each entry has a timeout that depends on protocol state and is refreshed by traffic. When the table is full, new connections are dropped.
Real output from the lab (Docker Desktop's Linux VM), a curl to a published port:
tcp 6 431998 ESTABLISHED src=127.0.0.1 dst=127.0.0.1 sport=56997 dport=8080 src=172.17.0.2 dst=172.17.0.1 sport=80 dport=56997 [ASSURED] mark=0 use=1
tcp 6 119 TIME_WAIT src=127.0.0.1 dst=127.0.0.1 sport=59364 dport=8080 src=172.17.0.2 dst=172.17.0.1 sport=80 dport=59364 [ASSURED] mark=0 use=1Read each line left to right. After tcp 6 (protocol number 6) comes the remaining timeout in seconds, then the state, then two tuples. The first src= dst= sport= dport= is the ORIGINAL direction (what the client sent). The second is the REPLY direction, the one the kernel will expect, with the rewrite already applied: here the reply comes from 172.17.0.2:80. 431998 seconds is nf_conntrack_tcp_timeout_established (432000, 5 days); 119 of 120 is nf_conntrack_tcp_timeout_time_wait.
Knob (sysctl net.netfilter.) | Default | Meaning |
|---|---|---|
nf_conntrack_max | nf_conntrack_buckets x 4 (262144 on the lab VM) | Table size; when full the kernel logs nf_conntrack: table full, dropping packet |
nf_conntrack_count (read only) | current | Entries now |
nf_conntrack_tcp_timeout_established | 432000 (5 days) | Idle established TCP flow |
nf_conntrack_tcp_timeout_time_wait | 120 | TIME_WAIT flow |
nf_conntrack_tcp_timeout_fin_wait | 120 | Closing |
nf_conntrack_udp_timeout | 30 | UDP flow with traffic in one direction only |
nf_conntrack_udp_timeout_stream | 120 | UDP "stream" (traffic both ways) |
nf_conntrack_buckets | auto | Hash table size; raise together with max |
RFC 4787 REQ-5 says a NAT's UDP mapping timer "MUST NOT expire in less than two minutes" (with an exception for well-known ports), and RFC 5382 REQ-5 says an established TCP idle timeout "MUST NOT be less than 2 hours 4 minutes". Real devices are looser: many consumer routers expire UDP in 30 to 60 seconds, which is why you need keepalives.
conntrack tuple (what a row stores)
original: proto=tcp src=192.168.1.10:51000 dst=93.184.216.34:443
reply: proto=tcp src=93.184.216.34:443 dst=203.0.113.7:40000 <- rewritten destination
state: ESTABLISHED timeout: 431998 s [ASSURED]Table exhaustion. Every connection, including each short-lived health check and each TIME_WAIT, holds a row. A busy NAT box, a Kubernetes node or a Docker host running a scraper can fill the table; then new flows silently disappear (the SYN is dropped, the client sees a timeout, not a refusal). Check conntrack -C against nf_conntrack_max, look at conntrack -S (insert_failed, drop, early_drop) and fix by raising nf_conntrack_max, lowering timeouts for noisy protocols, reusing connections (keep-alive, pooling) or moving offending traffic to NOTRACK / raw table rules.
How a reply finds its way back Must-know
In plain words: The reply is addressed to the router's public IP and port. The router looks that pair up in its table, finds the private host that owns it, rewrites the destination and forwards.
Common misunderstanding: "The server knows where the client really lives." It only knows the router's address and the translated port. If the table row is gone (timeout, reboot) the reply is dropped and the client's connection hangs.
1 laptop 192.168.1.10:51000 -> web 93.184.216.34:443 SYN
2 router rewrites source -> 203.0.113.7:40000, creates row
3 web 93.184.216.34:443 -> 203.0.113.7:40000 SYN-ACK
4 router matches public port 40000 -> 192.168.1.10:51000, rewrites destination
5 laptop receives 93.184.216.34:443 -> 192.168.1.10:51000
6 IP and TCP checksums are recomputed at every rewriteBecause the address is part of the TCP/UDP checksum (the pseudo header), every NAT rewrite must also update the IP header checksum and the transport checksum. NAT is also why a TCP connection cannot survive a change of the client's public address (a phone moving from Wi-Fi to mobile data): the 4-tuple changes, so it is a new connection. QUIC adds a connection ID to survive exactly that.
Port forwarding (DNAT) Must-know
In plain words: A standing rule at the edge: "anything arriving at public port X goes to this inside machine, port Y". It is how an inside service becomes reachable from outside.
Common misunderstanding: "-p 8080:80 just opens a port." It installs a DNAT rule, a masquerade rule and a forwarding allowance, and in many setups starts a user-space proxy as well. The container never listens on 8080.
Definition: DNAT in PREROUTING rewrites the destination; conntrack remembers the rewrite so the reply is automatically un-NATed.
Real rules Docker wrote for docker run -d -p 8080:80 nginx:alpine (the lab):
$ iptables -t nat -S
-A PREROUTING -m addrtype --dst-type LOCAL -j DOCKER
-A OUTPUT -m addrtype --dst-type LOCAL -j DOCKER
-A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE
-A POSTROUTING -s 172.17.0.2/32 -d 172.17.0.2/32 -p tcp -m tcp --dport 80 -j MASQUERADE
-A DOCKER -p tcp -m tcp --dport 8080 -j DNAT --to-destination 172.17.0.2:80Line by line: PREROUTING and OUTPUT send any packet addressed to a local IP into the DOCKER chain; the DOCKER chain DNATs :8080 to the container; POSTROUTING ... ! -o docker0 -j MASQUERADE is the outbound masquerade for the whole 172.17.0.0/16 bridge; the /32 to /32 rule is the hairpin helper (see Hairpin NAT). A matching FORWARD chain rule accepts tcp dport 80 to 172.17.0.2. The Docker docs state that the rules exist "to implement functionality including port publishing, and NAT/masquerading" and that "you should not modify the rules created by Docker".
| Where | How the forward is configured | Reachable from |
|---|---|---|
| Home router | Web UI: "Port forwarding" / "Virtual server": WAN port, LAN IP, LAN port, protocol | Internet, if you have a real public IP |
| UPnP / NAT-PMP / PCP | The app asks the router to open a port by itself (games, torrents) | Internet; a security risk if enabled blindly |
| Linux | iptables -t nat -A PREROUTING ... -j DNAT plus a FORWARD accept; net.ipv4.ip_forward=1 | Whoever can reach this host |
| Docker | -p host:container, -p 127.0.0.1:8080:80 (loopback only), -p 8080:80/udp | All interfaces unless you bind an IP |
| Kubernetes | NodePort, LoadBalancer, hostPort | Node IP:30000-32767, or the cloud LB |
| AWS | Security group + route to Internet gateway + public IP; NLB/ALB listeners | Internet |
| SSH | ssh -L 8080:10.0.0.5:80 bastion is a user-space forward, not NAT | Your laptop only |
Timeline of a single request through Docker's forward (real addresses from the lab, client 192.168.65.1 is the Docker Desktop gateway):
1 client 192.168.65.1:53895 -> host 192.168.65.3:8080 SYN arrives
2 nat/PREROUTING -> DOCKER: dport 8080 -> DNAT 172.17.0.2:80
3 filter/FORWARD: DOCKER chain allows dport 80 to 172.17.0.2
4 nginx 172.17.0.2:80 sees client 192.168.65.1 (not the real remote host if it came via the userland proxy)
5 reply 172.17.0.2:80 -> 192.168.65.1:53895 matches conntrack, source rewritten to 192.168.65.3:8080The Docker daemon can also run docker-proxy, a user-space TCP forwarder, for traffic that cannot be DNATed (loopback 127.0.0.1:8080 on a Linux host, or Docker Desktop). That is why the application inside the container often logs the bridge gateway (172.17.0.1) as the client instead of the real address, which is the next section's problem.
Hairpin NAT (NAT loopback) Important
In plain words: An inside machine reaches an inside server by its OUTSIDE address. The router must turn the packet around and send it back in, and also fix the source address so the reply comes back through the router.
Common misunderstanding: "If the port forward works from the internet it works from my own LAN." Many routers do not support hairpinning, so http://203.0.113.7:8080 times out from inside but works from a phone on mobile data.
Definition: RFC 4787 section 6: if two hosts X1 and X2 are behind the same NAT, "If X1 sends traffic to X2':x2', it goes to the NAT, which must relay the traffic from X1 to X2. This is referred to as hairpinning". Doing it right needs DNAT of the destination and SNAT of the source, otherwise the server answers X1 directly with its own source address and X1 drops the packet as a reply from an unknown peer.
The same thing happens in Docker. A container that connects to the host's published port (http://172.17.0.1:8080 or the host's LAN IP) is DNATed back to itself. I reproduced it in the lab by deleting the helper rule Docker had added:
$ iptables -t nat -D POSTROUTING -s 172.17.0.2/32 -d 172.17.0.2/32 -p tcp -m tcp --dport 80 -j MASQUERADE
$ docker exec natlab curl -s -m 4 -o /dev/null -w "self via gw:8080 -> %{http_code}\n" http://172.17.0.1:8080/
self via gw:8080 -> 000 # curl exit code 28: timeout
$ iptables -t nat -A POSTROUTING -s 172.17.0.2/32 -d 172.17.0.2/32 -p tcp -m tcp --dport 80 -j MASQUERADE
$ docker exec natlab curl ... http://172.17.0.1:8080/
after restore -> 200Broken hairpin (no SNAT half)
1 container 172.17.0.2:35000 -> 172.17.0.1:8080
2 DNAT dest -> 172.17.0.2:80 (source still 172.17.0.2)
3 packet loops back into the same container, source = destination host
4 container answers 172.17.0.2:80 -> 172.17.0.2:35000 (to itself, never leaves)
5 client socket waits for a SYN-ACK from 172.17.0.1:8080: sees none -> timeout
Fixed hairpin (Docker's rule, or router "NAT loopback")
2' SNAT source -> 172.17.0.1 (masquerade) so the reply must return via the gateway| Product | Hairpin behaviour |
|---|---|
| Docker bridge | Adds a /32 -> /32 MASQUERADE rule per published port (above); docker-proxy also serves it |
| Home routers | "NAT loopback" or "NAT reflection" setting; many cheap ones lack it |
| pfSense / OPNsense | "NAT reflection mode" (pure NAT / NAT + proxy) |
| Linux router | DNAT in PREROUTING plus -s lan -d server -j MASQUERADE in POSTROUTING |
| AWS | Not a gateway feature: use private DNS or the private IP from inside the VPC (split-horizon) |
| Kubernetes | Services work from their own pods thanks to kube-proxy plus hairpinMode in the CNI bridge (hairpin_mode on the veth) |
The cleanest fix is never to need it: use split-horizon DNS (internal name resolves to the private IP, external name to the public IP), or use the private address or service name from inside.
Double NAT and CGNAT Must-know
In plain words: Double NAT is two routers in series (an ISP box plus your own). CGNAT (Carrier-Grade NAT) is the ISP doing the sharing: many customers share a public IPv4 and your router's WAN address is not public at all.
Common misunderstanding: "I forwarded the port, so people can reach my home server." If your router's WAN address is 100.64.0.0/10 or any private range, the forward is on the wrong device; the carrier's NAT has no row for the visitor's packet and drops it. Port forwards only work if your router owns the public IP.
Definition: RFC 6598 reserved 100.64.0.0/10 (100.64.0.0 to 100.127.255.255) as Shared Address Space "to accommodate the needs of Carrier-Grade NAT (CGN) devices", used "to number the interfaces that connect CGN devices to Customer Premises Equipment". Test your router's WAN IP: in 10/8, 172.16/12, 192.168/16 or 100.64/10 means you are behind at least one more NAT.
internet visitor -> 203.0.113.7:443 (shared public IP of the ISP)
ISP CGNAT: no row for this flow, no rule for this port -> drop
... your home router's WAN 100.64.12.9 never even sees the SYN| Situation | Symptom | Fix |
|---|---|---|
| Your own router behind an ISP router (double NAT) | Port forward on the inner router fails | Put the ISP box in bridge mode, or forward on both, or set the inner router as the ISP box's "DMZ host" |
| ISP CGNAT, IPv4 only | Cannot host anything; WAN IP is 100.64/10 | Ask for a public IP (often paid), use IPv6, or use an outbound tunnel (cloudflared, ngrok, WireGuard to a VPS with a public IP, Tailscale) |
| Many users behind one CGNAT address | Sites rate-limit or block "your" IP because of a neighbour | Prefer IPv6; do not treat one IPv4 as one person |
| Games and P2P | "Strict NAT" type; no direct connections | UPnP does not help (it only talks to your router); IPv6 or relays |
| Rate limiting your own service | One public IPv4 may be thousands of real users | Key limits on user/session and use generous per-IP caps |
Self-hosting behind CGNAT fails for a simple reason: inbound traffic needs an inbound mapping, mappings are created by outbound packets or by rules on the device that owns the public address, and you do not own it. The reverse-connection tunnels (see NAT traversal and Laravel) work because YOUR machine dials out, which the CGNAT happily maps.
NAT traversal: STUN, TURN, ICE, hole punching and keepalive Important
In plain words: Two peers behind two NATs both only talk outward. A helper server on the public internet tells each one how the other looks from the outside; then both send at the same time, which makes each NAT create the row that lets the other's packet in. If that fails, a relay carries the traffic.
Common misunderstanding: "NAT traversal means breaking through the firewall." It is the opposite: it cooperates with the NAT by sending outbound packets the NAT will map. A NAT that gives each destination a different external port (symmetric NAT) defeats it, and then a relay is the only option.
Definition: STUN (Session Traversal Utilities for NAT, RFC 8489) lets a client learn its public ip:port, the "server-reflexive address"; TURN (Traversal Using Relays around NAT, RFC 8656) allocates a relayed address on a public server; ICE (Interactive Connectivity Establishment, RFC 8445) gathers all candidates (host, server-reflexive, relayed), pairs them, runs connectivity checks and picks the best. RFC 8445's abstract: "This document describes a protocol for Network Address Translator (NAT) traversal for UDP-based communication".
Hole punching (UDP)
1 A (192.168.1.10) -> rendezvous S: REGISTER NAT-A maps A:51000 -> 203.0.113.7:40000
2 B (10.0.0.4) -> rendezvous S: REGISTER NAT-B maps B:51000 -> 198.51.100.9:61000
3 S -> A: "peer is 198.51.100.9:61000" S -> B: "peer is 203.0.113.7:40000"
4 A -> 198.51.100.9:61000 (NAT-A row now allows replies from that remote)
B -> 203.0.113.7:40000 (NAT-B row likewise); first packets may be dropped, later ones pass
5 Both now exchange packets directly. A keepalive every 15-25 s keeps both rows aliveNAT mapping and filtering behaviour decides whether this works (RFC 4787 vocabulary): endpoint-independent mapping reuses the same external port for all destinations (needed for traversal, REQ-1: "A NAT MUST have an 'Endpoint-Independent Mapping' behavior"); address-dependent and address-and-port-dependent mapping change the external port per destination, so the port S saw is useless to the peer.
| NAT type (informal name) | Mapping | Who can send in | Hole punching |
|---|---|---|---|
| Full cone | Endpoint-independent | Anyone, once mapped | Easy |
| Restricted cone | Endpoint-independent | Only hosts the inside host sent to | Works |
| Port-restricted cone | Endpoint-independent | Only host:port sent to | Works with simultaneous send |
| Symmetric | Address-and-port-dependent | Only the exact host:port | Usually fails; use TURN |
A STUN message is tiny and exactly 20 bytes of header for a Binding Request. The snippet builds one and decodes the XOR-MAPPED-ADDRESS answer (the address is XORed with the magic cookie 0x2112A442 so that ALGs that rewrite IPs in payloads do not mangle it):
// A STUN Binding Request and its XOR-MAPPED-ADDRESS answer (RFC 8489):
// how a WebRTC client learns its public ip:port as the NAT sees it.
package main
import (
"crypto/rand"
"encoding/binary"
"encoding/hex"
"fmt"
"net/netip"
)
const magic = 0x2112A442
func bindingRequest() []byte {
b := make([]byte, 20)
binary.BigEndian.PutUint16(b[0:], 0x0001) // Binding Request
binary.BigEndian.PutUint16(b[2:], 0) // message length (no attributes)
binary.BigEndian.PutUint32(b[4:], magic)
rand.Read(b[8:]) // 96-bit transaction id
return b
}
// encodeXorMapped builds the success response attribute for ip:port.
func encodeXorMapped(ap netip.AddrPort) []byte {
a := make([]byte, 12)
binary.BigEndian.PutUint16(a[0:], 0x0020) // XOR-MAPPED-ADDRESS
binary.BigEndian.PutUint16(a[2:], 8)
a[5] = 0x01 // IPv4
binary.BigEndian.PutUint16(a[6:], ap.Port()^uint16(magic>>16))
ip := ap.Addr().As4()
binary.BigEndian.PutUint32(a[8:], binary.BigEndian.Uint32(ip[:])^magic)
return a
}
func decodeXorMapped(a []byte) netip.AddrPort {
port := binary.BigEndian.Uint16(a[6:]) ^ uint16(magic>>16)
x := binary.BigEndian.Uint32(a[8:]) ^ magic
var ip [4]byte
binary.BigEndian.PutUint32(ip[:], x)
return netip.AddrPortFrom(netip.AddrFrom4(ip), port)
}
func main() {
req := bindingRequest()
fmt.Printf("Binding Request (%d bytes):\n%s", len(req), hex.Dump(req))
seen := netip.MustParseAddrPort("203.0.113.7:61234") // what the NAT made of our source
attr := encodeXorMapped(seen)
fmt.Printf("XOR-MAPPED-ADDRESS attribute:\n%s", hex.Dump(attr))
fmt.Println("decoded back:", decodeXorMapped(attr))
}Binding Request (20 bytes):
00000000 00 01 00 00 21 12 a4 42 fe ea d5 dd 44 f9 06 40 |....!..B....D..@|
00000010 1a 42 e7 9f |.B..|
XOR-MAPPED-ADDRESS attribute:
00000000 00 20 00 08 00 01 ce 20 ea 12 d5 45 |. ..... ...E|
decoded back: 203.0.113.7:6123400 01 is the Binding Request type, 00 00 the message length, 21 12 a4 42 the magic cookie, the next 12 bytes the transaction ID. In the attribute, 00 20 is XOR-MAPPED-ADDRESS, 00 08 its length, 00 01 the family (IPv4), ce 20 the port XORed with the top 16 bits of the cookie (0xCE20 ^ 0x2112 = 0xEF32 = 61234), ea 12 d5 45 the address XORed with the cookie.
The protocol part of hole punching runs locally (on loopback no NAT exists, so it proves the message flow, not the NAT behaviour):
// UDP hole punching, run locally. A rendezvous server tells each peer the
// public address it observed for the other peer; both then send to each
// other at the same time. On a real pair of NATs the first outbound packet
// creates the mapping that lets the other side's packet in. On loopback there
// is no NAT, so this demonstrates the protocol, not the NAT behaviour.
package main
import (
"fmt"
"net"
"strings"
"sync"
"time"
)
func rendezvous(wg *sync.WaitGroup, ready chan<- string) {
defer wg.Done()
conn, _ := net.ListenPacket("udp", "127.0.0.1:0")
defer conn.Close()
ready <- conn.LocalAddr().String()
seen := map[string]net.Addr{}
buf := make([]byte, 512)
conn.SetDeadline(time.Now().Add(3 * time.Second))
for len(seen) < 2 {
n, from, err := conn.ReadFrom(buf)
if err != nil {
return
}
seen[string(buf[:n])] = from // "REGISTER name"
}
// Tell each peer where the other one appears from the outside.
for name, addr := range seen {
for other, oaddr := range seen {
if other != name {
conn.WriteTo([]byte("PEER "+oaddr.String()), addr)
}
}
}
}
func peer(name, server string, wg *sync.WaitGroup, out chan<- string) {
defer wg.Done()
conn, _ := net.ListenPacket("udp", "127.0.0.1:0") // ONE socket for server and peer traffic
defer conn.Close()
srv, _ := net.ResolveUDPAddr("udp", server)
conn.WriteTo([]byte("REGISTER "+name), srv)
buf := make([]byte, 512)
conn.SetReadDeadline(time.Now().Add(2 * time.Second))
n, _, err := conn.ReadFrom(buf)
if err != nil {
out <- name + ": no answer from rendezvous"
return
}
other, _ := net.ResolveUDPAddr("udp", strings.TrimPrefix(string(buf[:n]), "PEER "))
// Punch: send immediately; a real NAT creates the mapping on this first packet.
for i := 0; i < 3; i++ {
conn.WriteTo([]byte("HELLO from "+name), other)
time.Sleep(50 * time.Millisecond)
}
for {
conn.SetReadDeadline(time.Now().Add(time.Second))
n, from, err := conn.ReadFrom(buf)
if err != nil {
out <- name + ": nothing received from peer"
return
}
if from.String() == other.String() {
out <- fmt.Sprintf("%s: got %q from %s", name, buf[:n], from)
return
}
}
}
func main() {
var wg sync.WaitGroup
ready := make(chan string, 1)
wg.Add(1)
go rendezvous(&wg, ready)
server := <-ready
out := make(chan string, 2)
wg.Add(2)
go peer("alice", server, &wg, out)
go peer("bob", server, &wg, out)
wg.Wait()
close(out)
for line := range out {
fmt.Println(line)
}
}alice: got "HELLO from bob" from 127.0.0.1:50659
bob: got "HELLO from alice" from 127.0.0.1:49384WireGuard and keepalive. A NAT row dies when it is idle. WireGuard is silent when there is nothing to send, so a peer behind NAT that only wants to RECEIVE will stop being reachable once the row expires. The WireGuard quick start says: "if a peer is behind NAT or a firewall and he wants to receive incoming packets, he must keep the NAT/firewall mapping valid, by periodically sending keepalive packets. This is called persistent keepalives", with "a sensible interval that works with a wide variety of firewalls is 25 seconds" (PersistentKeepalive = 25, default 0 = off). The same rule applies to SSH (ServerAliveInterval 30), TCP keepalive (tcp_keepalive_time, default 7200 s: far longer than a consumer NAT's UDP timeout), long-lived WebSockets (ping frames) and database connections through a NAT gateway.
| Tool | Traversal method | Relay fallback |
|---|---|---|
| WebRTC (browsers) | ICE with STUN | TURN (coturn, Cloudflare, Twilio) |
| Tailscale | Hole punching, coordinated by the control plane | DERP relays |
| WireGuard (plain) | Endpoint roaming + PersistentKeepalive; one side needs a reachable endpoint | None (use a relay peer) |
| Skype / games | Proprietary STUN-like + relays | Super-nodes / servers |
| cloudflared / ngrok | Outbound-only reverse tunnel to the vendor edge | The edge is the relay |
| UPnP-IGD / NAT-PMP / PCP | Ask the router to create a forward | N/A |
Protocols that embed IPs: ALGs Good to know
In plain words: Some protocols put IP addresses inside their payload, not just in the IP header. NAT rewrites the header but not the payload, so the application tells its peer an address that is wrong.
Common misunderstanding: "NAT is transparent to applications." It is, for protocols that only use the headers (HTTP, TLS). It is not for FTP active mode, SIP/RTP, IRC DCC, H.323 and anything carrying an address in its data.
Definition: An Application Layer Gateway (ALG) is code in the NAT that understands such a protocol and rewrites its payload (and keeps the table in sync). RFC 3022: "FTP is the most popular ALG resident on NAT devices", and notes that applications needing an ALG "must not have their payload encoded", since encryption hides the addresses from it.
FTP active mode through NAT
1 client 192.168.1.10 -> server: PORT 192,168,1,10,195,80 (client says: connect back to 192.168.1.10:50000)
2 NAT (no ALG) forwards the line unchanged
3 server tries 192.168.1.10:50000 -> unreachable (private address)
With an ALG: NAT rewrites the line to PORT 203,0,113,7,195,80 and installs a forward for it| Protocol | What embeds an address | Fix |
|---|---|---|
FTP active (PORT/EPRT) | Data-connection address in the control channel | Use passive mode (PASV, client dials out) or the nf_conntrack_ftp helper |
| SIP / SDP / RTP | Contact, c= line and RTP ports in the signalling body | SIP ALG (often buggy: disable on routers), STUN/ICE, SBC |
| H.323, IRC DCC, TFTP | Callback ports | Conntrack helpers (nf_conntrack_*) |
| IPsec ESP | No ports to rewrite | NAT-T: ESP in UDP 4500 |
| TLS-wrapped protocols | Address hidden by encryption | ALG impossible: use passive modes or tunnels |
On modern Linux, automatic helper assignment is off by default for security (net.netfilter.nf_conntrack_helper=0); you attach a helper explicitly with a CT target. A frequent real bug: a router's "SIP ALG" rewrites correct headers into wrong ones, so VoIP gets one-way audio; the fix is to disable the ALG.
NAT in Kubernetes Must-know
In plain words: Pods talk to each other with their own IPs and no NAT, but anything leaving the cluster is SNATed to the node's address, and anything entering through a NodePort or LoadBalancer is DNATed to a pod, and often SNATed too.
Common misunderstanding: "My pod sees the real client IP." Not by default. The Kubernetes tutorial describes the NodePort path: the node replaces "the source IP address (SNAT) in the packet with its own IP address" and "replaces the destination IP on the packet with the pod IP", so the pod sees the node's IP.
Definition: kube-proxy implements Services as DNAT rules (iptables or IPVS, covered in Kubernetes networking); the cluster network is flat for pod to pod; leaving the cluster needs masquerading by the node (or the CNI / cloud NAT).
Pod -> internet Client -> NodePort Client -> NodePort, Local policy
10.244.1.5 -> 93.184.216.34 198.51.100.23 -> node2:30080 198.51.100.23 -> node2:30080
node SNAT: src = node IP node2: SNAT src -> node2, DNAT -> pod node2: DNAT -> local pod only, src kept
(cloud: then NAT gateway SNAT) pod sees node2's IP as client pod sees 198.51.100.23; no endpoint -> dropped| Setting | Client IP seen by the pod | Cost |
|---|---|---|
externalTrafficPolicy: Cluster (default) | The node's IP (SNAT) | Extra hop between nodes possible; even load spread |
externalTrafficPolicy: Local | The real client IP | "kube-proxy only proxies requests to local endpoints, and does not forward traffic to other nodes"; nodes without a pod drop traffic; uneven load |
internalTrafficPolicy: Local | n/a (in-cluster) | Only node-local endpoints for cluster-internal traffic |
Service type LoadBalancer with PROXY protocol | Real client via header | Needs the LB and the app/ingress both configured |
Ingress controller sets X-Forwarded-For | Real client in header | App must trust the ingress only |
The Kubernetes docs say of the Local policy: "This approach preserves the original source IP address." To see the other side, run kubectl edit svc NAME and set spec.externalTrafficPolicy to Local.
| Egress question | Answer |
|---|---|
| What IP does a pod's outbound traffic come from? | The node's IP, or the cloud NAT gateway's Elastic IP in a private subnet |
| How do I give a service a stable egress IP for a partner allow-list? | Route private subnets through a NAT gateway with a known Elastic IP; or an egress gateway (Cilium Egress Gateway, Istio egress, Calico egress); or a dedicated node pool |
| Who masquerades? | ip-masq-agent (GKE), the AWS VPC CNI (AWS_VPC_K8S_CNI_EXTERNALSNAT), Cilium (bpf.masquerade), Calico (natOutgoing), flannel (--ip-masq) |
Why do some pod IPs look like 10.x to a database in the same VPC? | VPC-native CNIs give pods real VPC addresses; no SNAT inside the VPC |
NAT in the cloud Important
In plain words: In a private subnet, instances have only private addresses. To reach the internet they go through a NAT gateway, which has a public (Elastic) IP. Public instances use an Internet gateway, which does 1:1 NAT for them.
Common misunderstanding: "The NAT gateway also lets the internet in." No: a NAT gateway only supports outbound-initiated flows. Inbound goes through a load balancer or a public instance.
Definition: AWS "NAT gateway" lets private subnets reach out; the Internet gateway "logically provides the one-to-one NAT on behalf of your instance". The NAT gateway pricing page's own worked example bills "a charge of $0.045 per hour" for the gateway and "$0.045" for each GB processed in its example region; the data processing charge comes on top of normal data transfer, which is why a chatty private subnet pulling container images and calling SaaS APIs through NAT can cost real money.
| Cloud | Outbound from private subnet | Inbound | Egress IP |
|---|---|---|---|
| AWS | NAT gateway (zonal or regional), or NAT instance | ALB/NLB, public IP + Internet gateway | Elastic IP on the NAT gateway |
| GCP | Cloud NAT (managed, no gateway VM) | Load balancers, external IP | Reserved external IPs on Cloud NAT |
| Azure | NAT Gateway (per subnet) / default outbound | Load balancer, public IP | Public IP on the NAT Gateway |
| DigitalOcean / Hetzner | Droplet public IP; NAT via a gateway server or NAT gateway (VPC) | Floating / Reserved IP | The reserved IP |
| Cost lever | What to do |
|---|---|
| Per-GB processing on NAT | Gateway VPC endpoints (S3, DynamoDB), interface endpoints (PrivateLink) for AWS APIs, an ECR pull-through cache |
| One NAT per AZ | Reliability vs hourly fee; do not route AZ-a traffic through AZ-b's NAT (cross-AZ transfer cost) |
| Port exhaustion | AWS: "Each new IPv4 address can support up to 55,000 concurrent connections" on a NAT gateway; add addresses, reuse connections, watch the IdleTimeoutCount CloudWatch metric and close idle connections |
| IPv6 | Use an egress-only internet gateway: no NAT, no per-GB NAT charge |
Lost client IPs: X-Forwarded-For and PROXY protocol Must-know
In plain words: After NAT or any proxy, the server sees the last hop's address. To learn the real client, the last hop must tell you, and you must only believe it from hops you control.
Common misunderstanding: "X-Forwarded-For is the client IP." It is a list the client can write into. The leftmost entry is attacker-controlled; only the entries added by YOUR proxies are trustworthy.
Definition: NAT itself cannot return the client address to the application (it rewrites in the other direction, and for DNAT with SNAT the source is already replaced). Two application-level fixes: the HTTP header X-Forwarded-For (a de facto header, standardised as Forwarded, RFC 7239) appended by each proxy: X-Forwarded-For: <client>, <proxy1>, <proxyN>; and the PROXY protocol, which, in the spec's words, exists because "relaying TCP connections through proxies generally involves a loss of the original TCP connection parameters such as source and destination addresses, ports".
Client 198.51.100.23 -> CDN 203.0.113.50 -> LB 10.0.0.5 -> app 10.0.2.8
App receives: REMOTE_ADDR=10.0.0.5 X-Forwarded-For: 198.51.100.23, 203.0.113.50
Trusted proxies configured: 10.0.0.0/8 and the CDN ranges.
Right-to-left: 203.0.113.50 (trusted CDN) -> next 198.51.100.23 is not trusted -> that is the client.
Forged: X-Forwarded-For: 1.2.3.4, 198.51.100.23, 203.0.113.50 -> still 198.51.100.23.| Mechanism | Layer | Format | Spoof risk | Where used |
|---|---|---|---|---|
X-Forwarded-For | HTTP | Comma list, leftmost = client | High unless right-to-left with trusted hops | nginx, ALB, Cloudflare (CF-Connecting-IP), most CDNs |
Forwarded (RFC 7239) | HTTP | for=198.51.100.23;proto=https | Same | Newer proxies |
X-Real-IP | HTTP | Single value | Same | nginx |
| PROXY protocol v1 | TCP | One text line PROXY TCP4 src dst sport dport\r\n | Only accept from trusted peers | HAProxy, nginx, AWS NLB, Envoy |
| PROXY protocol v2 | TCP | Binary header + TLVs (12-byte signature) | Same | AWS NLB, HAProxy |
externalTrafficPolicy: Local | L3/L4 | No header: source preserved | None | Kubernetes NodePort / LB |
Direct Server Return / transparent proxy (TPROXY) | L3 | Source preserved | None | L4 load balancers |
| Cloud LB preserving source IP | L4 | NLB with client IP preservation | None | AWS NLB targets by instance ID |
Go: read the real IP from a PROXY v1 header, but only from a trusted peer. The snippet's run:
// Reading the real client IP from a PROXY protocol v1 header, safely: the
// header is only honoured when the TCP peer is a proxy we trust. Anyone else
// could forge it and pretend to be any address.
package main
import (
"bufio"
"errors"
"fmt"
"net"
"net/netip"
"strconv"
"strings"
)
var trusted = []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8"), netip.MustParsePrefix("10.0.0.0/8")}
func isTrusted(a netip.Addr) bool {
for _, p := range trusted {
if p.Contains(a.Unmap()) {
return true
}
}
return false
}
// ParseV1 parses "PROXY TCP4 src dst sport dport\r\n" (max 107 bytes per the spec).
func ParseV1(line string) (src netip.AddrPort, err error) {
if len(line) > 107 {
return src, errors.New("header longer than 107 bytes")
}
f := strings.Fields(strings.TrimRight(line, "\r\n"))
if len(f) == 2 && f[0] == "PROXY" && f[1] == "UNKNOWN" {
return src, errors.New("UNKNOWN: use the socket address")
}
if len(f) != 6 || f[0] != "PROXY" || (f[1] != "TCP4" && f[1] != "TCP6") {
return src, errors.New("malformed PROXY line")
}
ip, err := netip.ParseAddr(f[2])
if err != nil {
return src, err
}
port, err := strconv.ParseUint(f[4], 10, 16)
if err != nil {
return src, err
}
return netip.AddrPortFrom(ip, uint16(port)), nil
}
// ClientAddr returns the address to log, rate-limit and authorise on.
func ClientAddr(conn net.Conn, r *bufio.Reader) (netip.AddrPort, string, error) {
peer := conn.RemoteAddr().(*net.TCPAddr).AddrPort()
if !isTrusted(peer.Addr()) {
return peer, "socket peer (not a trusted proxy, header ignored)", nil
}
line, err := r.ReadString('\n')
if err != nil {
return peer, "", err
}
src, err := ParseV1(line)
if err != nil {
return peer, "", err
}
return src, "PROXY header from trusted proxy " + peer.Addr().String(), nil
}
func main() {
ln, _ := net.Listen("tcp", "127.0.0.1:0")
defer ln.Close()
go func() {
c, _ := net.Dial("tcp", ln.Addr().String())
fmt.Fprint(c, "PROXY TCP4 198.51.100.23 203.0.113.7 54321 443\r\nGET / HTTP/1.1\r\n\r\n")
c.Close()
}()
conn, _ := ln.Accept()
r := bufio.NewReader(conn)
addr, why, err := ClientAddr(conn, r)
fmt.Println("client:", addr, "| via:", why, "| err:", err)
for _, bad := range []string{"PROXY TCP4 not-an-ip 1.1.1.1 1 2\r\n", "GET / HTTP/1.1\r\n", "PROXY UNKNOWN\r\n"} {
_, err := ParseV1(bad)
fmt.Printf("%q -> %v\n", bad, err)
}
}client: 198.51.100.23:54321 | via: PROXY header from trusted proxy 127.0.0.1 | err: <nil>
"PROXY TCP4 not-an-ip 1.1.1.1 1 2\r\n" -> ParseAddr("not-an-ip"): unable to parse IP
"GET / HTTP/1.1\r\n" -> malformed PROXY line
"PROXY UNKNOWN\r\n" -> UNKNOWN: use the socket addressAnd the HTTP side, walking X-Forwarded-For from the right:
// Reading the real client IP from X-Forwarded-For safely.
// The header is a list appended to by every proxy: "client, proxy1, proxy2".
// The leftmost entries are controlled by the CLIENT and can be forged. Walk
// from the RIGHT, skipping only addresses of proxies you operate.
package main
import (
"fmt"
"net"
"net/http"
"net/netip"
"strings"
)
type Resolver struct{ Trusted []netip.Prefix }
func (r Resolver) trusted(a netip.Addr) bool {
for _, p := range r.Trusted {
if p.Contains(a) {
return true
}
}
return false
}
// ClientIP returns the first address, from the right, that is not a trusted proxy.
func (r Resolver) ClientIP(req *http.Request) netip.Addr {
host, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
host = req.RemoteAddr
}
peer, err := netip.ParseAddr(host)
if err != nil {
return netip.Addr{}
}
peer = peer.Unmap()
if !r.trusted(peer) {
return peer // directly connected stranger: ignore any header they sent
}
var chain []string
for _, v := range req.Header.Values("X-Forwarded-For") {
chain = append(chain, strings.Split(v, ",")...)
}
for i := len(chain) - 1; i >= 0; i-- {
a, err := netip.ParseAddr(strings.TrimSpace(chain[i]))
if err != nil {
return peer // garbage in the chain: do not guess
}
a = a.Unmap()
if !r.trusted(a) {
return a
}
}
return peer
}
func main() {
res := Resolver{Trusted: []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")}}
cases := []struct{ remote, xff string }{
{"10.0.0.5:4000", "198.51.100.23"},
{"10.0.0.5:4000", "1.2.3.4, 198.51.100.23"}, // client forged the first hop
{"10.0.0.5:4000", "198.51.100.23, 10.0.1.9"}, // two trusted proxies
{"203.0.113.50:5000", "1.2.3.4"}, // no proxy in front: header is a lie
{"10.0.0.5:4000", "not-an-ip"},
{"10.0.0.5:4000", ""},
}
for _, c := range cases {
req, _ := http.NewRequest("GET", "http://x/", nil)
req.RemoteAddr = c.remote
if c.xff != "" {
req.Header.Set("X-Forwarded-For", c.xff)
}
fmt.Printf("peer=%-18s XFF=%-28q -> %v\n", c.remote, c.xff, res.ClientIP(req))
}
}peer=10.0.0.5:4000 XFF="198.51.100.23" -> 198.51.100.23
peer=10.0.0.5:4000 XFF="1.2.3.4, 198.51.100.23" -> 198.51.100.23
peer=10.0.0.5:4000 XFF="198.51.100.23, 10.0.1.9" -> 198.51.100.23
peer=203.0.113.50:5000 XFF="1.2.3.4" -> 203.0.113.50
peer=10.0.0.5:4000 XFF="not-an-ip" -> 10.0.0.5
peer=10.0.0.5:4000 XFF="" -> 10.0.0.5DHCP: the DORA exchange Must-know
In plain words: A device with no address shouts "is there a DHCP server?" (Discover); a server answers with a proposal (Offer); the device says "I'll take that one" (Request); the server confirms (Acknowledge). The result is an address, gateway, DNS and a lease time.
Common misunderstanding: "DHCP gives the address forever." It is a lease: it expires and the device must renew. "DHCP is TCP/HTTP." It is UDP: client port 68, server port 67, with broadcasts, because the client has no IP yet.
Definition: RFC 2131. The standard text of step 1: "The client broadcasts a DHCPDISCOVER message on its local physical subnet" and "BOOTP relay agents may pass the message on to DHCP servers not on the same physical subnet". The message format is the BOOTP header (236 bytes, fixed) + the 4-byte magic cookie 63 82 53 63 + TLV options.
Byte-level: the snippet builds a DISCOVER, hex-dumps the fixed header and decodes the options it contains.
// Build a DHCPDISCOVER (RFC 2131) byte by byte and decode its options.
// Shows why DHCP is "BOOTP plus options": a fixed 236-byte header, a magic
// cookie, then TLV options.
package main
import (
"encoding/binary"
"encoding/hex"
"fmt"
"net"
)
const (
optSubnet = 1
optRouter = 3
optDNS = 6
optDomain = 15
optMTU = 26
optReqIP = 50
optLease = 51
optMsgType = 53
optServerID = 54
optParamReq = 55
optClientID = 61
optEnd = 255
)
func discover(mac net.HardwareAddr, xid uint32) []byte {
b := make([]byte, 236)
b[0] = 1 // op: BOOTREQUEST
b[1] = 1 // htype: Ethernet
b[2] = 6 // hlen
binary.BigEndian.PutUint32(b[4:], xid)
binary.BigEndian.PutUint16(b[10:], 0x8000) // flags: BROADCAST (client has no IP yet)
copy(b[28:], mac) // chaddr
b = append(b, 0x63, 0x82, 0x53, 0x63) // magic cookie
b = append(b, optMsgType, 1, 1) // DHCPDISCOVER
b = append(b, optClientID, 7, 1)
b = append(b, mac...)
b = append(b, optParamReq, 5, optSubnet, optRouter, optDNS, optDomain, optMTU)
return append(b, optEnd)
}
var names = map[byte]string{1: "subnet-mask", 3: "router", 6: "dns-server", 15: "domain-name", 26: "interface-mtu",
50: "requested-ip", 51: "lease-time", 53: "message-type", 54: "server-id", 55: "param-request-list", 61: "client-id"}
func decodeOptions(pkt []byte) {
i := 240 // 236-byte BOOTP header + 4-byte cookie
for i < len(pkt) && pkt[i] != optEnd {
code, l := pkt[i], int(pkt[i+1])
fmt.Printf(" option %3d (%s) len=%d data=%x\n", code, names[code], l, pkt[i+2:i+2+l])
i += 2 + l
}
}
func main() {
mac, _ := net.ParseMAC("02:42:ac:11:00:02")
pkt := discover(mac, 0xdeadbeef)
fmt.Printf("DISCOVER is %d bytes; fixed header + cookie:\n%s", len(pkt), hex.Dump(pkt[:48]))
fmt.Printf("cookie at offset 236: %x\n", pkt[236:240])
decodeOptions(pkt)
}DISCOVER is 260 bytes; fixed header + cookie:
00000000 01 01 06 00 de ad be ef 00 00 80 00 00 00 00 00 |................|
00000010 00 00 00 00 00 00 00 00 00 00 00 00 02 42 ac 11 |.............B..|
00000020 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
cookie at offset 236: 63825363
option 53 (message-type) len=1 data=01
option 61 (client-id) len=7 data=010242ac110002
option 55 (param-request-list) len=5 data=0103060f1aOffsets: byte 0 01 = op (BOOTREQUEST), 01 = htype Ethernet, 06 = hlen, 00 = hops; de ad be ef = xid (transaction ID that matches replies to requests); 00 00 = secs; 80 00 = flags with the BROADCAST bit set (the client cannot receive unicast before it has an IP); then ciaddr, yiaddr, siaddr, giaddr (all zero in a DISCOVER) and from byte 28 the 16-byte chaddr (client MAC).
Now the real thing. I ran dnsmasq as the server on a throwaway Docker network and udhcpc as the client, with tcpdump -n -v on the server side (trimmed to the essentials):
udhcpc: broadcasting discover
udhcpc: broadcasting select for 10.99.0.150, server 10.99.0.2
udhcpc: lease of 10.99.0.150 obtained from 10.99.0.2, lease time 120
0.0.0.0.68 > 255.255.255.255.67: BOOTP/DHCP, Request from 9a:44:10:cf:86:b4, xid 0x875a3927
DHCP-Message (53), length 1: Discover
Parameter-Request (55): Subnet-Mask (1), Default-Gateway (3), Domain-Name-Server (6), Hostname (12), Domain-Name (15), BR (28), NTP (42)
Client-ID (61): ether 9a:44:10:cf:86:b4
10.99.0.2.67 > 10.99.0.150.68: BOOTP/DHCP, Reply, xid 0x875a3927
Your-IP 10.99.0.150 Server-IP 10.99.0.2
DHCP-Message (53): Offer Server-ID (54): 10.99.0.2 Lease-Time (51): 120
RN (58): 60 RB (59): 105 Subnet-Mask (1): 255.255.255.0 Domain-Name (15): "lab.test"
Domain-Name-Server (6): 10.99.0.53 Default-Gateway (3): 10.99.0.1
0.0.0.0.68 > 255.255.255.255.67: BOOTP/DHCP, Request from 9a:44:10:cf:86:b4, xid 0x875a3927
DHCP-Message (53): Request Requested-IP (50): 10.99.0.150 Server-ID (54): 10.99.0.2
10.99.0.2.67 > 10.99.0.150.68: BOOTP/DHCP, Reply, xid 0x875a3927
Your-IP 10.99.0.150 DHCP-Message (53): ACK Lease-Time (51): 120 RN (58): 60 RB (59): 105Things visible only in the real capture: the DISCOVER and REQUEST come from 0.0.0.0 to 255.255.255.255 (broadcast), while the OFFER and ACK are unicast to the offered address (10.99.0.2.67 > 10.99.0.150.68, since the client set no broadcast flag and the server could reach the MAC directly); the xid stays the same through the whole exchange; the first DISCOVER was repeated after 3 seconds (secs 3) because the client retransmits until it gets an OFFER; and RN/RB are the renewal (T1 = 60 s) and rebinding (T2 = 105 s) timers, 50% and 87.5% of the 120 s lease. The client also asked for option 28 (broadcast) and 42 (NTP) that this server did not have. It did not ask for option 26 (interface MTU), so dnsmasq did not send the MTU configured on the server: options are sent only when requested (or forced with dhcp-option-force).
On macOS the lease is visible with ipconfig getpacket en0 (real output from this machine on a phone hotspot, MAC masked):
op = BOOTREPLY
xid = 0xa09a3e49
ciaddr = 10.84.50.174
yiaddr = 10.84.50.174
siaddr = 10.84.50.254
chaddr = xx:xx:xx:xx:xx:xx
options:
dhcp_message_type (uint8): ACK 0x5
server_identifier (ip): 10.84.50.254
lease_time (uint32): 0xe0f # 3599 s
renewal_t1_time_value (uint32): 0x707 # 1799 s
rebinding_t2_time_value (uint32): 0xc4d # 3149 s
subnet_mask (ip): 255.255.255.0
router (ip_mult): {10.84.50.254}
domain_name_server (ip_mult): {10.84.50.254}| Client tool | Show the lease | Renew | Release |
|---|---|---|---|
| macOS | ipconfig getpacket en0 | sudo ipconfig set en0 DHCP | System Settings, "Renew DHCP Lease" |
| Linux NetworkManager | nmcli -f DHCP4 device show eth0 | nmcli device reapply eth0 | nmcli connection down id <name> |
Linux dhclient | /var/lib/dhcp/dhclient.leases | sudo dhclient -v eth0 | sudo dhclient -r eth0 |
| systemd-networkd | networkctl status eth0 | networkctl renew eth0 | networkctl reconfigure eth0 |
dhcpcd | dhcpcd -U eth0 | dhcpcd -n eth0 | dhcpcd -k eth0 |
| BusyBox | udhcpc -i eth0 -f -n | rerun | -R |
| Windows | ipconfig /all | ipconfig /renew | ipconfig /release |
Leases, renewals and options Must-know
In plain words: A lease is a rental. Halfway through, the device asks the same server to extend it. If that fails it asks anyone. If everything fails it gives up the address at the end.
Common misunderstanding: "My server's IP will not change after a reboot." It usually will not (the server remembers by MAC or client ID), but it can: when the lease expired while the machine was off, the pool was exhausted, the lease database was wiped, or the NIC changed.
Definition: RFC 2131: T1 "defaults to (0.5 * duration_of_lease)" and T2 to "(0.875 * duration_of_lease)". At T1 the client unicasts a REQUEST to the server that gave the lease; at T2 it broadcasts to any server; at expiry it must stop using the address and restart from DISCOVER.
lease 3600 s (T1 = 1800 s, T2 = 3150 s)
t=0 ACK address configured
t=1800 REQUEST (unicast to server) -> ACK lease restarts, timers reset
(server unreachable at T1)
t=3150 REQUEST (broadcast) -> any server may ACK/NAK
t=3600 lease expires -> deconfigure interface, DISCOVER again
NAK: server says "that address is no longer valid" -> client restarts at DISCOVER| Option (code) | Name | What it configures | Notes |
|---|---|---|---|
| 1 | Subnet mask | The netmask | Use with option 3 |
| 3 | Router | Default gateway | List, first preferred |
| 6 | Domain name server | DNS resolvers | Becomes /etc/resolv.conf |
| 12 | Hostname | Client's name | Used for DDNS, DNS registration |
| 15 | Domain name | Search domain | lab.test in the lab |
| 26 | Interface MTU | Link MTU | Needed for overlays and tunnels; only sent if requested |
| 28 | Broadcast address | Derivable from address and mask | |
| 42 | NTP servers | Time sync | |
| 43 | Vendor specific | e.g. ANDROID_METERED on hotspots | Opaque |
| 50 | Requested IP | Chosen address in REQUEST | |
| 51 | Lease time | Seconds | |
| 53 | DHCP message type | 1 Discover, 2 Offer, 3 Request, 4 Decline, 5 ACK, 6 NAK, 7 Release, 8 Inform | |
| 54 | Server identifier | Which server | Picks one offer |
| 55 | Parameter request list | Which options the client wants | |
| 58 / 59 | T1 / T2 | Renewal / rebinding | |
| 60 / 61 | Vendor class / client identifier | Identification | Used for reservations |
| 66 / 67 | TFTP server / bootfile | PXE netboot | |
| 82 | Relay agent information | Circuit and remote ID | Added by relays (RFC 3046) |
| 119 | Domain search list | Several search domains | |
| 121 | Classless static routes | Extra routes (VPN/split) | |
| 252 | WPAD | Proxy auto-config | Security-sensitive |
Reservations, relay agents, Docker and the cloud Important
In plain words: A reservation tells the DHCP server "always give this MAC the same address". A relay forwards broadcasts across routers so one server can serve many subnets. Docker and the cloud do not use DHCP the way a LAN does.
Common misunderstanding: "A DHCP reservation is a static IP." A static IP is configured on the host and the server does not know about it, so it can hand the same address to someone else unless it is outside the pool. A reservation is configured on the server; the host still uses DHCP.
| Topic | How it works | Product detail |
|---|---|---|
| Reservation (static lease) | Server maps MAC or client ID to a fixed IP | dnsmasq: dhcp-host=aa:bb:cc:dd:ee:ff,10.0.0.50,web1; ISC Kea reservations; router UI "Static DHCP"; Windows DHCP "Reservation" |
| Exclusion / pool | Addresses the server never hands out | Put static servers outside dhcp-range |
| Relay agent | A router with ip helper-address / dhcrelay receives the broadcast, sets giaddr and unicasts to the DHCP server | Adds option 82 (RFC 3046); server selects the subnet by giaddr |
| Rogue DHCP | An unauthorised server (a plugged-in home router) answers faster and hands out a wrong gateway or DNS: a man-in-the-middle | DHCP snooping on switches (trusted ports), 802.1X, monitor with nmap --script broadcast-dhcp-discover |
| DHCP in Docker | None: Docker's IPAM assigns the container IP from the network subnet; the container has a static address inside its namespace | docker network create --subnet 10.99.0.0/24; --ip for fixed addresses; macvlan/ipvlan networks can use an external DHCP only via third-party plugins |
| DHCP in VMs | The hypervisor or virtual network runs one | libvirt virbr0 uses dnsmasq; VirtualBox NAT has a built-in server; Vagrant NAT (10.0.2.15) |
| DHCP in the cloud | The VPC's virtual DHCP: the instance runs a normal DHCP client, but the address is assigned by the control plane, tied to the ENI; metadata (169.254.169.254) delivers user data and credentials | AWS "DHCP option sets" (DNS servers, domain, NTP); GCP and Azure similar |
| Kubernetes | Pod IPs come from the CNI's IPAM (not DHCP); nodes use cloud DHCP | host-local, whereabouts, cloud VPC IPAM |
DHCPv6 vs SLAAC Good to know
In plain words: IPv6 hosts can build their own address from a router's advertised prefix (SLAAC) or ask a server (DHCPv6), or both.
Common misunderstanding: "IPv6 does not need DHCP." SLAAC gives an address and gateway but not DNS (well, RDNSS exists); DHCPv6 can add DNS, NTP and prefixes. Many networks run both.
Definition: SLAAC (Stateless Address Autoconfiguration, RFC 4862): a router sends Router Advertisements (ICMPv6) with a prefix, and the host appends an interface identifier (random "privacy" address, or EUI-64). DHCPv6 (RFC 8415) uses UDP 546 (client) and 547 (server), a different message set (Solicit, Advertise, Request, Reply) and DUIDs instead of MACs. The RA flags M (managed: use DHCPv6 for addresses) and O (other: use DHCPv6 for options only) tell the host which to use.
| DHCPv4 | SLAAC | DHCPv6 stateful | DHCPv6 stateless | |
|---|---|---|---|---|
| Gives address | Yes | Yes, host-generated | Yes, from a pool | No |
| Gives gateway | Option 3 | Router Advertisement | No (RA does) | No (RA does) |
| Gives DNS | Option 6 | RDNSS option or none | Yes | Yes |
| Needs server | Yes | No, only a router | Yes | Yes (options only) |
| Tracking by server | Yes | No | Yes | No |
| IPv6 and NAT | Usually no NAT: global addresses |
IPv6 reduces the need for NAT (every host can have a global address, firewalls do the filtering), but NAT66/NPTv6 and NAT64/DNS64 (IPv6-only clients reaching IPv4 servers) exist and are common on mobile networks and in IPv6-only Kubernetes clusters.
Addressing choices: static vs dynamic, ephemeral vs fixed ports
In plain words: Servers want stable addresses and ports; clients do not care. NAT and firewalls use that asymmetry.
Common misunderstanding: "Opening port 443 on the firewall also opens the client's source port." A client's source port is ephemeral (typically 32768-60999 on Linux, 49152-65535 by IANA), chosen per connection; a stateful firewall allows the reply by looking the flow up in conntrack, not by opening the port.
| Choice | Use for | Why |
|---|---|---|
| Static address configured on the host | Routers, DNS servers, DHCP servers, bare-metal databases | Must be reachable even if DHCP is down |
| DHCP reservation | Printers, NAS, dev boxes, Raspberry Pi | Central control, host stays DHCP |
| Dynamic DHCP | Laptops, phones, IoT guests | Zero configuration |
| Cloud private IP | VMs | Assigned by the VPC, stable for the instance's life; use DNS names |
| DNS name instead of IP | Everything an app connects to | Survives lease and IP changes |
| Fixed (well-known) port | Servers: 22, 80, 443, 5432 | Clients must know it |
| Ephemeral port | Clients' source | Chosen from net.ipv4.ip_local_port_range (32768 60999 default) |
| NAT port range | Per NAT gateway | The gateway chooses; exhaustion limits connections |
Stateful firewall + NAT, both directions
outbound 192.168.1.10:51000 -> 93.184.216.34:443 conntrack ESTABLISHED row created
inbound 93.184.216.34:443 -> 203.0.113.7:40000 matches the row: allowed, even though no rule opens :40000
inbound 198.51.100.99:443 -> 203.0.113.7:40000 different remote: no row: droppedMechanics
Seeing NAT: commands and what they print
| What to look at | Command (Linux) | Notes |
|---|---|---|
| NAT rules, iptables syntax | sudo iptables -t nat -L -n -v --line-numbers or -S | -n stops reverse DNS; -v shows packet counters |
| All nftables rules | sudo nft list ruleset | iptables-nft rules appear here with a warning |
| The nat table only | sudo nft list table ip nat | Only exists if something created it |
| Live conntrack table | sudo conntrack -L, conntrack -L -p tcp --dport 8080 | From conntrack-tools |
| Count and stats | conntrack -C, conntrack -S | Compare -C with nf_conntrack_max |
| Watch events | sudo conntrack -E | [NEW], [UPDATE], [DESTROY] |
| Without the tool | cat /proc/net/nf_conntrack | |
| Is forwarding on? | sysctl net.ipv4.ip_forward | NAT routers need 1 |
| Which gateway | ip route, ip addr | Default route shows the next hop |
| From inside a container | ip route, cat /etc/resolv.conf, curl ifconfig.me | Shows the container IP and the NAT-ed public IP |
| Capture NAT in action | sudo tcpdump -ni any host 93.184.216.34 | Compare the packet on the inside and outside interfaces |
| macOS | ipconfig getpacket en0, netstat -rn, sudo pfctl -s nat, sudo pfctl -s state | pf replaces iptables |
| Windows | Get-NetNat, netsh interface portproxy show all |
Real iptables -t nat -S (Docker Desktop VM) is in Port forwarding; real conntrack rows are in the table section. From inside the published container (docker exec natlab ip route):
default via 172.17.0.1 dev eth0
172.17.0.0/16 dev eth0 scope link src 172.17.0.2and the masquerade of a container's outbound curl http://example.com/ in conntrack (public address trimmed): the original direction has the container as source, the reply direction is addressed to the VM, not to the container:
tcp 6 102 TIME_WAIT src=172.17.0.2 dst=198.18.1.39 sport=47340 dport=80 src=198.18.1.39 dst=192.168.65.3 sport=80 dport=47340 [ASSURED]Netfilter order of events
packet in
raw PREROUTING (can mark NOTRACK)
conntrack lookup / create
mangle PREROUTING
nat PREROUTING <- DNAT (port forwards, Docker -p, kube-proxy)
routing decision
local -> filter INPUT -> process
other -> filter FORWARD -> mangle POSTROUTING -> nat POSTROUTING <- SNAT / MASQUERADE -> out
local process out -> raw OUTPUT -> nat OUTPUT (DNAT for local clients) -> routing -> POSTROUTINGWhy this order matters: DNAT happens BEFORE routing, so the routing table decides where the rewritten packet goes; the filter FORWARD chain sees the already-rewritten destination (172.17.0.2:80, not :8080); SNAT happens after everything, so filter rules see the original source.
What each product does
| Product | NAT implementation | Port forward | Where the table lives | Notable default |
|---|---|---|---|---|
| Linux (iptables / nftables) | netfilter + conntrack | DNAT + FORWARD accept | kernel | nf_conntrack_max = 262144 on the lab VM |
| Docker | iptables/nft rules per bridge | -p, rules in DOCKER chain + docker-proxy | host conntrack | Masquerade for every bridge subnet; hairpin rule per port |
| Kubernetes | kube-proxy iptables or IPVS, or Cilium eBPF | NodePort, LoadBalancer | node conntrack / eBPF maps | externalTrafficPolicy: Cluster |
| AWS NAT gateway | Managed, per-AZ | None (outbound only) | Service-side | Connection and port limits per destination |
| AWS Internet gateway | 1:1 NAT for public IP / Elastic IP | Security groups + route | Service-side | |
| GCP Cloud NAT | Software-defined, no VM | None | Service-side | Min ports per VM configurable |
| Home router (Linux/BSD based) | netfilter or pf | UI | Router RAM | UDP timeout 30-60 s, table of a few thousand entries |
| macOS | pf | pfctl anchors | kernel | Internet Sharing uses bootpd for DHCP and pf for NAT |
| Windows | WinNAT (Get-NetNat) | netsh portproxy / NAT static mapping | kernel | Used by WSL2 and Hyper-V default switch |
| Cisco IOS | NAT/PAT | ip nat inside source static | router | PAT is overload |
| pfSense / OPNsense | pf | Firewall > NAT > Port Forward | firewall | NAT reflection optional |
Solving the classic problems
| Problem | Solution | How | Cost / limitation |
|---|---|---|---|
| Reach an inside service from outside | Port forward / DNAT | Rule on the edge device that owns the public IP | Needs a public IP; one service per port per IP |
| Same, but behind CGNAT or double NAT | Reverse tunnel | cloudflared, ngrok, WireGuard or SSH -R to a VPS | Depends on a relay; latency; vendor terms |
| Application needs the real client IP | TrustProxies / right-to-left XFF; PROXY protocol; externalTrafficPolicy: Local | See Lost client IPs | Must define which hops are trusted |
| Inside client cannot reach the inside server through its public name | Split-horizon DNS or hairpin NAT | Resolve to the private IP internally | Two views of DNS to maintain |
| Long-lived idle connection dies through NAT | Keepalive shorter than NAT timeout | PersistentKeepalive = 25, TCP keepalive, WebSocket ping | A little traffic |
| NAT table full | Raise nf_conntrack_max, lower timeouts, reuse connections, NOTRACK for known traffic | sysctl, pooling | Memory per entry |
| Hard-coded IP breaks after DHCP renewal | Name instead of IP, or DHCP reservation | DNS / dhcp-host= | DNS TTL discipline |
| Peers both behind NAT | STUN + ICE + TURN | WebRTC, Tailscale | A relay costs bandwidth |
| Stable outbound IP for partner allow-lists | NAT gateway with Elastic IP / egress gateway | Route private subnets through it | Per-hour and per-GB cost |
A small TCP port forwarder in Go
NAT does forwarding in the kernel; this does it in user space (what socat, docker-proxy and ssh -L do). The backend sees the forwarder as the client, so the real address is lost unless the forwarder prepends a PROXY protocol header.
// A tiny TCP port forwarder: what `socat TCP-LISTEN:8080,fork TCP:10.0.0.5:80`,
// docker-proxy and an SSH -L tunnel do. It is a layer-4 proxy, not NAT: the
// backend sees THIS process as the client, so the real client IP is lost
// unless we prepend a PROXY protocol v1 header (-proxy-protocol).
package main
import (
"context"
"flag"
"fmt"
"io"
"log"
"net"
"os"
"os/signal"
"sync"
"time"
)
func main() {
listen := flag.String("listen", "127.0.0.1:8080", "address to accept on")
target := flag.String("target", "127.0.0.1:9000", "backend to dial")
proxyProto := flag.Bool("proxy-protocol", false, "prepend a PROXY v1 header with the real client address")
flag.Parse()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
ln, err := net.Listen("tcp", *listen)
if err != nil {
log.Fatal(err)
}
go func() { <-ctx.Done(); ln.Close() }()
log.Printf("forwarding %s -> %s (proxy-protocol=%v)", *listen, *target, *proxyProto)
var wg sync.WaitGroup
for {
c, err := ln.Accept()
if err != nil {
break
}
wg.Add(1)
go func() {
defer wg.Done()
handle(c, *target, *proxyProto)
}()
}
wg.Wait()
}
func handle(client net.Conn, target string, proxyProto bool) {
defer client.Close()
backend, err := net.DialTimeout("tcp", target, 3*time.Second)
if err != nil {
log.Printf("dial %s: %v", target, err)
return
}
defer backend.Close()
if proxyProto {
src := client.RemoteAddr().(*net.TCPAddr)
dst := client.LocalAddr().(*net.TCPAddr)
fam := "TCP4"
if src.IP.To4() == nil {
fam = "TCP6"
}
// PROXY protocol v1: one text line before any payload.
fmt.Fprintf(backend, "PROXY %s %s %s %d %d\r\n", fam, src.IP, dst.IP, src.Port, dst.Port)
}
done := make(chan struct{}, 2)
pipe := func(dst, src net.Conn) {
io.Copy(dst, src)
// Half-close so the peer sees EOF but can still finish its reply.
if tc, ok := dst.(*net.TCPConn); ok {
tc.CloseWrite()
}
done <- struct{}{}
}
go pipe(backend, client)
go pipe(client, backend)
<-done
<-done
}Real run: a Python http.server on :9000, the forwarder on :8081, then curl through it; and with -proxy-protocol in front of a nc -l listener, what the backend receives is a one-line header before the payload:
$ /tmp/fwd -listen 127.0.0.1:8081 -target 127.0.0.1:9000
$ curl -s -o /dev/null -w "via forwarder: %{http_code}\n" http://127.0.0.1:8081/
via forwarder: 200
$ /tmp/fwd -listen 127.0.0.1:8082 -target 127.0.0.1:9100 -proxy-protocol
PROXY TCP4 127.0.0.1 127.0.0.1 56172 8082
helloStoring and classifying client addresses (SQL)
Keep real client addresses in a native address type and test them against the special ranges. PostgreSQL's inet type and the <<= ("is contained within or equals") operator make CGNAT and private-range checks one line:
CREATE TABLE login_events (
id bigserial PRIMARY KEY,
user_id bigint NOT NULL,
client_ip inet NOT NULL, -- the REAL client address after trusted-proxy resolution
proxy_ip inet, -- the TCP peer (load balancer / NAT gateway), for audits
at timestamptz NOT NULL DEFAULT now()
);
-- Which logins came from carrier-grade NAT, where one IP = many people?
SELECT client_ip, count(DISTINCT user_id) AS users
FROM login_events
WHERE client_ip <<= '100.64.0.0/10'
GROUP BY client_ip
ORDER BY users DESC;
-- Detect a misconfigured proxy: every row has the same (private) client IP.
SELECT client_ip, count(*) FROM login_events
WHERE at > now() - interval '1 hour'
GROUP BY client_ip HAVING count(*) > 1000;
-- Private or reserved addresses must never be "client" addresses on the public internet.
SELECT count(*) FROM login_events
WHERE client_ip <<= ANY (ARRAY['10.0.0.0/8','172.16.0.0/12','192.168.0.0/16','127.0.0.0/8']::inet[]);Laravel and PHP behind NAT
Laravel reads the client address from the TCP peer unless it is told which proxies to trust. The Laravel docs explain the symptom: behind a load balancer that terminates TLS the app sees plain HTTP on port 80 and generates insecure links; "you may enable the Illuminate\Http\Middleware\TrustProxies middleware ... specified using the trustProxies middleware method in your application's bootstrap/app.php file". In Laravel 13 the configuration is:
<?php
// bootstrap/app.php (Laravel 13): tell the framework which hops are YOUR proxies.
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
// Trust only the load balancer / ingress ranges, never '*' on a public host.
// 10.0.0.0/8 here is the VPC range where the load balancer lives.
$middleware->trustProxies(
at: ['10.0.0.0/8', '172.16.0.0/12'],
headers: Request::HEADER_X_FORWARDED_FOR
| Request::HEADER_X_FORWARDED_HOST
| Request::HEADER_X_FORWARDED_PORT
| Request::HEADER_X_FORWARDED_PROTO,
);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})
->create();A diagnostic route shows what the app really sees; without trustProxies, ip equals remote_addr (the load balancer), with it ip is the client:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
// Shows what the application sees behind NAT, a reverse proxy or a load balancer.
class WhoAmIController extends Controller
{
public function __invoke(Request $request): JsonResponse
{
return response()->json([
// The TCP peer: the load balancer or the NAT gateway, not the user.
'remote_addr' => $request->server('REMOTE_ADDR'),
// Real client IP after TrustProxies has walked X-Forwarded-For.
'ip' => $request->ip(),
// The full chain Symfony resolved, nearest hop first.
'ips' => $request->ips(),
'raw_xff' => $request->header('X-Forwarded-For'),
'scheme' => $request->getScheme(),
'secure' => $request->isSecure(),
]);
}
}Rate limiting by real IP. If TrustProxies is missing, every request has the same ip() (the gateway), so one client's burst locks out everyone. Behind CGNAT the opposite risk exists: one IPv4 is thousands of people, so limit by user where possible, and group IPv6 by prefix:
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
class RateLimitServiceProvider extends ServiceProvider
{
public function boot(): void
{
// Key on the REAL client IP. If TrustProxies is missing, every request
// arrives from the NAT gateway or load balancer, the key is one single
// address and the whole site shares one bucket: one noisy client
// locks everyone out.
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
// Carrier-grade NAT puts thousands of subscribers behind ONE public IPv4.
// Group IPv6 clients by /64 and keep a roomier per-IP budget for IPv4.
RateLimiter::for('login', function (Request $request) {
$ip = $request->ip();
$key = str_contains($ip, ':')
? 'v6:'.substr(bin2hex(inet_pton($ip)), 0, 16) // first 8 bytes = the /64
: 'v4:'.$ip;
return [
Limit::perMinute(5)->by($key.'|'.$request->input('email')),
Limit::perMinute(30)->by($key),
];
});
}
}Webhook servers behind NAT. A laptop or office server cannot receive a provider's webhook because there is no inbound path. A tunnel dials OUT to a vendor edge and the edge forwards inbound requests down that connection: the NAT is bypassed by reversing who opens the connection. With cloudflared, a one-line quick tunnel (random trycloudflare.com URL; the Cloudflare docs say "Quick Tunnels are for testing and development") or the Compose file below; with ngrok, ngrok http 8000. Because the URL is public, verify the signature, never the source IP:
# A reverse-connection tunnel: the container dials OUT to Cloudflare, so no
# port forward and no public IP are needed. Works behind CGNAT and double NAT.
services:
app:
image: nginx:alpine
expose: ["80"]
tunnel:
image: cloudflare/cloudflared:latest
# Quick tunnel (random trycloudflare.com URL, for demos only).
command: tunnel --no-autoupdate --url http://app:80
depends_on: [app]<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
// A webhook receiver behind NAT is reached through an outbound tunnel
// (cloudflared, ngrok). The public URL is not trustworthy by itself, so verify
// a signature instead of trusting the source IP.
class WebhookController extends Controller
{
public function __invoke(Request $request): Response
{
$payload = $request->getContent();
$expected = hash_hmac('sha256', $payload, config('services.provider.webhook_secret'));
$given = (string) $request->header('X-Signature', '');
if (! hash_equals($expected, $given)) {
return response('invalid signature', 401);
}
// Acknowledge fast, process in a queue: the tunnel and the sender both time out.
dispatch(new \App\Jobs\HandleWebhook(json_decode($payload, true, 512, JSON_THROW_ON_ERROR)));
return response('', 202);
}
}And an Artisan command to tell "refused" (a host answered, nothing listens) from "no answer" (dropped by NAT, a firewall or CGNAT), to run from outside the network:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
// php artisan net:check-port 198.51.100.7 8080
// Run it from OUTSIDE the network (a VPS, a phone hotspot) to test a port forward.
class CheckPortCommand extends Command
{
protected $signature = 'net:check-port {host} {port : TCP port} {--timeout=3}';
protected $description = 'Tell connection refused from timeout (what each means for NAT and firewalls)';
public function handle(): int
{
$errno = 0;
$err = '';
$start = microtime(true);
$s = @stream_socket_client(
sprintf('tcp://%s:%d', $this->argument('host'), (int) $this->argument('port')),
$errno,
$err,
(float) $this->option('timeout'),
);
$ms = round((microtime(true) - $start) * 1000);
if ($s) {
fclose($s);
$this->info("open ({$ms} ms): the forward and the service work");
return self::SUCCESS;
}
// errno 111 = ECONNREFUSED: a host answered with RST (forward reaches a machine, nothing listens).
// errno 110 / timeout: packets were dropped silently (no forward, firewall, CGNAT, wrong IP).
$this->error($errno === 111
? "refused ({$ms} ms): reached a host, nothing listening on that port"
: "no answer ({$ms} ms, errno {$errno}): dropped by NAT, a firewall or CGNAT");
return self::FAILURE;
}
}| Laravel API | What it does | Note |
|---|---|---|
$middleware->trustProxies(at: [...], headers: ...) | Declares trusted proxy IPs/CIDRs and which X-Forwarded-* headers to believe | at: '*' trusts everyone: unsafe on a public host |
Request::ip() / $request->ip() | Real client IP after trusted-proxy resolution | Equals REMOTE_ADDR if no proxy is trusted |
$request->ips() | Full chain of client + proxies | Useful for audits |
RateLimiter::for() / Limit::perMinute()->by() | Named limiters; ->by() sets the key | Use user id first, then ip |
hash_equals() | Constant-time signature comparison | For webhooks |
php artisan serve / Octane | Listens on 127.0.0.1 / 0.0.0.0 | Bind explicitly in containers |
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Home lab with a real public IP | Port forward plus DDNS and TLS | Fail2ban, non-default SSH port, VPN for admin | Simple, but exposed to scans |
| Home lab behind CGNAT | Outbound tunnel (cloudflared, Tailscale, WireGuard to a VPS) | Or ask the ISP for a public IP / use IPv6 | Inbound is impossible |
| Webhook development | cloudflared / ngrok quick tunnel | Signature verification | Public URL without router changes |
| Production behind a load balancer | TrustProxies with the LB's CIDR | PROXY protocol on L4 LBs | Real client IP for logs and limits |
| Pods need a partner-whitelisted IP | NAT gateway with Elastic IP / egress gateway | Cilium Egress Gateway | One stable address |
| High-volume outbound to AWS APIs | VPC endpoints | Per-AZ NAT only for the rest | NAT per-GB cost |
| Real-time P2P (video, games) | WebRTC with STUN + TURN | coturn, Tailscale | Direct when possible, relay otherwise |
| Servers on the LAN | Static IP outside the pool, or DHCP reservation | DNS names | Predictable addresses |
| Containers need fixed IPs | User-defined network --ip or DNS names | Compose service names | Docker's IPAM, not DHCP |
| Many customers behind one IPv4 | Per-user limits, IPv6 | CGNAT makes IP a weak identity |
In architecture: from a single process to a distributed system
Monolith (one process, one database)
Example. A Laravel app on one VPS with a public IP. A cloud firewall allows 80/443; nginx proxies to PHP-FPM on 127.0.0.1:9000. There is no NAT in the path, $request->ip() is the client, and logging and rate limiting just work. The moment you put Cloudflare or a load balancer in front, REMOTE_ADDR becomes the proxy and you must configure trustProxies with that proxy's ranges. In the office, the developers' laptops are behind a PAT router and all reach the staging server from the same public IP, which is why staging allow-lists are keyed on that address.
Modular monolith
Example. Several modules (billing, auth, reporting) share a deployment and talk in-process, but they call external providers (payments, email) over the internet from a private subnet. All outbound calls leave through one NAT gateway, so every provider sees one stable IP. Allow-listing for the payment provider uses that Elastic IP; losing the gateway (or recreating it with a new address) breaks the allow-list, so treat it as a managed asset. Webhooks from the providers come inbound through the load balancer, not through the NAT gateway.
Microservices
Example. An order service in Kubernetes calls a partner API and receives webhooks. Pod-to-pod traffic is not NATed; the partner API call is SNATed to the node and then to the NAT gateway's Elastic IP (two SNATs, the partner sees one IP). The Ingress sets X-Forwarded-For; the order service trusts only the ingress CIDR. Internal audit logs store client_ip (resolved), proxy_ip (peer) and the trace id, using the inet columns shown above. The service-to-service hop goes by DNS name; hard-coded pod IPs are a bug, because a pod gets a new IP on every restart. Service meshes and mTLS add identity so that "source IP" stops being the only way to say who called (mTLS).
Distributed data: replicas, caches, multi-region
Example. A database replica in another region, reached through a VPN or peering. NAT gateways in the path will silently drop idle connections: PostgreSQL replication or a pooled connection that idles longer than the NAT's timeout (350 seconds for the AWS NAT gateway, per its troubleshooting page) times out; the NAT gateway then answers the next packet with an RST (its troubleshooting page: "a NAT gateway returns an RST packet to any resources behind the NAT gateway that attempt to continue the connection"), so the app sees connection reset on the next query instead of a clean close. Defence: TCP keepalives shorter than the NAT timeout (tcp_keepalives_idle=60 in the Postgres client), pool health checks, and statement_timeout. For caches (Redis) the same applies to long-lived pub/sub connections. Multi-region active-active systems prefer private connectivity (peering/transit) over NAT because the table is state that cannot be replicated between two NAT devices: a failover loses every flow.
Scaling path
| Load | What breaks first | What to change |
|---|---|---|
| 1x (hundreds of connections) | Nothing; one NAT, one public IP | Defaults are fine |
| 10x (tens of thousands of connections) | conntrack table fills on the NAT box or Docker/K8s node; hairpin and TrustProxies mistakes show up as skewed logs | Raise nf_conntrack_max, keep-alive and pooling, externalTrafficPolicy: Local or PROXY protocol |
| 100x (millions of short outbound calls) | NAT gateway port exhaustion (about 55,000 concurrent connections per attached IPv4 address) and per-GB cost | More Elastic IPs, regional NAT, VPC endpoints, connection reuse, IPv6 egress |
| Global scale | NAT as a single point; asymmetric routing breaks state; CGNAT makes IP a poor identity | Anycast + L4 load balancers with source preservation (DSR), IPv6, identity-based limits |
Lab
All commands ran on Docker Desktop (a Linux VM); on a Linux host drop the docker run --net=host helper and use sudo directly. Output below is real.
1. Publish a port and read the rules.
docker run -d --name natlab -p 8080:80 nginx:alpine
docker run --rm --net=host --cap-add NET_ADMIN alpine sh -c 'apk add -q iptables >/dev/null; iptables -t nat -S'
# expect (among others):
# -A DOCKER -p tcp -m tcp --dport 8080 -j DNAT --to-destination 172.17.0.2:80
# -A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE
# -A POSTROUTING -s 172.17.0.2/32 -d 172.17.0.2/32 -p tcp -m tcp --dport 80 -j MASQUERADE2. Watch conntrack during a request.
docker run --rm --net=host --cap-add NET_ADMIN alpine sh -c '
apk add -q conntrack-tools >/dev/null
(printf "GET / HTTP/1.1\r\nHost: x\r\n\r\n"; sleep 4) | nc 127.0.0.1 8080 >/dev/null &
sleep 1; conntrack -L -p tcp | grep dport=8080; conntrack -C'
# expect: tcp 6 431998 ESTABLISHED src=127.0.0.1 dst=127.0.0.1 sport=56997 dport=8080 src=172.17.0.2 dst=172.17.0.1 sport=80 dport=56997 [ASSURED]
# the reply tuple already shows the container (172.17.0.2:80): that is the DNAT3. Reproduce the hairpin failure.
docker exec natlab sh -c 'apk add -q curl; curl -s -m 4 -o /dev/null -w "%{http_code}\n" http://172.17.0.1:8080/' # 200 (rule present)
docker run --rm --net=host --cap-add NET_ADMIN alpine sh -c 'apk add -q iptables >/dev/null; iptables -t nat -D POSTROUTING -s 172.17.0.2/32 -d 172.17.0.2/32 -p tcp -m tcp --dport 80 -j MASQUERADE'
docker exec natlab curl -s -m 4 -o /dev/null -w "%{http_code}\n" http://172.17.0.1:8080/ # 000, exit 28 (timeout)
docker run --rm --net=host --cap-add NET_ADMIN alpine sh -c 'apk add -q iptables >/dev/null; iptables -t nat -A POSTROUTING -s 172.17.0.2/32 -d 172.17.0.2/32 -p tcp -m tcp --dport 80 -j MASQUERADE' # restore
docker exec natlab curl -s -m 4 -o /dev/null -w "%{http_code}\n" http://172.17.0.1:8080/ # 200 again4. Capture a real DHCP DORA exchange.
docker network create --subnet 10.99.0.0/24 dhcplab
docker run -d --name dhcpd --network dhcplab --ip 10.99.0.2 --cap-add NET_ADMIN alpine sh -c \
'apk add -q dnsmasq tcpdump; dnsmasq -k --interface=eth0 --bind-interfaces --port=0 \
--dhcp-range=10.99.0.100,10.99.0.150,255.255.255.0,2m --dhcp-option=option:router,10.99.0.1 \
--dhcp-option=option:dns-server,10.99.0.53 --dhcp-option=option:domain-name,lab.test --log-dhcp'
docker exec -d dhcpd sh -c 'tcpdump -l -n -v -i eth0 "udp port 67 or udp port 68" > /tmp/dora.txt 2>&1'
docker run --rm --network dhcplab --cap-add NET_ADMIN alpine udhcpc -i eth0 -f -n -q -v
# udhcpc: broadcasting discover ... lease of 10.99.0.150 obtained from 10.99.0.2, lease time 120
docker exec dhcpd cat /tmp/dora.txt
docker rm -f dhcpd; docker network rm dhcplab5. See what your app sees behind a proxy (Go, no Docker):
cd docs/snippets/foundations/nat-dhcp-port-forwarding/go
go run ./realip # right-to-left X-Forwarded-For with trusted CIDRs
go run ./proxyproto # PROXY v1 from a trusted peer
go run ./patable # the toy translation table, port exhaustion included6. Is a forward reachable from the internet? Run from a phone hotspot or VPS: nc -vz YOUR_PUBLIC_IP 8080 or php artisan net:check-port YOUR_PUBLIC_IP 8080. "Connection refused" means a host answered with a reset (the forward works, nothing listens); a timeout means a drop (NAT, firewall or CGNAT). Compare your router's WAN address with the address curl https://ifconfig.me prints; if they differ, or the WAN address is in 100.64.0.0/10, you are behind CGNAT. Clean up: docker rm -f natlab.
Common bugs
| Symptom | Cause | Check | Fix |
|---|---|---|---|
| Port forward works from my phone but not from inside the LAN | No hairpin NAT (NAT loopback) | Does a LAN host reach the public IP? | Split-horizon DNS or enable NAT reflection |
| Container cannot reach itself via the host port | Hairpin DNAT without masquerade | iptables -t nat -S; curl exit 28 | Use the service name, host.docker.internal, or restore Docker's rule |
| Port forward works at the router but not from outside at all | CGNAT / double NAT; ISP blocks the port; wrong WAN IP | Router WAN IP in 100.64/10 or private | Tunnel, bridge mode, ISP public IP, IPv6 |
| Service sees one client IP for everyone | NAT/LB without TrustProxies or PROXY protocol | $request->ips(), REMOTE_ADDR | Trust the proxy CIDR; externalTrafficPolicy: Local |
| Client IP is spoofable | Reading the leftmost X-Forwarded-For | Send a forged header | Walk right-to-left, trust only own proxies |
| Intermittent timeouts under load, no refusals | conntrack table full | dmesg "table full, dropping packet", conntrack -C vs max | Raise nf_conntrack_max; reuse connections |
| Long idle connection (SSH, DB, WebSocket) dies | NAT idle timeout | Works while active | Keepalive below the NAT timeout |
| WireGuard works only if the laptop sends first | No keepalive; NAT row expired | wg show latest handshake | PersistentKeepalive = 25 |
| VoIP has one-way audio | SIP ALG rewriting SDP | Disable SIP ALG | STUN/ICE, SBC |
| App stops working after reboot, config had a private IP | DHCP lease changed | ip addr differs | Reservation, static IP outside pool, DNS name |
| Two hosts with the same IP | Static IP inside DHCP pool | ARP conflict messages | Exclude it from the pool |
| Devices get a wrong gateway/DNS | Rogue DHCP server | Capture DHCP replies, nmap --script broadcast-dhcp-discover | DHCP snooping, remove the rogue box |
| Pod sees node IP as client | externalTrafficPolicy: Cluster SNAT | App logs | Switch to Local or use the ingress header |
| NAT gateway bill explodes | Per-GB processing on traffic to AWS/SaaS | Cost explorer by usage type | VPC endpoints, caching |
| Webhook never arrives | Receiver behind NAT | Nothing inbound | Tunnel, public endpoint |
Common misconceptions
| Belief | Reality |
|---|---|
| "NAT is a firewall" | It drops unsolicited inbound only as a side effect; no policy, no outbound control |
| "NAT hides my identity" | The shared IP still identifies your site; cookies, TLS fingerprints and logs do the rest |
| "Port forwarding is all I need to host at home" | CGNAT and double NAT make it impossible without a tunnel or a public IP |
"-p 8080:80 makes the container listen on 8080" | It installs a DNAT rule (and sometimes docker-proxy); the container only listens on 80 |
"X-Forwarded-For is the client IP" | It is a list; only the entries added by trusted proxies count |
| "More conntrack entries is harmless" | The table has a hard cap; at the cap new connections are dropped silently |
| "UDP has no connections, so NAT ignores it" | NAT creates a row per UDP flow and expires it quickly; keepalives matter |
| "Hairpin works if the forward works" | They are separate features |
| "DHCP assigns the IP forever" | It is a lease with T1/T2 timers |
| "Docker uses DHCP for container IPs" | Docker's own IPAM assigns them |
| "IPv6 is NAT-free so everything is reachable" | A stateful firewall is still needed; global addresses are reachable by default |
| "A reservation equals a static IP" | A reservation is server-side; a static IP is host-side and can collide |
| "NAT breaks only old protocols" | It also affects P2P, VoIP, gaming, IPsec without NAT-T, and anything keyed on client IP |
Cheat sheet
| Topic | What to remember |
|---|---|
| PAT | Many private to one public IP; the table keys on (proto, ip, port); about 64k ports per IP |
| SNAT vs DNAT | SNAT in POSTROUTING rewrites the source; DNAT in PREROUTING rewrites the destination |
| Masquerade | SNAT that follows the interface's current address |
| conntrack | conntrack -L, -C, -S; limit nf_conntrack_max; established TCP timeout 5 days |
| Reply path | Looked up by the table; no row = dropped |
| Port forward | DNAT + FORWARD accept + ip_forward=1; test from outside |
docker run -p | DNAT rule in DOCKER chain + masquerade + hairpin rule + sometimes docker-proxy |
| Hairpin | Needs DNAT and SNAT; fix with split DNS |
| CGNAT | 100.64.0.0/10 (RFC 6598); no inbound; tunnel or IPv6 |
| Traversal | STUN finds the public ip:port, TURN relays, ICE chooses; symmetric NAT needs a relay |
| Keepalive | WireGuard PersistentKeepalive = 25; keepalive < NAT timeout |
| Kubernetes | Pod egress SNAT to node; externalTrafficPolicy: Local keeps client IP |
| Cloud | NAT gateway for outbound, Internet gateway 1:1 NAT; watch per-GB cost |
| Client IP | TrustProxies / right-to-left XFF; PROXY protocol with trusted peers only |
| DHCP | DORA over UDP 67/68; T1 = 50%, T2 = 87.5%; options only if requested |
| Debug | iptables -t nat -S, nft list ruleset, conntrack -L, ipconfig getpacket en0 |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why does a home router need a translation table, and what happens to an inbound packet with no row? Must-know
Answer
Answer: The router can only undo a rewrite if it remembers it. The table maps the public port back to the private ip:port. A packet with no row cannot be delivered anywhere, so it is dropped, which is why unsolicited inbound traffic fails without a port forward.
2 — What is the difference between SNAT, masquerade and DNAT, and which chain does each use? Must-know
Answer
Answer: SNAT rewrites the source in POSTROUTING; masquerade is SNAT that takes the outgoing interface's current address (for dynamic WAN IPs); DNAT rewrites the destination in PREROUTING (or OUTPUT for local processes).
3 — In conntrack -L output, what do the two src= dst= sport= dport= groups mean? Important
Answer
Answer: The first is the original direction as the client sent it; the second is the expected reply direction after NAT. For a DNAT the second tuple shows the translated backend address.
4 — What happens when nf_conntrack_max is reached, and how would you notice? Important
Answer
Answer: New flows are dropped (the SYN vanishes, the client times out; no refusal). The kernel logs "table full, dropping packet"; conntrack -C is near the max and conntrack -S shows drop or insert_failed. Raise the limit, shorten timeouts, reuse connections.
5 — A container cannot reach http://host-ip:8080, its own published port, but others can. Why, and what is the fix? Important
Answer
Answer: Hairpin: the packet is DNATed back to the same container without source rewriting, so the reply never matches the connection. Docker adds a /32 masquerade rule to cover it; in setups without it, use the service name or fix the rule.
6 — Your router's WAN IP is 100.72.4.9. Does port forwarding work? Important
Answer
Answer: No. 100.64.0.0/10 is the CGNAT shared address space (RFC 6598); the ISP's NAT owns the public address and has no row for inbound packets. Use an outbound tunnel, ask for a public IP or use IPv6.
7 — Why does WireGuard need PersistentKeepalive behind NAT? Important
Answer
Answer: WireGuard sends nothing when idle, so the NAT row expires (often in 30 to 60 seconds for UDP) and inbound packets stop arriving. A keepalive every 25 seconds keeps the mapping alive.
8 — How do you read the real client IP from X-Forwarded-For safely? Must-know
Answer
Answer: Only trust the header if the TCP peer is a trusted proxy; then walk the list from the right, skipping trusted proxy addresses, and take the first untrusted address. Never take the leftmost entry.
9 — What does externalTrafficPolicy: Local change, and what is the downside? Important
Answer
Answer: kube-proxy only forwards to pods on the same node, which preserves the client source IP (no SNAT). Nodes without a local pod drop traffic and load can be uneven.
10 — Name the four DHCP messages, their ports and when T1 and T2 happen. Good to know
Answer
Answer: Discover, Offer, Request, Acknowledge over UDP (client 68, server 67). T1 is 50% of the lease (unicast renew), T2 is 87.5% (broadcast rebind); at 100% the address is dropped.
11 — Why did the lab's DHCP client not get the MTU the server was configured with? Good to know
Answer
Answer: DHCP servers send options the client asked for in its parameter request list (option 55). The client did not request option 26 (interface MTU), so the server did not include it.
12 — Why verify a webhook signature instead of trusting the source IP when using a tunnel? Must-know
Answer
Answer: Behind a tunnel the TCP peer is the tunnel agent, the public URL can be hit by anyone, and CGNAT/proxies blur the origin. An HMAC signature proves the payload came from the provider.
Glossary
| Term | Meaning |
|---|---|
| NAT | Network Address Translation: rewriting IP addresses in packet headers |
| NAPT / PAT | NAT that also rewrites ports so many hosts share one IP |
| Masquerade | Linux SNAT that uses the outgoing interface's current IP |
| SNAT | Source NAT: rewrite the source address, in POSTROUTING |
| DNAT | Destination NAT: rewrite the destination, in PREROUTING |
| Static NAT / 1:1 NAT | Fixed one-to-one address mapping |
| Dynamic NAT | Pool of public addresses handed out on demand |
| Port forwarding | A standing DNAT rule for inbound traffic |
| Translation table | The NAT's memory of rewritten flows |
| conntrack | Linux connection tracking (netfilter) |
| 5-tuple | Protocol, source IP, source port, destination IP, destination port |
| Hairpin NAT / NAT loopback / NAT reflection | Inside client reaching an inside server by its public address |
| Double NAT | Two NAT devices in series |
| CGNAT / CGN | Carrier-grade NAT done by the ISP |
| Shared Address Space | 100.64.0.0/10, RFC 6598 |
| ALG | Application Layer Gateway: NAT code that rewrites payload addresses |
| STUN | Protocol to learn your public ip:port |
| TURN | Relay server for peers that cannot connect directly |
| ICE | Framework that tries host, reflexive and relayed candidates |
| Hole punching | Both peers send at once so each NAT opens a row |
| Symmetric NAT | NAT with a different external port per destination |
| Keepalive | Periodic packet that keeps a NAT row alive |
| PROXY protocol | Header a proxy prepends to pass the original client address |
| X-Forwarded-For | HTTP header listing the client and proxy chain |
| TrustProxies | Laravel middleware that trusts forwarded headers from listed proxies |
externalTrafficPolicy | Kubernetes Service field; Local preserves the client IP |
| NAT gateway | Managed cloud outbound NAT |
| Internet gateway | Cloud component doing 1:1 NAT for public addresses |
| Elastic IP | AWS static public IPv4 address |
| DHCP | Dynamic Host Configuration Protocol |
| DORA | Discover, Offer, Request, Acknowledge |
| Lease | Time-limited right to use an address |
| T1 / T2 | Renewal (50%) and rebinding (87.5%) timers |
| Reservation | Server-side fixed address for a MAC/client ID |
| Relay agent | Forwards DHCP broadcasts across subnets (giaddr, option 82) |
| Rogue DHCP | Unauthorised DHCP server |
| DHCP snooping | Switch feature that only allows DHCP replies from trusted ports |
| DHCPv6 | Stateful IPv6 configuration (UDP 546/547) |
| SLAAC | Stateless Address Autoconfiguration from Router Advertisements |
| Ephemeral port | Short-lived source port for client connections |
| Magic cookie | 63 82 53 63 marking DHCP options in a BOOTP packet |
References
Every URL was fetched and its text saved under scratchpad/sources/nat-dhcp-port-forwarding/; the HTTP status was 200 when fetched.
- RFC 3022, Traditional NAT: https://www.rfc-editor.org/rfc/rfc3022
- RFC 2663, NAT terminology: https://www.rfc-editor.org/rfc/rfc2663
- RFC 3027, Protocol complications with NAT: https://www.rfc-editor.org/rfc/rfc3027
- RFC 4787, NAT behavioral requirements for UDP: https://www.rfc-editor.org/rfc/rfc4787
- RFC 5382, NAT behavioral requirements for TCP: https://www.rfc-editor.org/rfc/rfc5382
- RFC 6598, Shared Address Space (CGNAT): https://www.rfc-editor.org/rfc/rfc6598
- RFC 1918, private address space: https://www.rfc-editor.org/rfc/rfc1918
- RFC 8445 (ICE): https://www.rfc-editor.org/rfc/rfc8445; RFC 8489 (STUN): https://www.rfc-editor.org/rfc/rfc8489; RFC 8656 (TURN): https://www.rfc-editor.org/rfc/rfc8656
- RFC 2131 (DHCP): https://www.rfc-editor.org/rfc/rfc2131; RFC 2132 (options): https://www.rfc-editor.org/rfc/rfc2132; RFC 3046 (relay agent): https://www.rfc-editor.org/rfc/rfc3046
- RFC 8415 (DHCPv6): https://www.rfc-editor.org/rfc/rfc8415; RFC 4862 (SLAAC): https://www.rfc-editor.org/rfc/rfc4862; RFC 7239 (Forwarded): https://www.rfc-editor.org/rfc/rfc7239
- HAProxy PROXY protocol specification: https://raw.githubusercontent.com/haproxy/haproxy/master/doc/proxy-protocol.txt
- Linux kernel
nf_conntrack-sysctl: https://www.kernel.org/doc/Documentation/networking/nf_conntrack-sysctl.txt - netfilter NAT HOWTO (source NAT / masquerading): https://www.netfilter.org/documentation/HOWTO/NAT-HOWTO-6.html
- Docker, packet filtering and firewalls: https://docs.docker.com/engine/network/packet-filtering-firewalls/
- Kubernetes, using source IP: https://kubernetes.io/docs/tutorials/services/source-ip/; Services: https://kubernetes.io/docs/concepts/services-networking/service/; virtual IPs: https://kubernetes.io/docs/reference/networking/virtual-ips/
- WireGuard quick start (persistent keepalive): https://www.wireguard.com/quickstart/
- AWS, NAT gateways: https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html; NAT gateway troubleshooting (350 s idle timeout, 55,000 connections): https://docs.aws.amazon.com/vpc/latest/userguide/nat-gateway-troubleshooting.html; Internet gateway: https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html; VPC pricing: https://aws.amazon.com/vpc/pricing/
- Laravel 13 requests (trusted proxies): https://laravel.com/docs/13.x/requests; routing (rate limiting): https://laravel.com/docs/13.x/routing
- Cloudflare quick tunnels: https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/trycloudflare/; ngrok: https://ngrok.com/docs/getting-started/
- MDN, X-Forwarded-For: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-For