检测是否在Windows设置中选择"自动获取IP地址"

Ris*_*hav 5 .net c# wmi winforms

我创建了一个winform应用程序,可以使用C#检测,设置和切换IPv4设置.当用户想要从DHCP自动获取IP时,我会调用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

}
Run Code Online (Sandbox Code Playgroud)

Getip方法中,我提取当前的IP地址,子网,网关和DNS,而不管所有这些都可以由DHCP手动设置或自动分配,并使用该Update_current_data()方法更新标签中的这些值.

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;
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

但问题是我无法检测当前IP是手动设置还是自动分配,尽管我可以从该方法中自动从DHCP中选择Automatic_IP.将ManagementObject.InvokeMethod("EnableDHCP", null);可以很容易地将它设置为自动获取IP地址,但我也没办法,以检查是否第一次启动应用程序时,IP是自动或手动设置.

我做了一些挖掘,发现了类似的帖子像这样.虽然此处存在非常类似的帖子,但这是关于DNS而不是IP设置.

基本上我想找到选择的选项:

自动

Dav*_*idG 4

该类ManagementObject有许多可以使用的属性,对于网络适配器,其中一个称为DHCPEnabled。这会告诉您网络接口是否自动获取 IP 地址。例如:

var isDHCPEnabled = (bool)motemp.Properties["DHCPEnabled"].Value;
Run Code Online (Sandbox Code Playgroud)