← Lessons

quiz vs the machine

Platinum1620

Networking

NAT Traversal With STUN And TURN

Discover how two devices behind separate routers establish a direct connection.

6 min read · advanced · beat Platinum to climb

The Problem Behind A NAT

Most devices sit behind network address translation, sharing one public address and holding only a private one. That is fine for reaching out to servers, but two such devices cannot easily connect directly to each other because neither knows the other public facing address and port.

Discovering Your Public Address With STUN

A STUN server solves the first half. A device sends it a request, and the server replies with the public address and port it observed.

  • The device learns how the outside world sees it.
  • It can share this candidate address with the peer.
  • Each side gathers several candidate addresses to try.

Relaying With TURN

Some NATs are too strict for a direct path to work. A TURN server acts as a relay: both peers connect out to it, and it forwards traffic between them.

  • It always works because each side only makes outbound connections.
  • It costs bandwidth and adds latency since all data passes through it.
  • It is used as a fallback when direct connection fails.

Choosing A Path With ICE

The ICE framework ties this together. Each peer gathers candidates from STUN and TURN, then they systematically test pairs to find a working path, preferring a direct one and falling back to a relay only if needed.

Key idea

STUN reveals a device public address, TURN relays traffic when direct paths fail, and ICE gathers and tests candidates to pick the best working route between peers behind separate NATs.

Check yourself

Answer to earn rating on the learn ladder.

1. What does a STUN server tell a client?

2. When is a TURN relay used?