Search code examples
networkingwebrtcp2pstunhole-punching

P2P between peers in natted networks when the external port changes constantly


I was reading up on WebRTC which led me to start looking into STUN (Session Traversal Utilities for NAT) and all the examples I saw seemed to assume that the public ip and port were static over at least several seconds or minutes at a time.

However, my home internet connection uses a shared public ip and putting the following php code

<?php
echo $_SERVER['REMOTE_ADDR'] . ":" . $_SERVER['REMOTE_PORT'];
?>

on a server with a public ip address gives results like this

63.142.201.34:34850
63.142.201.34:34924
etc.

when the page is refreshed repeatedly. The same thing happens with my cell phone when it is using my data plan (just with a different public ip).

How are peer-to-peer connections possible in this case? Can someone point me to a tutorial or some keywords I could use to look this up?

Dustin Soodak


Solution

  • The reason you are seeing a different external port is that you are using different local ports, one for each HTTP request. That is rather common with TCP.

    UDP as a connectionless protocol makes it easier to reuse the local port. The tailscale project recently wrote up a great blog post on hole punching here