Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 453
Rishav Avatar asked May 21 '18 17:05

Rishav


1 Answers

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;
like image 96
DavidG Avatar answered Sep 23 '22 12:09

DavidG