0

我需要找出本地 IP 地址,因此我使用了以下代码:

IPHostEntry host;
string localIP = "";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
    if (ip.AddressFamily == AddressFamily.InterNetwork)
    {
        localIP = ip.ToString();
        break;
    }
}
return localIP;

我发现当一台 PC 有多个 IP 时,AddressFamily.InterNetwork我总是得到第一个。但是我找不到任何属性来找出活动 IP。

我怎样才能获得正确的IP?

感谢您的提示!

4

3 回答 3

0
    static string GetActiveIP()
            {
                string ip = "";
                foreach (NetworkInterface f in NetworkInterface.GetAllNetworkInterfaces())
                {
                    if (f.OperationalStatus == OperationalStatus.Up)
                    {
                        IPInterfaceProperties ipInterface = f.GetIPProperties();
                        if (ipInterface.GatewayAddresses.Count > 0)
                        {`enter code here`
                            foreach (UnicastIPAddressInformation unicastAddress in ipInterface.UnicastAddresses)
                            {
                                if ((unicastAddress.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) && (unicastAddress.IPv4Mask.ToString() != "0.0.0.0"))
                                {
                                    ip = unicastAddress.Address.ToString();
break;

                                }                          
                            }`enter code here`
                        }


                    }
                }
                return ip;
            }
于 2014-04-22T13:58:09.560 回答
0

我前段时间从网上捡到了这个。

        string strHostName = System.Net.Dns.GetHostName(); ;
        IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
        IPAddress[] addr = ipEntry.AddressList;

这应该会给你一个包含你电脑的所有 IP 地址的数组。

于 2013-10-25T13:57:08.373 回答
0

Bwall 在此线程中发布了一个合适的解决方案。

foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
   if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
   {
       Console.WriteLine(ni.Name);
       foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
       {
           if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
           {
               Console.WriteLine(ip.Address.ToString());
           }
       }
   }  
}

这段代码的重要之处在于,它只列出了以太网和无线接口的 IP 地址。我怀疑您是否会激活串行连接,因此这很可能无关紧要。或者,您可以随时编辑 if 语句。

//编辑 如果您只想使用实际连接到互联网的 IP 地址,请使用Hosam Aly解决方案

这是他的代码:

static IPAddress getInternetIPAddress()
{
    try
    {
        IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName());
        IPAddress gateway = IPAddress.Parse(getInternetGateway());
        return findMatch(addresses, gateway);
    }
    catch (FormatException e) { return null; }
}

static string getInternetGateway()
{
    using (Process tracert = new Process())
    {
        ProcessStartInfo startInfo = tracert.StartInfo;
        startInfo.FileName = "tracert.exe";
        startInfo.Arguments = "-h 1 www.example.com
        startInfo.UseShellExecute = false;
        startInfo.RedirectStandardOutput = true;
        tracert.Start();

        using (StreamReader reader = tracert.StandardOutput)
        {
            string line = "";
            for (int i = 0; i < 5; ++i)
                line = reader.ReadLine();
            line = line.Trim();
            return line.Substring(line.LastIndexOf(' ') + 1);
        }
    }
}

static IPAddress findMatch(IPAddress[] addresses, IPAddress gateway)
{
    byte[] gatewayBytes = gateway.GetAddressBytes();
    foreach (IPAddress ip in addresses)
    {
        byte[] ipBytes = ip.GetAddressBytes();
        if (ipBytes[0] == gatewayBytes[0]
            && ipBytes[1] == gatewayBytes[1]
            && ipBytes[2] == gatewayBytes[2])
        {
            return ip;
        }
    }
    return null;
}

它的基本作用是跟踪到 www.example.com 的路由并从那里处理正确的 IP。我在我的机器上测试了代码,需要将迭代从 9 更改为 5 以从流中获取正确的行。你最好重新检查它,否则你可能会进入 NullReferenceException 因为line将是null.

于 2013-10-25T13:57:29.910 回答