Rishav
Rishav

Reputation: 4088

Detecting if "Obtain IP address automatically" is selected in windows settings

I made an winform application that can detect , set and toggle IPv4 settings using C#. When the user wants to get IP automatically from DHCP I call Automatic_IP():

Automatic_IP:

private void Automatic_IP()
{
    ManagementClass mctemp = new ManagementClass("Win32_NetworkAdapterConfiguration");
    ManagementObjectCollection moctemp = mctemp.GetInstances();

    foreach (ManagementObject motemp in moctemp)
    {
        if (motemp["Caption"].Equals(_wifi)) //_wifi is the target chipset
        {
            motemp.InvokeMethod("EnableDHCP", null);
            break;
        }
    }

    MessageBox.Show("IP successfully set automatically.","Done!",MessageBoxButtons.OK,MessageBoxIcon.Information);

    Getip(); //Gets the current IP address, subnet, DNS etc
    Update_current_data(); //Updates the current IP address, subnets etc into a labels

}

And in the Getip method I extract the current IP address, subnet, gateway and the DNS regardless of the fact that all these could be manually set or automatically assigned by DHCP and update those values in the labels using the Update_current_data() method.

Getip:

public bool Getip()
{
    ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
    ManagementObjectCollection moc = mc.GetInstances();

    foreach (ManagementObject mo in moc)
    {
        if(!chipset_selector.Items.Contains(mo["Caption"]))
            chipset_selector.Items.Add(mo["Caption"]);

        if (mo["Caption"].Equals(_wifi))
        {
            ipadd = ((string[])mo["IPAddress"])[0];
            subnet = ((string[])mo["IPSubnet"])[0];
            gateway = ((string[])mo["DefaultIPGateway"])[0];
            dns = ((string[])mo["DNSServerSearchOrder"])[0];
            break;
        }

    }
}

But the problem is I cannot detect if the current IP is manually set or automatically assigned, though I can select select automatically from DHCP from the Automatic_IP method. The ManagementObject.InvokeMethod("EnableDHCP", null); can easily set it to obtain IP address automatically but I have no way to check if IP is set automatically or manually when the Application first starts.

I did some digging and found similar posts like this. Although a very similar post exists here but this is about DNS and not IP settings.

Basically I want to find which option is selected:

Automatic

Upvotes: 5

Views: 1139

Answers (2)

Jimi
Jimi

Reputation: 32278

Alternative method using NetworkInformation class:

using System.Net.NetworkInformation;

NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
IPInterfaceProperties IPProperties = Interfaces[0].GetIPProperties();
IPv4InterfaceProperties IpV4Properties = IPProperties.GetIPv4Properties();
bool DhcpEnabed = IpV4Properties.IsDhcpEnabled;

All Network Interfaces with DHCP enabled and their IP Address:

List<NetworkInterface> DhcpInterfaces = Interfaces
    .Where(IF => (IF.Supports(NetworkInterfaceComponent.IPv4)) &&
          (IF.GetIPProperties().GetIPv4Properties().IsDhcpEnabled))
    .ToList();

if (DhcpInterfaces != null)
{
    IEnumerable<UnicastIPAddressInformation> IpAddresses = 
        DhcpInterfaces.Select(IF => IF.GetIPProperties().UnicastAddresses.Last());
}

A sample class to collect and inspect some (a limited number) of the informations that the NetworkInformation class can provide:

using System.Net.NetworkInformation;

public class NetWorkInterfacesInfo
{
    public string Name { get; set; }
    public string Description { get; set; }
    public PhysicalAddress MAC { get; set; }
    public List<IPAddress> IPAddresses { get; set; }
    public List<IPAddress> DnsServers { get; set; }
    public List<IPAddress> Gateways { get; set; }
    public bool DHCPEnabled { get; set; }
    public OperationalStatus Status { get; set; }
    public NetworkInterfaceType InterfaceType { get; set; }
    public Int64 Speed { get; set; }
    public Int64 BytesSent { get; set; }
    public Int64 BytesReceived { get; set; }
}

List<NetWorkInterfacesInfo> NetInterfacesInfo = new List<NetWorkInterfacesInfo>();

NetInterfacesInfo = DhcpInterfaces.Select(IF => new NetWorkInterfacesInfo()
{
    Name = IF.Name,
    Description = IF.Description,
    Status = IF.OperationalStatus,
    Speed = IF.Speed,
    InterfaceType = IF.NetworkInterfaceType,
    MAC = IF.GetPhysicalAddress(),
    DnsServers = IF.GetIPProperties().DnsAddresses.Select(ipa => ipa).ToList(),
    IPAddresses = IF.GetIPProperties().UnicastAddresses.Select(ipa => ipa.Address).ToList(),
    Gateways = IF.GetIPProperties().GatewayAddresses.Select(ipa => ipa.Address).ToList(),
    DHCPEnabled = IF.GetIPProperties().GetIPv4Properties().IsDhcpEnabled,
    BytesSent = IF.GetIPStatistics().BytesSent,
    BytesReceived = IF.GetIPStatistics().BytesReceived
}).ToList();

Statistical features:

IPGlobalStatistic
TcpConnectionInformation
IPInterfaceStatistics

Events:

NetworkChange
NetworkAddressChanged
NetworkAvailabilityChanged

Utilities:
Ping

Upvotes: 3

DavidG
DavidG

Reputation: 119076

The ManagementObject class has a bunch of properties you can use, and for the network adapters one of them is called DHCPEnabled. This tells you if the network interface is obtaining IP an address automatically. For example:

var isDHCPEnabled = (bool)motemp.Properties["DHCPEnabled"].Value;

Upvotes: 4

Related Questions