Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#3.5

netUtility

2.71/5 (6 votes)
20 Feb 2012CPOL2 min read 34.4K   1.4K  
A good implementation method to check Internet and network connections.

network.png

Introduction

This article will show how to use my netUtility (short for NetworkUtility) library to check Internet connections, listen for Internet connections and other methods as finding router, check if a webpage are available and a Ping method.

Requires .NET 3.0 or above.

Background

I created this as a result of a project I have, I needed a way to check Internet connections and I seached the web and found many different ways to solve the problem. There were so many that I decided to create a class library file that solves the problem for me and I can be re-used in other projects.

Using the code

Before you get started you need to place the netUtility.dll (in the source code above) in your project folder. In your solution you need to add the netUtility.dll as a reference (browse). Then you import it by type the following:

C#
using netUtility;

Thereafter you are able to create an instance of NetworkUtility class:

C#
NetworkUtility netUtil = new NetworkUtility();

The NetworkUtility has the following methods:

C#
netUtil.AddressExistOrAvailable(string address); // Checks wether the URL is available - returns true/false
netUtil.CheckInternetConnection(); // Checks if there is an Internet connection or not - returns true/false<br />netUtil.CheckRouterConnection(); // Checks if there is a router available in the network - returns true/false
netUtil.GetAddressHeaders(string address); // Returns an array of headers of a website
netUtil.Ping(string address); // Gives the ability of "Pinging" a website, you can type an http-address or an IP-address - return true/false
//The following method are in beta - is still working on a god solution
netUtil.CheckAvailability(bool checkInternet); // This checks the Internet connection (if checkInternet is set to true) and the router connection. You must have listeners and subscribers to use this method

The following are the Properties of NetworkUtility

C#
netUtil.ErrorMessage; // Returns the most recent error. Should be used in a try-catch statement (more explenation below) - returns a string<br />netUtil.PingInfo; // When you Ping an address or IP it gathers the information that was returned, this property will return the most recent Ping() that was made in an array
netUtil.RouterInfo; // As with the PingInfo, this will return all the information that was returned from the router in an array

The following are the Events of the NetworkUtility

C#
netUtil.RouterAvailableEvent += new RouterAvailableHandler(netUtil_RouterAvailableEvent); //listens for the router<br />netUtil.InternetAvailableEvent += new InternetAvailableHandler(netUtil_InternetAvailableEvent); listens for an Internet connection

The following will show how to check for a router and print its information, check Internet connection and at last Ping google.

C#
//remember using netUtility  

//setup an instance of NetworkUtility class
NetworkUtility netUtil = new NetworkUtility();            <br />
//check the router, first print the answer - then check and continue to Internet connection if true            
Console.WriteLine("Router connection: " + netUtil.CheckRouterConnection()); 
if(netUtil.CheckRouterConnection)
{
   string[] routerInfo = netUtil.RouterInfo;    //get router information        
   for(int i = 0; i < routerInfo.Length; i++)
   {
      Console.WriteLine(routerInfo[i]); // print it
   }      
   //check Internet connection, print the answer and then continue if true
   Console.WriteLine("\nInternet connection: " + netUtil.CheckInternetConnection());
   if(netUtil.CheckInternetConnection)
   {
      //Ping google - print its success
      Console.WriteLine("n\Ping webaddress: " + netUtil.Ping("http://www.google.com"));
      //try to catch the information that returned                
      try {
         //this must be done before any other method is raised in NetworkUtility, otherwise you will get the wrong data
         string[] pingInfo = netUtil.PingInfo;
         for(int i = 0; i < pingInfo.Length; i++)
         {
             Console.WriteLine(pingInfo[i]);
         }
      } catch (Exception) {
         //prints the error caught in NetworkUtility                 
         Console.WriteLine(netUtil.ErrorMessage);
      }   
    }
}

The following are the code in the testApp(console application) that prints out all data:

C#
using System;
using System.Collections.Generic;
using System.Text;
using netUtility;

