socketsp2p

Peer to Peer Networking - with shared public IP and DHCP


I am trying to setup peer to peer networking and am trying to understand how this works.

Normally in Client to Server connection, I will connect to the server IP and port. Behind the scenes, it will create a client socket bound to a local port at the local ip, and the packet is sent to the router. The router will then NAT the local port and the local socket, to the client public ip and a different public client socket with a destination for the server IP and port.

When the server responds, the router then DENATs the public client ip and public client port back to the local ip and local port, and the packet arrives at the computer.

In a Peer to Peer networking, I may have the peer's public IP, but it is shared by many machines and the router hasn't allowed a connection yet, so there isn't a open port I can send the data to.

There was then an option that both peers contact a server. That opens a port on the router. Then the peers send packets to each other's client port.

However, usually the router will only accept packets from the same IP the request was made to, so the two peers cannot reuse the server's connection.

How do the two peers talk to each other in this scenario ?


Solution

  • You said it yourself: "peers send packets to each other's client port". Therefore, the router will "accept packets from the same IP the request was made to".

    Say, Alice is behind router A and Bob is behind router B.
    Having learned their public endpoints from a server, Alice will send UDP packets to Bob's public IP, and Bob will send UDP packets to Alice's.
    Having seen Alice talk to Bob's IP, router A will accept UDP packets from Bob.
    Having seen Bob talk to Alice, router B will accept UDP packets from her as well.

    That is, some initial packets might be rejected as coming from the blue, but after both parties have initiated communication on their side, routers will have no reason to block what follows.

    In terms of Symmetric NAT Traversal using STUN 2003, by sending a packet to Bob, Alice is creating a door for Bob in A. On the other side, by sending a packet to Alice, Bob is creating a door for Alice in B.
    (p.s. cf. "Finessing finicky firewalls" at https://tailscale.com/blog/how-nat-traversal-works)

    The trick in UDP hole punching seems to be for the routers to reuse the same NAT tunnel for different IPs - so that the port discovered by a server is the same as the port reused for direct communication.
    We can talk with different IPs from a normal UDP socket (by skipping connect and using sendto), so it's kind of logical that a tunneled socket would be able to do the same.