Part XIX - NAT

19. NAT Traversal

STUN, TURN, UDP and TCP hole punching, ICE, port mapping protocols, WebRTC, and Tailscale-style relay fallback.

1. 19.8 - STUN

STUN lets a client discover the public transport address that a NAT created for one UDP socket. The server simply reflects the source tuple it observed in a Binding Response, encoded as an XOR-mapped address so middleboxes do not rewrite the address-like bytes in the payload.

STUN is discovery, not connectivity. Comparing the mapped address from two STUN destinations can reveal whether the NAT keeps one external port or creates destination-specific symmetric mappings.

Minimal C Demo - STUN Binding Mirror

STUN Binding Mirror — C Demo
stdin (optional)

2. 19.9 - TURN

TURN allocates a public relay address when direct peer connectivity is impossible. Both peers send to the relay, and the relay forwards packets between them using Send indications or a ChannelBind fast path.

  • Use TURN when both sides are behind symmetric NATs or strict firewalls.
  • TURN uses authenticated allocations, commonly the long-term credential mechanism.
  • The tradeoff is predictable reachability at the cost of extra latency and relay bandwidth.

3. 19.10 - UDP Hole Punching

UDP hole punching uses a signaling server to exchange public tuples, then makes both peers send to each other at nearly the same time. Each outbound packet creates NAT state that allows the other peer's inbound packet through.

The hard failure case is symmetric mapping: the tuple seen by the signaling server is not the tuple used for the peer destination. Port prediction can help in some deployments, but production systems need relay fallback.

Minimal C Demo - UDP Punch Decision

UDP Punch Decision — C Demo
stdin (optional)

4. 19.11 - TCP Hole Punching

TCP hole punching relies on simultaneous open: both peers send SYN from the intended local port and accept a peer SYN while in SYN_SENT. It is more fragile than UDP because RST handling, TIME_WAIT, and NAT TCP state machines all have to line up.

Implementations often need SO_REUSEADDR or SO_REUSEPORT so the same local port can be reused while older socket state is still visible to the OS.

5. 19.12 - ICE

ICE turns STUN, TURN, and hole punching into a deterministic candidate-selection algorithm. It gathers local, server-reflexive, peer-reflexive, and relay candidates, then tests candidate pairs with STUN connectivity checks.

The agent prioritizes cheaper paths first and nominates the first working high-priority pair. A public server can run ICE Lite: it only responds to checks because it already has a reachable address.

6. 19.13 - UPnP, NAT-PMP, and PCP

Port mapping protocols let an inside application ask the gateway to create an inbound mapping instead of relying on pure hole punching. They are convenient for games, calls, and VPNs, but they widen the trust boundary of the LAN.

ProtocolMechanismUseRisk or note
UPnP IGDSSDP discovery plus SOAP control callsConsumer routersMalicious local clients can request exposed ports
NAT-PMPSimple UDP request to map external to internal portApple-originated home NAT traversalIPv4-focused predecessor to PCP
PCPMAP and PEER opcodes for IPv4/IPv6 mappingsModern NATs and CGN assistanceSupports explicit peer mappings and third-party extensions

7. 19.14 - WebRTC

WebRTC embeds ICE in the browser. SDP offer/answer carries candidate lists over an application-defined signaling channel, ICE chooses the path, DTLS authenticates it, and SRTP carries audio/video over the nominated transport.

Trickle ICE sends candidates incrementally as they are discovered, so connectivity checks can start before every host, STUN, and TURN candidate is known.

8. 19.15 - Tailscale and WireGuard

WireGuard is UDP-based and handles endpoint roaming naturally. Tailscale adds coordination, direct punch attempts, DERP relay fallback, and background upgrade probes that keep trying to replace relayed traffic with direct traffic.

Minimal C Demo - Direct vs DERP Path

Direct vs DERP Path — C Demo
stdin (optional)

9. Interview Prep

QuestionAnswer checkpoint
What does STUN tell a client?The public source IP and port observed by an external server; it does not prove peer reachability.
When do you need TURN?When direct checks fail, commonly symmetric NAT on both sides or restrictive UDP firewalls.
Why must UDP hole punching be simultaneous?Each NAT must see an outbound packet first so the other peer's inbound packet matches permitted state.
What are ICE candidate types in priority order?Host, server-reflexive, peer-reflexive, then relay, with relay as the most reliable but most expensive fallback.
How does Tailscale resemble ICE?It discovers endpoints, attempts direct UDP connectivity, relays through DERP if needed, and keeps probing for a direct upgrade.