【问题标题】:Network Selection网络选择
【发布时间】:2012-04-21 14:01:19
【问题描述】:

我正在使用 TcpClient 和套接字开发 P2P 聊天应用程序。

我写了下面的代码来接受tcpclient:

IPAddress[] ip = Dns.GetHostAddresses(Dns.GetHostName());
IPAddress ip_local = Dns.GetHostAddresses(Dns.GetHostName())[0];
// IPAddress ip_local = IPAddress.Parse(ip_local);
TcpListener tcpl = new TcpListener(new IPEndPoint(ip_local, 9277));
while (true)
{
    try
    {
        tcpl.Start();
        TcpClient tcpClient = tcpl.AcceptTcpClient();
        StateObject state = new StateObject();
        state.workSocket = tcpClient.Client;
        tcpClient.Client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
            new AsyncCallback(OnReceive), state);
    }
    catch (Exception ex)
    {

    }
}

问题在于它每次都选择不同的网络[因为我有 1 个 LAN 和 2 个 VMWARE 网络]。那么问题来了,如何强制它获取局域网的网络地址,即特定的网络?

【问题讨论】:

  • 语言标记问题。

标签: c# networking


【解决方案1】:

您正在从 DNS 主机名中获取本地 IP 地址。问题可能是其中一个或两个(但按顺序)自动将其地址注册为您的主机名。您有几个选择:1)更改 DNS 主机名以指向正确的地址; 2)具体获取地址,函数GetHostAddresses将IP地址作为参数或主机名。

【讨论】:

    【解决方案2】:

    查看this answer,它建议不要使用Dns.GetHostAddresses,并提供了更彻底的方法。

    不确定,但我认为System.Net.NetworkInformation.IPInterfaceProperties 在这里可能很有趣。

    【讨论】:

      【解决方案3】:

      所以这就是如何检测正确的 localIP 以传递 TcpListener 构造函数,就像您似乎已经在做的那样:

      TcpListener tcpl = new TcpListener(new IPEndPoint(ip_local, 9277));
      

      这是我们在开源网络框架networkComms.net 中解决的一个特别重要的问题。如果您查看第 80 行 here 上的 Getter for LocalIP,有几种方法:

      1. Ping 已知的外部 IP,然后使用操作系统选择的网络适配器(使用 iphlpapi.dll,因此仅支持 windows)。
      2. 使用 NetworkInterface.GetAllNetworkInterfaces() 搜索所有已知的 IP 适配器并选择 IP 与提供的前缀匹配的一个,例如 192.* 等。

      关于如何使用 networkComms.net 的基本 11 示例可能也很有趣,here

      【讨论】:

        猜你喜欢
        • 2013-05-03
        • 2017-05-16
        • 1970-01-01
        • 2019-07-30
        • 1970-01-01
        • 1970-01-01
        • 2016-10-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多