How do I make a TCP server work behind a router (NAT) without any redirection configuration needed

StackOverflow https://stackoverflow.com/questions/1511562

  •  19-09-2019
  •  | 
  •  

Question

The scenario is the following. I have two machines A and B: A: Client (behind NAT) B: Server (behind NAT)

I want B to be able to listen on any given port, so that A can send packets to B through that specific TCP port and receive any response. If both machines are not behind a NAT it is pretty straight foward process. However how do I make it work so that it works even when B is behind a router, without him having to go change the router configuration enable some port forwarding etc...

For example, how do peer-to-peer programs like torrent clients work without the user having anything to configure?

Was it helpful?

Solution

An alternative to a proxy server is a match-making server. Instead of proxying all of the traffic, the match maker just negotiates until the peers can talk to each other. This involves finding the external public IPs of the peers and talking to each one so that the firewall/router knows that the peers wish to communicate.

This is called hole punching and it often has to be done by the match maker rather than the peers themselves. Once the hole are punched though, the match maker can tell the peers about each other and they can communicate directly.

OTHER TIPS

To answer the example of Peer to Peer programs, and in general: There is a technology called Universal Plug and Play which NAT routers can use to allow clients behind them to expose ports to the outside. That's what bittorrent clients can use so the other clients can directly connect to them.

You will have to either:

  1. Set up port forwarding from the nat gateway in front the server into the machine your server software is running, and have the client connect to the IP address of that gateway.

  2. Create a proxy server sitting inbetween the 2 nat gatewys so both your server and client can connect to that. Both your server and client have to set up a connection to that proxy which will mediate the data between those 2 connections.

Hole punching is moderately well-understood for UDP communication, but it can be reliably used to set up peer-to-peer TCP streams as well. Here is the well detailed article on both TCP and UDP:

http://www.brynosaurus.com/pub/net/p2pnat/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top