System.Net.NetworkInformation in .NET Fx 2.0
One of the things I'm really digging about .NET Fx 2.0 right now is the ability to interrogate network cards on my machine. For example, I've often wanted a hassle-free way to find out IP address information, DNS specifics and trap events (such as cables being removed or loss of connectivity).
The System.Net.NetworkInformation namespace gives me this.
Here's is a quick snippet of code that detects network interface changes (e.g. you pull out or plug in the ethernet cable), and displays the new status in the console. IMO this is very useful for developing Smart Client applications that need to switch context based on their network state.
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.NetworkInformation;
namespace NetworkTest
{
class Program
{
static void Main(string[] args)
{
NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
Console.Write("Now Listening for network changes... Press Enter to Quit.\n\n");
Console.In.Read();
}
static void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
DisplayNetworkInfo();
}
static void DisplayNetworkInfo()
{
if (!NetworkInterface.GetIsNetworkAvailable())
{
Console.WriteLine("Connectivity has been lost.\n");
}
else
{
Console.WriteLine("Connectivity has been detected.\n");
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
Console.WriteLine("Interface: " + ni.Name);
Console.WriteLine("MAC Address: " + ni.GetPhysicalAddress().ToString());
Console.WriteLine("Speed: " + ni.Speed.ToString());
DisplayIPAddrs(ni);
Console.WriteLine("\n");
}
}
}
static void DisplayIPAddrs(NetworkInterface ni)
{
foreach (IPAddressInformation anycastAddr in ni.GetIPProperties().AnycastAddresses)
{
Console.WriteLine("Anycast Address: " + anycastAddr.Address.ToString());
}
foreach (IPAddressInformation unicastAddr in ni.GetIPProperties().UnicastAddresses)
{
Console.WriteLine("Unicast Address: " + unicastAddr.Address.ToString());
}
foreach (IPAddressInformation multicastAddr in ni.GetIPProperties().MulticastAddresses)
{
Console.WriteLine("Multicast Address: " + multicastAddr.Address.ToString());
}
foreach (IPAddress dhcpAddr in ni.GetIPProperties().DhcpServerAddresses)
{
Console.WriteLine("DHCP Address: "+dhcpAddr.ToString());
}
}
}
}