Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Tcp connection for clients behind NAT

Tags:

tcp

nat

Which software libraries does exist for such task for Linux, Windows OS?

Does it exist some info in RFC how people should do it?

I'm interesting how can I create functionality for my C++ project like presented here in that software: https://secure.logmein.com/ru/products/hamachi/download.aspx

like image 704
Konstantin Burlachenko Avatar asked Aug 12 '15 00:08

Konstantin Burlachenko


1 Answers

There is not much difference if you want to make a connection through TURN relay server. The only difference is how TCP and UDP creates connection and nothing else.

There are some big differences if you want to make P2P connection.

If you are in same network(behind same NAT): In UDP you send a stun binding request to your peer candidate and then if you get a response back then you know you are connected. Same in TCP you have to create one active socket on one side and one passive socket on another. And then send syn from active socket and receive it from passive socket and then send syn ack to the active socket. And then active socket send an ack and the connection is established.

If you are in different Network(behind different NAT): You have to employ TCP hole punching technique for making a connection. Because your NAT won't allow a TCP syn packet through if previously no packet was sent to the address the syn is coming from.

TCP hole punching in details:

You have to use a TCP simultaneous open socket. This socket acts in both active and passive mode. Both end needs to know each others private and public IP:Port. TCP simultaneous open will happen as follows:

  1. Peer A keeps sending SYN to Peer B Peer B keeps sending SYN to Peer A

  2. When NAT-a receives the outgoing SYN from Peer A, it creates a mapping in its state machine. When NAT-b receives the outgoing SYN from Peer B, it creates a mapping in its state machine.

  3. Both SYN cross somewhere along the network path, then:

    SYN from Peer A reaches NAT-b, SYN from Peer B reaches NAT-a Depending on the timing of these events (where in the network the SYN cross), at least one of the NAT will let the incoming SYN through, and map it to the internal destination peer

  4. Upon receipt of the SYN, the peer sends a SYN+ACK back and the connection is established.

From WIKI.

Also to learn about TCP simultaneous open connection read from here. To learn about NAT filtering behavior see this answer.

like image 128
Tahlil Avatar answered Sep 28 '22 00:09

Tahlil