Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Using the APIs Defined in the System.Net.NetworkInformation Namespace

0.00/5 (No votes)
30 Dec 2009 1  
An article that uses C# to demonstrate how to gather network information

Obtaining Network Information

Using the APIs Defined in the System.Net.NetworkInformation Namespace

There are times when you need to obtain some general information about the state of the network around you. When writing code in C#, you can use a number of APIs defined in the System.Net.NetworkInformation namespace. These enable you to query things such as your network interface card (NIC) status, current network traffic, DNS and IP address information, or even ping a remote server. This article has referenced both MSDN and Professional .NET Framework 2.0 to provide small programs that can be used to query network device information and status, as well as querying the IPv4 addresses in that network traffic. This could useful for security purposes. The router is there to route the data packets—it has no interest in the data contained in those packets. But it must perform an Address Resolution Protocol. If an IP number has been cached after an ARP request to a reply, then that 32 bit IP number must be correlated to the 48 bit MAC number of the destination machine. Not only is there no mathematical relation between an IP number and an MAC number, there is also no way to verify the source origin of the IP. Unless the known and expected IP addresses are explicitly written to the router’s disk, they will be overwritten as more come in. But before blowing the security horn, we’ll just write some code to inform us of the activity:

using System;
using System.Net;
using System.Net.NetworkInformation;
public sealed class Program {
public static void Main() {
DisplayUnicastAddresses();
}

public static void DisplayUnicastAddresses()
{
    Console.WriteLine("Unicast Addresses");
    NetworkInterface[] adapters  = NetworkInterface.GetAllNetworkInterfaces();
    foreach (NetworkInterface adapter in adapters)
    {
        IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
        UnicastIPAddressInformationCollection uniCast = adapterProperties.UnicastAddresses;
        if (uniCast.Count >0)
        {
            Console.WriteLine(adapter.Description);
            string lifeTimeFormat = "dddd, MMMM dd, yyyy  hh:mm:ss tt";
            foreach (UnicastIPAddressInformation uni in uniCast)
            {
                DateTime when;

                Console.WriteLine
		("  Unicast Address ......................... : {0}", uni.Address);
                Console.WriteLine
		("     Prefix Origin ........................ : {0}", uni.PrefixOrigin);
                Console.WriteLine
		("     Suffix Origin ........................ : {0}", uni.SuffixOrigin);
                Console.WriteLine
		("     Duplicate Address Detection .......... : {0}", 
                    uni.DuplicateAddressDetectionState);

                // Format the lifetimes as Sunday, February 16, 2003 11:33:44 PM
                // if en-us is the current culture.

                // Calculate the date and time at the end of the lifetimes.    
                when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.AddressValidLifetime);
                when = when.ToLocalTime();    
                Console.WriteLine("     Valid Life Time ...................... : {0}", 
                    when.ToString(lifeTimeFormat,
			System.Globalization.CultureInfo.CurrentCulture)
                );
                when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.AddressPreferredLifetime);   
                when = when.ToLocalTime();
                Console.WriteLine("     Preferred life time .................. : {0}", 
                    when.ToString(lifeTimeFormat,
			System.Globalization.CultureInfo.CurrentCulture)
                ); 

                when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.DhcpLeaseLifetime);
                when = when.ToLocalTime(); 
                Console.WriteLine("     DHCP Leased Life Time ................ : {0}", 
                    when.ToString(lifeTimeFormat,
			System.Globalization.CultureInfo.CurrentCulture)
                );
            }
            Console.WriteLine();
        }
    }
  }
}

The output shows that things are configured normally. The router is not dumping its ARP cache, so it would appear that there are no attackers sending fake requests for ARP to poison our cache. Here is the output:

Unicast Addresses
Intel(R) Wireless WiFi Link 4965AGN
  Unicast Address ......................... : fe80::6932:849e:6838:35c8%12
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Preferred
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:05:42 AM
  Unicast Address ......................... : 192.168.1.101
     Prefix Origin ........................ : Dhcp
     Suffix Origin ........................ : OriginDhcp
     Duplicate Address Detection .......... : Preferred
     Valid Life Time ...................... : Thursday, December 31, 2009  08:42:39 PM
     Preferred life time .................. : Thursday, December 31, 2009  08:42:39 PM
     DHCP Leased Life Time ................ : Friday, January 01, 2010  12:24:09 AM

