0

I'm trying to make NAT Traversal using STUN (https://stunprotocol.org/)

As I understand, I need to follow these steps:

  1. Bind TCP Client to some local port
  2. Connect to STUN, receive external IP & Port
  3. Start TCP server at the same local port, without closing connection to STUN server
  4. Share external IP & port to client
  5. Client connects by external address & port

So I connected to STUN server via TCP Client. Then I used library to generate an STUN request and parse response (https://www.nuget.org/packages/STUN/) and successfully got my external port.

After this I launched Client, enter the external address, tried to connect and.. nothing happened.

Server:

// Connecting to stun and receiving external IP & port
IPEndPoint clientEndpoint = new(IPAddress.Any, 7777);
TcpClient tcp = new();
tcp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
tcp.Client.Bind(clientEndpoint);

string externalIp = await GetExternalHostFromStun(tcp);
Console.WriteLine($"External host: {externalIp}");

var server = new TcpListener(clientEndpoint);
server.AllowNatTraversal(true);
server.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);

// Starting server on the same local port
server.Start();

server.AcceptTcpClient();
Console.WriteLine("CONNECTED!");

Client:

Console.WriteLine("Enter remote port");
string portStr = Console.ReadLine();
int port = int.Parse(portStr);

var tcp = new TcpClient();
tcp.Connect(MY_REAL_IP, port);

Console.WriteLine("CONNECTED");
Andrew
  • 129
  • 9
  • Add to end of each program Console.ReadLine() so application doesn't end and you can see message if connection completed. – jdweng Mar 08 '23 at 00:45

0 Answers0