简体   繁体   中英

get my dhcp server ip address

My DHCP servers address is 192.168.0.1

But, I am assuming that other networks can have a different IP address for their DHCP server.

what is a good way to get my networks DHCP server IP address in C#

I have looked under the

System.Net.NetworkInformation

but cannot see anything I can call for this.

I suspect this is a simple thing to do as well?

Thanks

Information about a DHCP server that provided a IP address is interface specific since you can have multiple interfaces on the host, each of them connected to a different network with different DHCP servers. This information should be under a IPInterfaceProperties.DhcpServerAddresses based on the MSDN documentation. The sample code from their docs:

public static void DisplayDhcpServerAddresses()
{
    Console.WriteLine("DHCP Servers");
    NetworkInterface[] adapters  = NetworkInterface.GetAllNetworkInterfaces();
    foreach (NetworkInterface adapter in adapters)
    {

        IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
        IPAddressCollection addresses = adapterProperties.DhcpServerAddresses;
        if (addresses.Count >0)
        {
            Console.WriteLine(adapter.Description);
            foreach (IPAddress address in addresses)
            {
                Console.WriteLine("  Dhcp Address ............................ : {0}", 
                    address.ToString());
            }
            Console.WriteLine();
        }
    }
}

You could try this:

Console.WriteLine("DHCP Servers");
NetworkInterface[] adapters  = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{

    IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
    IPAddressCollection addresses = adapterProperties.DhcpServerAddresses;
    if (addresses.Count >0)
    {
        Console.WriteLine(adapter.Description);
        foreach (IPAddress address in addresses)
        {
            Console.WriteLine("  Dhcp Address ............................ : {0}", 
                address.ToString());
        }
        Console.WriteLine();
    }
}

More info: Here

With System.Linq , you can make this even simpler:

public static IEnumerable<IPAddress> GetDhcpServers() =>
   NetworkInterface.GetAllNetworkInterfaces().
   SelectMany(i => i.GetIPProperties().DhcpServerAddresses).Distinct();

If you only want active servers, you can filter by the adapter's OperationalStatus :

public static IEnumerable<IPAddress> GetActiveDhcpServers() =>
   NetworkInterface.GetAllNetworkInterfaces().
   Where(i => i.OperationalStatus == OperationalStatus.Up).
   SelectMany(i => i.GetIPProperties().DhcpServerAddresses).Distinct();

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