Can anyone explain how UDP hole punching
works in a simple way? I know how NAT
and PAT
works, but can't get a clear idea about UDP hole punching
.
2 Answers
Details vary but basically it goes something like.
- The two peers both open a UDP socket bound to a random local port
- The two peers both contact a server on the internet. This server responds and tells them what IP and port their packet was received from. Since the server is on the Internet the IP/port seen by the server is the external IP and port
- The two peers exchange information about the external IPs and ports through some mechanism.
- The two peers start trying to send UDP traffic to each other.
- Hopefully the external IP and port used by the NAT for the traffic to the server are the same as the external IP and port used for the traffic sent towards the other peer. So once both peers have sent packets out through their NATs the incoming packets match the mappings and peer to peer communication is established.
This strategy will work reliablly with full cone, restricted cone or restricted port cone NATs. It will work most of the time with port-preservative symmetric NATs. It will not work with randomising symmetric NATs.
-
2
Hopefully the external IP and port used by the NAT for the traffic to the server are the same as the external IP and port used for the traffic sent towards the other peer
This didn't make sense to me right away, it would have been helpful to elaborate on why that is important (just a quick example). Still, the answer is very clear. Thanks. Oct 8, 2019 at 19:36 -
-
@j3141592653589793238 if otherwise, the NAT will drop the packet because the common behavior of NAT is that if no packet was sent to an external device, it won't allow the external device to send a packet inside. Here is a detailed answer about UDP hole punching: stackoverflow.com/a/74954710/9857078– MateenDec 30, 2022 at 5:17
From testing, when you send a UDP to a server it will respond back with the port you used, the thing is when you try to contact the other peer the port you use will be different based on your NAT, making the whole chit chat with the middle server to find what your external port was to accomplish communication with a third node pointless.
-
1You need to find out your public-side source port that is used after NAT. Locally, you only ever see your private-side port. You do need an external which-IP-and-port-am-I-talking-from service.– Zac67 ♦Feb 13, 2022 at 9:25