Card 05/ 10

ConceptDifficulty: Advanced2 min

NAT Traversal: ICE, STUN and TURN

Two peers behind home routers cannot reach each other until they learn their public addresses or fall back to a relay.

Most devices sit behind NAT, a router that shares one public address among many private ones, so a browser does not know the address the internet sees and cannot be reached from outside without help. ICE (Interactive Connectivity Establishment) is how WebRTC finds a working path anyway: it gathers every address a peer might be reached at, learning its public one from a STUN server, falls back to a relay on a TURN server, and tests pairs until one connects.

STUN is like asking someone outside the building what your return address looks like on the envelope. TURN is a forwarding service: you send to it, and it posts your letters on. The comparison breaks in one place: a forwarding service could open the post, but a TURN relay passes on media that is encrypted end to end, which it cannot read.

Which kind of candidate connects two peers?
  1. When Both peers are on the same local network

    , choose

    A host candidate, the device's own private address. Direct and fastest.

  2. When Each is behind a NAT that keeps the same public port for every destination

    , choose

    A server-reflexive candidate, the public address and port learnt from STUN. Direct across the internet.

  3. When A NAT picks a new public port for every destination, or a firewall blocks UDP

    , choose

    A relay candidate on a TURN server, which forwards every packet. Always works, at the cost of a hop and the relay's bandwidth.

How it starts. Each browser gathers candidates of three kinds. Host candidates are its own addresses. Server-reflexive candidates come from asking a STUN server "what address did my request come from?", which reveals the public address and port the NAT assigned. Relay candidates are addresses allocated on a TURN server, which will forward packets on the peer's behalf. Candidates reach the other side through signalling.

Who may send. Both peers send connectivity checks, small STUN messages, to every pair of their own and the other's candidates. A check that gets an answer proves that pair works in both directions. The highest priority working pair is chosen, direct ones first.

One message on the wire. Through a relay, each packet goes from the peer to the TURN server and on to the other peer, still encrypted with the keys the two peers agreed. The relay sees addresses and sizes, not content.

After a drop. An ICE restart gathers new candidates and repeats the checks.

Most calls connect directly, but behind strict firewalls or NATs that change ports per destination only TURN works, and a service without one fails those calls.

So STUN tells a peer its own public address, and TURN carries the traffic when knowing it is not enough.