asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search





Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Networking Features in .NET Framework 2.0
By Thiru Thangarathinam
Rating: 4.1 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

  • 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.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Other Articles
    Jul 21, 2005 - N-Tier Web Applications using ASP.NET 2.0 and SQL Server 2005 - Part 1
    While the .NET Framework made building ASP.NET applications easier then it had ever been in the past, .NET 2.0 builds on that foundation in order to take things to the next level. This article shows you to how to construct an N-Tier ASP.NET 2.0 Web application by leveraging the new features of ASP.NET 2.0 and SQL Server 2005.
    [Read This Article]  [Top]
    Apr 28, 2005 - New Files and Folders in ASP.NET 2.0
    With the release of ASP.NET 2.0, Microsoft has greatly increased the power of ASP.NET by introducing a suite of new features and functionalities. As part of this release, ASP.NET 2.0 also comes with a host of new special files and folders that are meant to be used to implement a specific functionality. This article examines these new files and folders in detail and provides examples that demonstrate how to utilize them to create ASP.NET 2.0 applications.
    [Read This Article]  [Top]
    Mar 10, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 2, Cont'd
    Alex Homer continues his detailed look at the major changes to the DataSet class. In this part, he looks at two features that allow developers to work with data in a more structured and efficient way when using the DataSet with a SQL Server 2005 database server.
    [Read This Article]  [Top]
    Mar 9, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 2
    Alex Homer continues his detailed look at the major changes to the DataSet class. In this part, he looks at two features that allow developers to work with data in a more structured and efficient way when using the DataSet with a SQL Server 2005 database server.
    [Read This Article]  [Top]
    Mar 3, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 1, Cont'd
    In this article, Alex Homer looks at the changes between the version 1.x and version 2.0 DataSet and their associated classes, showing you how you can take advantage of the new features to improve your applications' capabilities and performance.
    [Read This Article]  [Top]
    Mar 2, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 1
    In this article, Alex Homer looks at the changes between the version 1.x and version 2.0 DataSet and their associated classes, showing you how you can take advantage of the new features to improve your applications' capabilities and performance.
    [Read This Article]  [Top]
    Feb 16, 2005 - Writing a Custom Membership Provider for the Login Control in ASP.NET 2.0
    In ASP.NET 2.0 and Visual Studio 2005, you can quickly program custom authentication pages with the provided Membership Login controls. In this article, Dina Fleet Berry examines the steps involved in using the Login control with a custom SQL Server membership database.
    [Read This Article]  [Top]
    Dec 29, 2004 - ClickOnce Deployment in .NET Framework 2.0
    In this article, Thiru Thangarathinam examines .NET 2.0's new ClickOnce deployment technology that is designed to ease deployment of Windows forms applications. This new technology not only provides an easy application installation mechanism, it also eases deployment of upgrades to existing applications.
    [Read This Article]  [Top]
    Dec 15, 2004 - A Sneak Peek at ASP.NET 2.0's Administrative Tools
    With ASP.NET 2.0, Microsoft has made great strides in increasing developer productivity and has made implementing previously complex solutions relatively easy. Where this version of ASP.NET really shines, however, is in its new administrative tools that allow developers to spend less time managing the configuration of the servers and software and more time developing great code.
    [Read This Article]  [Top]
    Nov 17, 2004 - The ASP.NET 2.0 TreeView Control
    Thiru Thangarathinam introduces ASP.NET 2.0's new TreeView control which provides a seamless way to consume and display information from hierarchical data sources. The article discusses this new control in depth and explains how to use this feature rich control in your ASP.NET applications.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers