A most elegant TCP hole punching algorithm
19 hours ago
- #TCP
- #Networking
- #NAT
- TCP hole punching connects computers behind NAT routers by knowing each other's WAN IPs, external ports, and connecting simultaneously.
- The algorithm uses a deterministic approach to derive metadata from a single parameter, avoiding fixed infrastructure.
- A 'bucket' is calculated using Unix timestamp, max clock error, and min run window to synchronize both sides without communication.
- Ports are selected using the bucket as a seed for a pseudo-random number generator, ensuring both sides generate the same port list.
- Essential socket options for TCP hole punching include SO_REUSEADDR and SO_REUSEPORT to aggressively reuse socket addresses.
- Non-blocking sockets with select for polling are recommended for precise timing control during SYN packet exchanges.
- The algorithm uses a leader-follower model to choose the winning connection, with the leader sending a single character to confirm.
- The entire process is deterministic, requiring only a destination IP and no additional metadata exchange between hosts.
- The tool can be tested locally by running commands within a 10-second window to simulate the hole punching process.