简体   繁体   English

在 C# .NET 中检查静态或动态 IP 地址?

[英]Checking static or dynamic IP address in C# .NET?

I am building a pretty basic form app.我正在构建一个非常基本的表单应用程序。

I can get a list of IP addresses available on the local machine.我可以获得本地计算机上可用的 IP 地址列表。 However, I want to also determine how these addresses are obtained (eg DHCP or static).但是,我还想确定如何获取这些地址(例如 DHCP 或静态)。 How can I tell if a static IP address is configured on the system?如何判断系统上是否配置了静态 IP 地址?

The goal is to inform a novice end-user (who may have no knowledge of the network setup, or how to obtain it) what static IP addresses are available.目标是告知新手最终用户(他们可能不了解网络设置或如何获取网络设置)哪些静态 IP 地址可用。 And, if no static address exist, inform them that one needs to be setup.并且,如果不存在静态地址,则通知他们需要设置一个。

TIA TIA

Better use Net.NetworkInformation due to better performance compared to WMI由于与 WMI 相比具有更好的性能,因此更好地使用 Net.NetworkInformation

    using System.Net.NetworkInformation;

    NetworkInterface[] niAdpaters = NetworkInterface.GetAllNetworkInterfaces();

    private Boolean GetDhcp(Int32 iSelectedAdpater)
    {
        if (niAdpaters[iSelectedAdpater].GetIPProperties().GetIPv4Properties() != null)
        {
            return niAdpaters[iSelectedAdpater].GetIPProperties().GetIPv4Properties().IsDhcpEnabled;
        }
        else
        {
            return false;
        }
    }

You can use WMI to get network adapter configuration.您可以使用 WMI 来获取网络适配器配置。

For an example, have a look at http://www.codeproject.com/KB/system/cstcpipwmi.aspx .例如,请查看http://www.codeproject.com/KB/system/cstcpipwmi.aspx The 'DhcpEnabled' property on the network adapter should tell you if the address is obtained via dhcp or not.网络适​​配器上的“DhcpEnabled”属性应该告诉您地址是否是通过 dhcp 获得的。

I use two method(s) as follows:我使用以下两种方法:

public static string GetLocalIPAddress()
{
    var host = Dns.GetHostEntry(Dns.GetHostName());

    foreach (var ip in host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            return ip.ToString();

        }

    }

    return "unknown";
}

public static string GetLocalIpAllocationMode()
{
    string MethodResult = "";
    try
    {
        ManagementObjectSearcher searcherNetwork = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_NetworkAdapterConfiguration");

        Dictionary<string, string> Properties = new Dictionary<string, string>();

        foreach (ManagementObject queryObj in searcherNetwork.Get())
        {
            foreach (var prop in queryObj.Properties)
            {
                if (prop.Name != null && prop.Value != null && !Properties.ContainsKey(prop.Name))
                {
                    Properties.Add(prop.Name, prop.Value.ToString());

                }

            }

        }

        MethodResult = Properties["DHCPEnabled"].ToLower() == "true" ? "DHCP" : "Static";

    }
    catch (Exception ex)
    {
        ex.HandleException();

    }

    return MethodResult;

}

GetLocalIpAllocationMode() will tell you whether the ip is static or allocated via dhcp , whereas GetLocalIPAddress() will tell you the local ip itself. GetLocalIpAllocationMode()会告诉您ipstatic还是通过dhcp分配的,而GetLocalIPAddress()会告诉您本地ip本身。

Unfortunately you'll probably have to use WMI.不幸的是,您可能不得不使用 WMI。 There might be another way, but this is the only way that I know.可能还有另一种方式,但这是我所知道的唯一方式。

This code will output all of the information about every adapter on your system.此代码将输出有关系统上每个适配器的所有信息。 I think the name is "DHCPEnabled" of the property you want.我认为名称是您想要的属性的“DHCPEnabled”。

ManagementObjectSearcher searcherNetwork =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_NetworkAdapterConfiguration");

foreach (ManagementObject queryObj in searcherNetwork.Get())
{
     foreach (var prop in queryObj.Properties)
     {
         Console.WriteLine(string.Format("Name: {0} Value: {1}", prop.Name, prop.Value));
     }
}

The answers here helped me with my own project, but I had to do some research before I found out how to use the suggested method.这里的答案帮助我完成了我自己的项目,但在我发现如何使用建议的方法之前,我必须做一些研究。

Adding using System.Management;添加使用System.Management; to your code doesn't work by itself.对您的代码本身不起作用。 You need to add a reference to System.Management before the namespace will be recognized.在识别命名空间之前,您需要添加对 System.Management 的引用。 (For new people like me who tried this and were getting the error "managementclass could not be found"). (对于像我这样尝试过并收到错误“找不到管理类”的新人)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM