I recently came across an experiment wherein they where able to make peer-to-peer communications happen between 2 machines using UDP hole punching using netcat. I'm not sure if I fully understand the experiment that is going on here. The experiment is as follows:
There are 2 machines, 1 and 2. They have the public IP(s) say IPa and IPb.
# run on machine 1
echo 'punching a hole in NAT table' | nc -u -p 50001 IPa 50002
nc -u -l 50001 # start a UDP listener
# run on machine 2
echo 'punching a hole in NAT table' | nc -u -p 50001 IPb 50002
nc -u -l 50001 # start a UDP listener
# run on machine 1
echo 'hello' | nc -u -p 50002 IPa 50001
# run on machine 2
echo 'hello' | nc -u -p 50002 IPb 50001
This experiment assumes both machines are behind a NAT system. What I understand is the the first 2 lines will insert the NAT entries in the NAT table of 1 and 2 like this:
Machine 1:
| Private IP | Private Port | Public IP | Public Port |
|---|---|---|---|
| PrivateIPa | 50001 | IPa | PublicPorta |
Machine 2:
| Private IP | Private Port | Public IP | Public Port |
|---|---|---|---|
| PrivateIPb | 50001 | IPb | PublicPortb |
Now when the 2nd command runs that sends hello from say machine 1 port 50002 to machine 2 at port 50001 then the packet reaches machine 2 NAT with port 50001 as destination. But the NAT entry in machine 2 has path of IPb:PublicPortb. How is the reverse mapping done then?
When Machine 1 sends a UDP packet with source port 50002 to Machine 2 port 50001, the NAT on Machine 1 modifies the source port of the packet to PublicPorta to match the NAT entries (IP:50002 -> IP:50001 then IPa:PublicPorta). The same translation process is executed in reverse when the message reaches Machine 2.
Documentation: Link1, Link2