Search code examples
c++linuxnetwork-programmingnat

NAT-Traversal implementation for P2P connection


I need to implement a simple P2P application behind NATs. It should send data over a reliable and secure connection (Encrypted data over TCP). From the theoretical background I know there are several NAT-Traversal techniques (for example Session Traversal Utilities for NAT) described in several RFCs (5389, 5769, and 5780).

Though in practice I can't find needed tools/libraries to implement such a system (preferably in C++ programming language). What I already found by googling around blindly: ICE, TURN, libnice, libjingle and STUNTMAN

Below image describes what it should look like. I have a VPS with valid IP address, a PC behind a NAT and a sensor behind another NAT. They have private IPs. I want my sensor to connect to server, find monitor and send connection request to it. After connection establishment, relay server should not be used to direct traffic of data. I want my sensor and monitor to use this path to communicate:

Sensor <--> AP0 <--> R3 <--> {THE INTERNET} <--> R2 <--> Monitor

Currently all data is transmitted through VPS:

Sensor <--> AP0 <--> R3 <--> {THE INTERNET} R1 <--> 
VPS <--> R1 <--> {THE INTERNET} <--> R2 <--> Monitor

Network


Solution

  • Basically, if you can port forward, then this is more of a infrastructure question than programming. You Just need to configure the routers to direct traffic from the public IP / Port to the Private IP / Port, e.g.:

    R2: Port 500 - TCP -> Laptop-PT - Port 500
    R3: Ports 16000/16500 - TCP/UDP -> PDA-PT - Port 16000/16500
    

    If you want to get fancy and your routers support UPnP, just resort to a library that implements the IGD protocol (e.g., MiniUPnP), in order to make your application control the port mapping. This article provides a good starting point as well as some sample code (although I would really recommend a robust library).