How STUN, TURN, and ICE Work Together in WebRTC
WebRTC enables real-time communication directly between browsers, but NAT and firewall rules make this challenging. To navigate these obstacles, WebRTC relies on three key technologies: STUN, TURN, and ICE.
STUN: Discovering Public IPs
STUN (Session Traversal Utilities for NAT) helps a client discover its public IP and port from behind a NAT. It does this by querying a STUN server, which replies with the observed external address.
- Used to try direct P2P first
- Lightweight and fast
- Doesn't work well with Symmetric NAT
TURN: Relay When All Else Fails
TURN (Traversal Using Relays around NAT) is a fallback when direct connection fails. The media or data is relayed through a TURN server, which introduces additional latency but ensures connectivity.
- Essential for Symmetric NAT
- Increases server load and cost
ICE: Connectivity Orchestrator
ICE (Interactive Connectivity Establishment) is the framework that coordinates STUN and TURN usage. It collects all connection candidates and tests them in order of preference to find the best possible path.
- Gathers host, reflexive (STUN), and relay (TURN) candidates
- Picks the optimal route
Summary
| Protocol | Role | When Used | |---------|------|-----------| | STUN | Discover public IP | First attempt | | TURN | Relay traffic | Fallback | | ICE | Orchestrate connection | Always |
Conclusion
WebRTC depends on a smart combination of STUN, TURN, and ICE to overcome NAT/firewall restrictions and establish stable, low-latency connections across devices.