连接2台不同的基础计算机

时间:2009-12-12 22:17:17

标签: c# tcp sockets udp subnet

如何连接2台不同子网的计算机?例如,让我们说以下内容:

192.168.1.92连接到外部可见222.251.155.20。 192.168.1.102连接到外部可见223.251.156.23。

现在有两台机器连接的中间人服务器,因此他们可以协商彼此的内部和外部IP,并打开一个监听端口。我目前知道如何做到这一点的唯一方法是端口转发。

我非常精通C#套接字,只是不知道如何连接两个不同子网上的两台计算机。

我有一个服务器,客户端连接到有域名的服务器,通常客户端将在家用路由器后面,我希望它们能够直接相互共享信息。

1 个答案:

答案 0 :(得分:1)

您正在寻找的是NAT traversal。 没有中继服务器且没有端口转发的解决方案通常使用某种形式的UDP hole punching。 标准化机制是STUN(即Interactive Connectivity Establishment)。

注意:通过UDP实现UDP打孔和可靠的文件传输并非易事。最好的选择可能是使用UPnP或NAT-PMP自动设置端口转发。两者都有库,例如Mono.Natsources):

class NatTest
{
    public Start ()
    {
        // Hook into the events so you know when a router
        // has been detected or has gone offline
        NatUtility.DeviceFound += DeviceFound;
        NatUtility.DeviceLost += DeviceLost;

        // Start searching for upnp enabled routers
        NatUtility.StartDiscovery ();
    }

    void DeviceFound(object sender, DeviceEventArgs args)
    {
        // This is the upnp enabled router
        INatDevice device = args.Device;

        // Create a mapping to forward external port 3000 to local port 1500
        device.CreatePortMap(new Mapping(Protocol.Tcp, 1500, 3000));

        // Retrieve the details for the port map for external port 3000
        Mapping m = device.GetSpecificMapping(Protocol.Tcp, 3000);

        // Get all the port mappings on the device and delete them
        foreach (Mapping mp in device.GetAllMappings())
            device.DeletePortMap(mp);

        // Get the external IP address
        IPAddress externalIP = device.GetExternalIP();
    }

    private void DeviceLost (object sender, DeviceEventArgs args)
    {
        INatDevice device = args.Device;

        Console.WriteLine ("Device Lost");
        Console.WriteLine ("Type: {0}", device.GetType().Name);
    }
}
相关问题