5

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

Rishav
  • 3,818
  • 1
  • 31
  • 49
  • 1
    What about calling `ipconfig /all` and parsing the result? – Gerardo Grignoli May 21 '18 at 17:24
  • @GerardoGrignoli I'm sorry but I think that can only tell me about about the IP address and not if it was set automatically or manually. Also I am a more or less a beginner , if this can do it i'd be glad if you could elaborate or link me to some docs. – Rishav May 21 '18 at 17:28
  • Don't know about wmi, but you can get this info via `NetworkInterface.GetAllNetworkInterfaces()` API. – Evk May 21 '18 at 17:29
  • 2
    How about `var isDHCP = (bool)motemp.Properties["DHCPEnabled"].Value;`? – DavidG May 21 '18 at 17:31
  • @GerardoGrignoli Ipconfig's output is optimized for human reading, not really to be consumed by something else. It may even change its format in the future and can contain subtle differences, for example, it's localized together with Windows. There are APIs that give this information. – Alejandro May 21 '18 at 17:57

2 Answers2

4

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;
DavidG
  • 113,891
  • 12
  • 217
  • 223
  • Yea that works perfectly. Is there any such property for DNS and Internet Proxy? The [properties](https://msdn.microsoft.com/en-us/library/system.management.managementbaseobject.properties(v=vs.110).aspx) link you provided is not understandable by me sadly. Where can I find all the properties like "DHCPEnabled" and more ManagementObject Property? – Rishav May 21 '18 at 18:02
  • 1
    You can find all the properties of the Win32_NetworkAdapterConfiguration class here, https://msdn.microsoft.com/en-us/library/aa394217(v=vs.85).aspx – Bearcat9425 May 21 '18 at 18:26
2

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

Jimi
  • 29,621
  • 8
  • 43
  • 61