Reputation: 7324
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
Upvotes: 0
Views: 3933
Reputation: 348
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();
Upvotes: 0
Reputation: 484
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
Upvotes: 2
Reputation: 2202
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();
}
}
}
Upvotes: 3