Search code examples
c#socketsipportforwardingupnp

How to let others to connect my pc without changing router settings


For example, if the computer's IP is under the Lan, it's 192.168.10.10 and Internet IP 10.10.10.10.

How to set up the Socket in C# to connect to the computer?

Some programs like "Ammyy Admin" do this.

public void Connect(string server)
{
    if (IsConnected)
        return;
    try
    {
        _server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPAddress[] allIp = Dns.GetHostAddresses(server);
        foreach (IPAddress ipa in allIp)
        {
            if (ipa.AddressFamily != AddressFamily.InterNetwork) continue;
            try
            {
                IPEndPoint remoteEndPoint = new IPEndPoint(ipa, DefaultPort);
                _server.Connect(remoteEndPoint);
                _server.SendBufferSize = SendReceveDataSize;
                _server.ReceiveBufferSize = SendReceveDataSize;
                DataHolder data = new DataHolder(_server, SendReceveDataSize);
                _server.BeginReceive(data.Buffer, 0, data.BufferSize, 0, ReceiveData, data);
                break;
            }
            catch { /* ignore */ }
        }
    }
    catch { /* ignore */ }
}

This code only works under Lan But I have to be able to connect to the user on the Internet


Solution

  • First add the Open.Nat package to your project, then with the following code you can temporarily forward a port on the router via the UPnP protocol. (Until you remove it via this library or the router is rebooted)

    var nat = new NatDiscoverer();
    var cts = new CancellationTokenSource(10000);
    var device = await nat.DiscoverDeviceAsync(PortMapper.Upnp, cts.Token);
    Console.WriteLine($"External IP: {await device.GetExternalIPAsync()}");
    await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, 8080, 80, "WebHosting"));
    

    Unfortunately I don't need my answer but I'm posting it for others who can use it.