找出活动的本地 IP

本文关键字:IP 活动 | 更新日期: 2023-09-27 18:36:56

我需要找出本地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?

感谢您的任何提示!

找出活动的本地 IP

我不久前从互联网上了解到这一点。

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

这应该为您提供PC的所有IP地址的数组。

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

    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;
            }