|
download source code
One of the cool features introduced with the .NET Framework 2.0 is the networking feature.
The .NET Framework 2.0 introduces a new namespace named System.Net.NetworkInformation that
encapsulates all of the network related features. This namespace exposes a number of classes
that provide useful information about the network such as network address, network traffic information,
and network cards configured on the local machine. In this article, we will examine some of the
important functionalities of the System.Net.NetworkInformation classes. While looking at these classes,
we will also look at examples to understand how to utilize them from a .NET application.
Introduction
The System.Net.NetworkInformation namespace contains a number of new classes that allow you to access network information about the local computer. The accessible information includes items such as the number of network cards configured on the machine, IP address, and the configuration settings of each card. Many of the classes in the NetworkInformation namespace provide respective static GetXXX methods to retrieve instances of whatever configuration or information object they represent.
System.Net.NetworkInformation Namespace
As mentioned before, the System.Net.NetworkInformation namespace provides an object model that represents network-related data such as addresses and traffic. It extends this model to provide notifications about the network if/when something occurs. The below table discusses some of the important classes in the System.Net.NetworkInformation namespace.
| Class |
Description |
| IPAddressInformation |
Allows you to get information (such as the IP address) about a network interface address |
| IPGlobalProperties |
Allows you to get information about the network connectivity (such as domain name, host name) of the local computer |
| IPGlobalStatistics |
As the name suggests, this class provides information about IP statistical data |
| IPInterfaceProperties |
Allows you to get information about the network interfaces that support IPv4 or IPv6 protocols |
| NetworkChange |
Allows you to detect changes in the network such as when the IP address of a network interface changes |
| NetworkInterface |
Represents the network interface and provides configuration and statistical information about a network interface |
| PhysicalAddress |
This class represents the MAC address for a network interface |
| Ping |
This class provides you with the ability to determine if a remote computer is accessible over the network |
| TcpStatistics |
Allows you to get information about TCP statistical data such as the current TCP connections, maximum allowed connections and so on |
| UdpStatistics |
Allows you to get UDP statistical information such as the number of UDP data grams that were received and sent |
For information about the rest of the classes in the System.Net.NetworkInformation namespace, please refer to the MSDN documentation.
Now that you have seen the important classes, let's look at how to leverage them. For the purposes of this article,
create a new Visual C# Windows Forms application named NetworkExample using Visual Studio 2005 as shown below.
Now that the project is created, let us focus on the following functionalities of the System.Net.NetworkInformation namespace.
- How to ping a remote computer
- How to retrieve DNS addresses
- How to display IP statistics
Let us start by looking at the Ping class that allows you to ping a remote computer.
How to Ping a Remote Computer
The Ping class allows you to check the accessibility of another computer over a TCP/IP-based network from managed code. Just as the name of the class indicates, it behaves similarly to the ping network command. It sends an ICMP echo request to a remote host and waits for an ICMP echo reply. Just as with the ping command, there is no guarantee the remote host is going to respond if there is a firewall between locations.
In the Windows Forms project, double click the form to open it. Drag and drop a ListBox named lstOutput onto the forms designer. Then add a command button named btnPing and modify its Click event to look like the following:
private void btnPing_Click(object sender, EventArgs e)
{
lstOutput.Items.Clear();
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
//Modify the default fragmentation behavior
options.DontFragment = true;
//Create a buffer of 32 bytes of data to be transmitted.
string data = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
PingReply reply = pingSender.Send("192.168.0.101",
timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
lstOutput.Items.Add("Address: " + reply.Address.ToString());
lstOutput.Items.Add("RoundTrip time: " + reply.RoundtripTime);
lstOutput.Items.Add("Time to live: " + reply.Options.Ttl);
lstOutput.Items.Add("Don't fragment: " + reply.Options.DontFragment);
lstOutput.Items.Add("Buffer size: " + reply.Buffer.Length);
}
}
In the above code, you start by creating an instance of the Ping and PingOptions classes respectively. The PingOptions class enables you to configure how the data packets are transmitted across the network. In this example, you set the DontFragment property of the PingOptions class to true to indicate that the data be sent in one single packet. Then you declare a string variable named data that holds the data to be transmitted. Then you convert that data into a byte array for transmission through the Send() method of the Ping class. To the Send() method, you supply the remote computer's IP address, timeout in milliseconds, data in the form of byte array and the PingOptions object. Note that the Send() method pings the remote computer synchronously. To asynchronously ping the remote computer, you leverage the SendAsync() method of the Ping class.
PingReply reply = pingSender.Send("192.168.0.101",
timeout, buffer, options);
As you can see from the above line of code, the Send() method returns an object of type PingReply, which you can examine to check the status of the ping operation. The Status property of the PingReply object returns an enumeration of type IPStatus that you can examine to see if the ping is successful. If it is successful, you then display the various properties of the PingReply object in the ListBox control.
if (reply.Status == IPStatus.Success)
{
lstOutput.Items.Add("Address: " + reply.Address.ToString());
lstOutput.Items.Add("RoundTrip time: " + reply.RoundtripTime);
lstOutput.Items.Add("Time to live: " + reply.Options.Ttl);
lstOutput.Items.Add("Don't fragment: " + reply.Options.DontFragment);
lstOutput.Items.Add("Buffer size: " + reply.Buffer.Length);
}
Build the project and run the application by pressing F5. You should see an output that is somewhat similar to the following screenshot.
How to Retrieve DNS Addresses
In this section, we will see how to retrieve DNS addresses using the various classes of the System.Net.NetworkInformation namespace. Start by opening the form designer and add a command button named btnDisplayDNSAddresses. Modify the Click event of the button to look as shown below.
private void btnDisplayDNSAddresses_Click(object sender, EventArgs e)
{
lstOutput.Items.Clear();
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
IPAddressCollection dnsServers = adapterProperties.DnsAddresses;
if (dnsServers.Count > 0)
{
lstOutput.Items.Add(adapter.Description);
foreach (IPAddress dns in dnsServers)
{
lstOutput.Items.Add("Address Family : " + dns.AddressFamily);
}
}
}
}
The above code shows the use of the static method named GetAllNetworkInterfaces() to retrieve an array of NetworkInterface objects. You then loop through this array to get the DNS addresses by invoking the DnsAddresses property of the IPInterfaceProperties. The DnsAddresses property returns a collection of type IPAddressCollection. You loop through this collection to display all the IP addresses contained in that IPAddressCollection object.
Run the application and click the "Display DNS Addresses" button. You should get an output that is somewhat similar to the following.
In addition to retrieving the DNS addresses, you can also leverage the classes in the System.Net.NetworkInformation namespace to retrieve IPV4 statistical data for the local computer. The next section demonstrates the code required to accomplish this.
How to Display IP Statistics
For the purposes of this section, add a new command button named btnDisplayIPStatistics and modify its Click event to look like the following:
private void btnDisplayIPStatistics_Click(object sender, EventArgs e)
{
lstOutput.Items.Clear();
IPGlobalProperties properties =
IPGlobalProperties.GetIPGlobalProperties();
IPGlobalStatistics ipstat = properties.GetIPv4GlobalStatistics();
lstOutput.Items.Add("Inbound Packet Data:");
lstOutput.Items.Add("Received : " + ipstat.ReceivedPackets);
lstOutput.Items.Add("Forwarded :" + ipstat.ReceivedPacketsForwarded);
lstOutput.Items.Add("Delivered : " + ipstat.ReceivedPacketsDelivered);
lstOutput.Items.Add("Discarded :{0}" + ipstat.ReceivedPacketsDiscarded);
}
The above code starts by invoking the static method named GetIPGlobalProperties() of the IPGlobalProperties class. Then you invoke the GetIPv4GlobalStatistics() method of the IPGlobalProperties class to get reference to a IPGlobalStatistics object.
IPGlobalStatistics ipstat = properties.GetIPv4GlobalStatistics();
The IPGlobalStatistics class provides information on the received packets that are delivered, forwarded, and discarded and so on. You display the values contained in the various properties of the IPGlobalStatistics object in the ListBox. The final output produced by the form when the "Display IP Statistics" command button is clicked is shown below.
In addition to the above features, the System.Net.NetworkInformation namespace also provides ways to detect network changes using the NetworkChange class. Using this class, you can detect changes such as when the Ethernet cable is pulled out or plugged in and display the new status in the console. This feature can be very powerful in that you can use this to implement context switching in a smart client application based on their network state.
Conclusion
In this article, we demonstrated the different classes and features available in the System.Net.NetworkInformation namespace. By providing a speed-dial that allows you to more quickly and effectively retrieve network related information, the networking features provide huge productivity improvements to .NET developers.
|