Search code examples
socketstcpudpconnectionp2p

connect two clients together by a server without port forwarding


I’m trying to write an app that performs the following actions:

  1. client (1) connects to a server and picks another client (2) from a list
  2. server connects clients (1) and (2) together (there is not port forwarding involved)

How to connect two clients to each other directly, using a server which knows their addresses, ports and has an opened connection to both?

In many posts about p2p there are statements, that it is possible and a common scenario, but I’m struggling to find an explanation how its done.


Solution

  • What you are describing is a direct peer-to-peer (p2p) connection. In order for that to work under normal conditions, without needing port forwarding, or more advanced NAT traversal techniques (hole punching, STUN, etc), the server will have to facilitate a negotiation between the clients, where one client agrees to open a listening socket which the other client will then try to connect to. If that connection fails, the clients can reverse roles and try again in the other direction. As long as at least 1 client is not behind a NAT, this will typically work. But if that connection also fails, further communication between the clients will have to go through the server as a proxy, unless more advanced techniques are used.