Click here to Skip to main content
15,885,782 members
Articles / Programming Languages / C# 3.5

netUtility

Rate me:
Please Sign up or sign in to vote.
2.71/5 (6 votes)
20 Feb 2012CPOL2 min read 32.8K   1.4K   18   23
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)



Comments and Discussions

 
QuestionNetworkChange Class Pin
giammin21-Feb-12 3:16
giammin21-Feb-12 3:16 
AnswerRe: NetworkChange Class Pin
User 711503721-Feb-12 7:16
User 711503721-Feb-12 7:16 
GeneralMy vote of 1 Pin
michaelvdnest20-Feb-12 19:09
michaelvdnest20-Feb-12 19:09 
GeneralRe: My vote of 1 Pin
User 711503720-Feb-12 21:36
User 711503720-Feb-12 21:36 
GeneralMy vote of 1 Pin
vilainchien20-Feb-12 12:02
vilainchien20-Feb-12 12:02 
GeneralRe: My vote of 1 Pin
User 711503720-Feb-12 21:36
User 711503720-Feb-12 21:36 
GeneralRe: My vote of 1 Pin
vilainchien20-Feb-12 21:41
vilainchien20-Feb-12 21:41 
GeneralRe: My vote of 1 Pin
vilainchien20-Feb-12 22:03
vilainchien20-Feb-12 22:03 
GeneralRe: My vote of 1 Pin
User 711503720-Feb-12 22:13
User 711503720-Feb-12 22:13 
GeneralRe: My vote of 1 Pin
vilainchien20-Feb-12 22:42
vilainchien20-Feb-12 22:42 
GeneralRe: My vote of 1 Pin
User 711503720-Feb-12 23:16
User 711503720-Feb-12 23:16 
GeneralMy vote of 2 Pin
David Rush20-Feb-12 10:27
professionalDavid Rush20-Feb-12 10:27 
GeneralRe: My vote of 2 Pin
User 711503720-Feb-12 11:14
User 711503720-Feb-12 11:14 
GeneralMy vote of 1 Pin
Dean Oliver20-Feb-12 7:10
Dean Oliver20-Feb-12 7:10 
not a good explanation or source code for this class.
GeneralRe: My vote of 1 Pin
User 711503720-Feb-12 10:10
User 711503720-Feb-12 10:10 
BugSource code... Pin
Mladen Janković20-Feb-12 6:46
Mladen Janković20-Feb-12 6:46 
GeneralRe: Source code... Pin
User 711503720-Feb-12 10:11
User 711503720-Feb-12 10:11 
SuggestionRe: Source code... Pin
David Rush20-Feb-12 10:14
professionalDavid Rush20-Feb-12 10:14 
GeneralRe: Source code... Pin
User 711503720-Feb-12 11:16
User 711503720-Feb-12 11:16 
GeneralRe: Source code... Pin
David Rush20-Feb-12 11:41
professionalDavid Rush20-Feb-12 11:41 
GeneralRe: Source code... Pin
User 711503720-Feb-12 21:35
User 711503720-Feb-12 21:35 
GeneralRe: Source code... Pin
David Rush21-Feb-12 9:53
professionalDavid Rush21-Feb-12 9:53 
GeneralRe: Source code... Pin
User 711503722-Feb-12 0:41
User 711503722-Feb-12 0:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.