Hacker News new | ask | show | jobs
by ashton314 779 days ago
Can someone ELI5 for me how STUN and TURN work to make peer-to-peer happen? I get basic web protocols, but peer-to-peer stuff has always been a little confusing for me.
2 comments

STUN is a way of breaking NAT using uPNP.

What I mean is that: You don't have a public IP, you likely go to the internet via a router. That router is stateful and allows traffic destined to go to some other internet address to return to you, even though your device is not technically routable on the internet.

So, what a STUN server does, is give you information about how to initiate connections to each party; that allows traffic to go through each of your routers.

    CLIENT1 <-> STUN    // (what ip/port combo is needed for CLIENT2 ;;; there is nothing in the table)
    CLIENT1 <-> CLIENT2 // (initiate a connection attempt that will fail, but will be remembered by the stateful NAT/firewall for return traffic)
    CLIENT1 <-> STUN    // (CLIENT1's incoming info for CLIENT2, this combo will only work for CLIENT2, so it requires CLIENT2 to ask about it)
    CLIENT2 <-> STUN    // (what ip/port combo is needed for CLIENT1 ;;; information is now in the table and will be fetched)
    CLIENT2 <-> CLIENT1 // (direct connection based on previous incoming connection attempt *from* CLIENT1)

NOTE: this is not required for ipv6; this is a hack we needed to bypass NAT because we ran out of ipv4.

TURN is the same idea, but instead of coordinating a peer-to-peer connection, it routes traffic via itself, it's just a neutral relay.

Excellent explanation—thank you. Great example of a handshake too.
Device A sends a request to the STUN server. STUN server responds with the public IP address, port and other NAT details that it is able to see. Device A forwards this info to device B, and periodically sends keepalive packets so the connection remains active. Device B is now able to hit device A's public IP/port directly (the router/firewall thinks that the packets are coming from the STUN server).

If the NAT is more restrictive then a TURN server can act as a middleman to relay the packets between device A and device B.