namespace testApp
{
    class Program
    {
        public static void Main(string[] args)
        {
            NetworkUtility netUtil = new NetworkUtility();            

            Console.WriteLine("Router connection: " + 
                netUtil.CheckRouterConnection());//check router    

            string[] routerInfo = netUtil.RouterInfo;    //get router information  
            for(int i = 0; i < routerInfo.Length; i++)
            {
               Console.WriteLine(routerInfo[i]); // print it
            }
            Console.WriteLine("Internet connection: " + 
              netUtil.CheckInternetConnection()); // check Internet connection

            Console.WriteLine();            
            Console.WriteLine("Ping IP: " + 
              netUtil.Ping("209.85.137.99")); // ping an ip that belongs to google

            try {
                string[] pingIpInfo = netUtil.PingInfo;
                for(int i = 0; i < pingIpInfo.Length; i++)
                {
                    Console.WriteLine(pingIpInfo[i]);
                }
            } catch (Exception) {
                Console.WriteLine(netUtil.ErrorMessage);
            }

            Console.WriteLine();
            Console.WriteLine("Ping webaddress: " + 
              netUtil.Ping("http://www.google.com")); // ping google

            try {
                string[] pingInfo = netUtil.PingInfo;
                for(int i = 0; i < pingInfo.Length; i++)
                {
                    Console.WriteLine(pingInfo[i]);
                }
            } catch (Exception) {
                Console.WriteLine(netUtil.ErrorMessage);
            }

            Console.WriteLine();
            Console.WriteLine("The address exist: " + 
              netUtil.AddressExistOrAvailable("http://www.google.com")); // does google exist

            if(netUtil.ErrorMessage != null)
            {
                Console.WriteLine(netUtil.ErrorMessage);          
            }

            Console.WriteLine();
            try {
                string[] getHeaders = netUtil.GetAddressHeaders("http://www.google.com"); // get googles' headers
                for(int i = 0; i < getHeaders.Length; i++)
                {
                    Console.WriteLine(getHeaders[i]);
                }
            } catch (Exception) {
                 Console.WriteLine(netUtil.ErrorMessage);
            }

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);

        }

    }
}

testapp.png

To setup a listener, you will need the following code:

C#
//initialize the NetworkUtility
private NetworkUtility net_utility = new NetworkUtility();

//initialize listeners - can be initialized in the Load Event (se whole code at the bottom)<br />  net_utility.RouterAvailableEvent += new NetworkUtility.RouterAvailableHandler(RouterAvailable);
net_utility.InternetAvailableEvent += new NetworkUtility.InternetAvailableHandler(InternetAvailable);

//the subscribers, they need to be written exactly as this - except from the Print() method, you should implement your own

//subscriber for the router
private void RouterAvailable(object sender, RouterAvailableEventArgs e)
{
   //Make sure that the sender is a NetworkUtility
   if (sender is NetworkUtility)
   {
      NetworkUtility n_utility = (NetworkUtility)sender;
      Print("Router" ,e.IsAvailable);
    }
 }

 //subscriber dor the Internet
 private void InternetAvailable(object sender, InternetAvailableEventArgs e)
 {
    //Make sure that the sender is a NetworkUtility
    if (sender is NetworkUtility)
    {
       NetworkUtility n_utility = (NetworkUtility)sender;
       Print("Internet", e.IsAvailable);
    }
 }

//finally the method that runs the listeners
//start listeners
//true if Internet should be checked too
//router is always checked
//this should be started in a seperate thread
net_utility.CheckAvailability(true);

Below you will have the whole code for the NetConnection Tester.

C#
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using netUtility;

namespace NetConnection_Tester
{
    /// <summary>
    /// Description of MainForm.
    /// </summary>

    public partial class MainForm : Form
    {
        private NetworkUtility net_utility = new NetworkUtility();

        public MainForm()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();
        }

        void Button1Click(object sender, EventArgs e)
        {
            //start listeners
            //true if Internet should be checked too
            //router is always checked
            //this should be started in a seperate thread
            net_utility.CheckAvailability(true);
        }

        //subscriber
        private void RouterAvailable(object sender, RouterAvailableEventArgs e)
        {
            //Make sure that the sender is a NetworkUtility
            if (sender is NetworkUtility)
            {
                NetworkUtility n_utility = (NetworkUtility)sender;
                Print("Router" ,e.IsAvailable);
            }
        }

        //subscriber
        private void InternetAvailable(object sender, InternetAvailableEventArgs e)
        {
            //Make sure that the sender is a NetworkUtility
            if (sender is NetworkUtility)
            {
                NetworkUtility n_utility = (NetworkUtility)sender;
                Print("Internet", e.IsAvailable);
            }
        }

        private void Print(string data, bool status)
        {
            textBox1.AppendText(string.Format("{0} is available: {1}\n", data, status));
        }

        void MainFormLoad(object sender, EventArgs e)
        {
            //initialize listeners
            net_utility.RouterAvailableEvent += 
              new NetworkUtility.RouterAvailableHandler(RouterAvailable);
            net_utility.InternetAvailableEvent += 
              new NetworkUtility.InternetAvailableHandler(InternetAvailable);
        }
    }
}

Points of Interest

This library file has been useful to me, I saved basicly 20-30 lines of code by building this. I needed just a few lines to check everything I needed for my project.

History

Article updated (2012-02-21)
Article updated (2012-02-20)
Latest version 1.0.0.0

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)