Technology12 min read
STUN and TURN Servers: How P2P Connections Work Behind NAT
Technical deep dive into how STUN and TURN servers enable peer-to-peer connections even when devices are behind firewalls.
The NAT Problem
Most devices aren't directly accessible on the internet. They sit behind NAT (Network Address Translation) routers that:
- Share a single public IP among many devices
- Block unsolicited incoming connections
- Make direct P2P connections challenging
Understanding NAT Types
1. Full Cone NAT
2. Restricted Cone NAT
3. Port Restricted Cone NAT
4. Symmetric NAT
STUN: Session Traversal Utilities for NAT
What STUN Does
STUN helps a device discover:
How It Works
1. Device sends request to STUN server
STUN server sees the public IP:port STUN server responds with that information Device now knows its public address
Limitations
STUN only works when direct connections are possible. It fails with:
TURN: Traversal Using Relays around NAT
When TURN is Needed
When direct connections fail, TURN provides a fallback:
How TURN Works
Device A → [TURN Server] → Device B
↑
Data relayed, but still encrypted!
Security Consideration
Even though data passes through TURN:
ICE: Interactive Connectivity Establishment
ICE combines STUN and TURN intelligently:
The ICE Process
- Gather Candidates
- Connectivity Checks
- Select Best Path
- Direct connection (best)
- STUN-assisted connection (good)
- TURN relay (fallback)
- Host candidates (local addresses)
- Server reflexive (STUN-discovered)
- Relay candidates (TURN)
- Try all candidate pairs
- Find the best working path
- Prefer direct connections
- Fall back to relay if needed
Priority Order
In Practice: ZeroSend
ZeroSend uses Cloudflare's TURN service:
Connection Attempt:
Try direct P2P connection If blocked, try STUN-assisted If still blocked, use TURN relay All paths encrypted end-to-end
Why This Matters
- ~85% of connections succeed directly
- ~10% need STUN assistance
- ~5% require TURN relay
- 100% maintain encryption
Technical Details
STUN Message Format
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
0 0 STUN Message Type Message Length
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Magic Cookie
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Transaction ID (96 bits)
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Candidate Format
a=candidate:1 1 UDP 2122260223 192.168.1.100 54321 typ host
a=candidate:2 1 UDP 1686052607 203.0.113.50 12345 typ srflx
a=candidate:3 1 UDP 41885439 turn.example.com 3478 typ relay
Conclusion
STUN and TURN servers are essential infrastructure that enable P2P connections across the complex reality of modern networks. They solve the NAT traversal problem while maintaining end-to-end encryption.