It’s time to add some value to the project. For a long time I’ve been thinking about the UI for adding/editing/removing hosts and I’m still not sure which one will be good enough. As a result, I’ve delayed this interface for further steps, today I’ll show how to discover network configuration of a computer and find out IP addresses of gateway, DNS servers, etc. to fill in the list of hosts.
The Base Class Library (BCL) doesn’t contain any network configuration-related classes mostly because it must be platform independent. So we have to interoperate somehow with machine-dependent components such as Windows Management Instrumentation (WMI). Luckily, BCL provides the System.Management.ManagementClass type which will help. In order to read network adapter’s configuration we will use “Win32_NetworkAdapterConfiguration” WMI class.
// Creating the desired WMI class var mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); // Getting all instances of the specified WMI class var items = mc.GetInstances();
Having fetched all instances of WMI class we read the required properties and form the list of hosts. The properties that are interesting for us are:
- DefaultIPGateway
- DHCPServer
- DNSServerSearchOrder
- WINSPrimaryServer
- WINSSecondaryServer
Here is the code:
var gateList = new HashSet(); var dnsList = new HashSet (); var dhcpList = new HashSet (); var winsList = new HashSet (); foreach (var item in items) { // Skipping devices that are not IP-enabled if (!((bool)item["ipEnabled"])) continue; var addresses = (string[])item["DefaultIPGateway"]; if (addresses != null && addresses.Length > 0) foreach (var gw in addresses) gateList.Add(gw); addresses = (string[])item["DNSServerSearchOrder"]; if (addresses != null && addresses.Length > 0) foreach (var dns in addresses) dnsList.Add(dns); string dhcp = (string)item["DHCPServer"]; if (!string.IsNullOrEmpty(dhcp)) dhcpList.Add(dhcp); string wins1 = (string)item["WINSPrimaryServer"]; if (!string.IsNullOrEmpty(wins1)) winsList.Add(wins1); string wins2 = (string)item["WINSSecondaryServer"]; if (!string.IsNullOrEmpty(wins2)) winsList.Add(wins2); } foreach (var address in gateList) Hosts.Add(new HostViewModel(address, "Gateway")); foreach (var address in dnsList) Hosts.Add(new HostViewModel(address, "DNS")); foreach (var address in dhcpList) Hosts.Add(new HostViewModel(address, "DHCP")); foreach (var address in winsList) Hosts.Add(new HostViewModel(address, "WINS"));
Depending on the number and configuration of your network interfaces, the NetMonitor will automatically discover and fill in the list of hosts to monitor.
Here are my automatically discovered hosts. As you see, my Wi-Fi router also acts like a DNS server & a DHCP server, the other two DNS servers (10.0.0.x) are provided by additional VPN connection. BTW, it might be a good idea to remove duplicate entries from the list.
Download latest binaries or play with the code.
No comments:
Post a Comment