简体   繁体   中英

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. However, I want to also determine how these addresses are obtained (eg DHCP or static). How can I tell if a static IP address is configured on the system?

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. And, if no static address exist, inform them that one needs to be setup.

TIA

Better use Net.NetworkInformation due to better performance compared to WMI

    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.

For an example, have a look at 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.

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.

Unfortunately you'll probably have to use 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.

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; to your code doesn't work by itself. You need to add a reference to System.Management before the namespace will be recognized. (For new people like me who tried this and were getting the error "managementclass could not be found").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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