I'm trying to make NAT Traversal using STUN (https://stunprotocol.org/)
As I understand, I need to follow these steps:
- Bind TCP Client to some local port
- Connect to STUN, receive external IP & Port
- Start TCP server at the same local port, without closing connection to STUN server
- Share external IP & port to client
- 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");