Bluetooth Device (Personal Area Network)
  Unicast Address ......................... : fe80::98f6:cced:c44a:d8ad%10
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Deprecated
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:05:49 AM
  Unicast Address ......................... : 169.254.216.173
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Tentative
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:05:42 AM

Generic Marvell Yukon Chipset based Ethernet Controller
  Unicast Address ......................... : fe80::a1ce:c8bd:9784:a08b%8
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Deprecated
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:05:57 AM
  Unicast Address ......................... : 169.254.160.139
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Tentative
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:05:50 AM

Software Loopback Interface 1
  Unicast Address ......................... : ::1
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Preferred
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:06:10 AM
  Unicast Address ......................... : 127.0.0.1
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : WellKnown
     Duplicate Address Detection .......... : Preferred
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:06:10 AM

isatap.{EABD2F31-7318-43F3-B16F-F3F6589369E1}
  Unicast Address ......................... : fe80::5efe:192.168.1.101%16
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Deprecated
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:05:35 AM

Teredo Tunneling Pseudo-Interface
  Unicast Address ......................... : 2001:0:4137:9e50:1857:4cd:3f57:fe9a
     Prefix Origin ........................ : RouterAdvertisement
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Preferred
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:05:03 AM
  Unicast Address ......................... : fe80::1857:4cd:3f57:fe9a%13
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Preferred
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:05:03 AM

Here is some code that queries IPv4 address in that same network:

using System;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
public sealed class Application {
public static void Main() {
DisplayIPv4NetworkInterfaces();
}
public static void DisplayIPv4NetworkInterfaces()
{
    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
    IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
    Console.WriteLine("IPv4 interface information for {0}.{1}",
       properties.HostName, properties.DomainName);
    Console.WriteLine();   

    foreach (NetworkInterface adapter in nics)
    {
        // Only display information for interfaces that support IPv4.
        if (adapter.Supports(NetworkInterfaceComponent.IPv4) == false)
        {
            continue;
        }
        Console.WriteLine(adapter.Description);
        // Underline the description.
        Console.WriteLine(String.Empty.PadLeft(adapter.Description.Length,'='));
        IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
        // Try to get the IPv4 interface properties.
        IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties();

        if (p == null)
        {
            Console.WriteLine("No IPv4 information is available for this interface.");
            Console.WriteLine();
            continue;
        }
        // Display the IPv4 specific data.
        Console.WriteLine("  Index ............................. : {0}", p.Index);
        Console.WriteLine("  MTU ............................... : {0}", p.Mtu);
        Console.WriteLine("  APIPA active....................... : {0}", 
            p.IsAutomaticPrivateAddressingActive);
        Console.WriteLine("  APIPA enabled...................... : {0}", 
            p.IsAutomaticPrivateAddressingEnabled);
        Console.WriteLine("  Forwarding enabled................. : {0}", 
            p.IsForwardingEnabled);
        Console.WriteLine("  Uses WINS ......................... : {0}", 
            p.UsesWins);
        Console.WriteLine();
    }
 }
}

The above yields:

IPv4 interface information for John-PC.

Intel(R) Wireless WiFi Link 4965AGN
===================================
  Index ............................. : 12
  MTU ............................... : 1500
  APIPA active....................... : False
  APIPA enabled...................... : True
  Forwarding enabled................. : False
  Uses WINS ......................... : False

Bluetooth Device (Personal Area Network)
========================================
  Index ............................. : 10
  MTU ............................... : 1500
  APIPA active....................... : False
  APIPA enabled...................... : True
  Forwarding enabled................. : False
  Uses WINS ......................... : False

Generic Marvell Yukon Chipset based Ethernet Controller
=======================================================
  Index ............................. : 8
  MTU ............................... : 1500
  APIPA active....................... : False
  APIPA enabled...................... : True
  Forwarding enabled................. : False
  Uses WINS ......................... : False

Software Loopback Interface 1
=============================
No IPv4 information is available for this interface.

isatap.{71A2BA2A-7090-4221-BFAB-25FAEF97756D}
=============================================
No IPv4 information is available for this interface.

isatap.{1F7410AD-675A-4507-8E32-58E279C1DAFB}
=============================================
No IPv4 information is available for this interface.

isatap.{EABD2F31-7318-43F3-B16F-F3F6589369E1}
=============================================
No IPv4 information is available for this interface.

Teredo Tunneling Pseudo-Interface
=================================
No IPv4 information is available for this interface.

This basic information would be of help if one decides to completely deploy IPv6. That would be a very powerful migration.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here