Search code examples
tcpudpforwarding

Torrent peer-to-peer connection


I used to think my understanding of the TCP and UDP protocols, although limited, is correct. Although recently, when I realized that peers sharing a common torrent can connect to one another through a TCP or UDP protocols without the actual need for port forwarding, I got confused. How does a router know which machine in the local network to forward packets to? Any help in clearing that up would be appreciated. The torrent protocol diagrams and articles on the Internet are greatly simplified, and hence do not contain any information that would help.


Solution

  • The router (running NAT) tracks all outgoing packets and then allows incoming packets which are responses to those outgoing packets.

    So if you make an outgoing TCP connection to google.com:80 then it will allow packets back in (in response) from google.com:80. If two internal hosts make a connection to the same port it can differentiate them because the local port is different, for example:

    1) Host A makes a connection to Google and the router uses its own local port 10001 for the TCP connection

    2) Host B makes a similar connection and the router uses its own local port 10002 for the TCP connection

    If a packet comes in from google.com:80 and its addressed for the port 10001 on the router's WAN IP then the router knows to send it to Host A. If its addressed for port 10002 the router knows to send it to Host B.

    If you have two peer to peer hosts behind routers (two NATs) then there is no way to establish the connection except that if there is something to transfer information about each others IPs (i.e. a server they can both use to exchange information) they can try to guess what port the router will choose as a local port and then start sending each other data on that port, to the routers WAN IP. Because both routers see data going OUT they then set up a rule to allow data IN. If the ports are guessed correctly then the packets from each side can get through because both routers have a rule set up. This is called UDP/TCP Hole Punching.

    http://en.wikipedia.org/wiki/UDP_hole_punching

    I believe Skype is an example of a app which uses UDP and does hole punching.