检测是否在 windows 设置中选择了 "Obtain IP address automatically"

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

我制作了一个可以使用 C# 检测、设置和切换 IPv4 设置的 winform 应用程序。当用户想从 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

}

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

获取提示:

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

    }
}

但问题是我无法检测当前 IP 是手动设置还是自动分配,尽管我可以 select select 自动从 DHCP Automatic_IP 方法。 ManagementObject.InvokeMethod("EnableDHCP", null); 可以很容易地将它设置为 自动获取 IP 地址 但是我无法在应用程序首次启动时检查 IP 是自动设置还是手动设置。

我进行了一些挖掘,发现类似 this. Although a very similar post exists here 的帖子,但这是关于 DNS 而不是 IP 设置的。

基本上我想找到哪个选项是 selected:

ManagementObject class 有一堆 properties 可以使用,对于网络适配器,其中一个称为 DHCPEnabled。这会告诉您网络接口是否正在自动获取 IP 地址。例如:

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

替代方法使用 NetworkInformation class:

using System.Net.NetworkInformation;

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

所有启用了 DHCP 的网络接口及其 IP 地址:

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

样本class收集和检查NetworkInformationclass可以提供的一些(有限的)信息:

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();

统计特征:

IPGlobalStatistic
TcpConnectionInformation
IPInterfaceStatistics

事件:

NetworkChange
NetworkAddressChanged
NetworkAvailabilityChanged

实用程序:
Ping