65.9K
CodeProject 正在变化。 阅读更多。
Home

netUtility

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.71/5 (6投票s)

2012年2月20日

CPOL

2分钟阅读

viewsIcon

34981

downloadIcon

1474

一种良好的实现方法,用于检查互联网和网络连接。

network.png

引言

本文将展示如何使用我的 netUtility(NetworkUtility 的缩写)库来检查互联网连接,监听互联网连接以及其他方法,例如查找路由器、检查网页是否可用以及 Ping 方法。

需要 .NET 3.0 或更高版本。

背景

我创建这个是因为一个项目,我需要一种检查互联网连接的方法,我在网上搜索并找到了许多不同的解决方案。 方案太多了,所以我决定创建一个类库文件来解决我的问题,并且可以在其他项目中重用。

使用代码

在开始之前,你需要将 netUtility.dll(在上面的源代码中)放在你的项目文件夹中。 在你的解决方案中,你需要将 netUtility.dll 添加为引用(浏览)。 然后通过输入以下内容导入它

using netUtility;

此后,你就可以创建 NetworkUtility 类的实例了

NetworkUtility netUtil = new NetworkUtility();

NetworkUtility 具有以下方法

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

以下是 NetworkUtility 的属性

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

以下是 NetworkUtility 的事件

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

以下将展示如何检查路由器并打印其信息,检查互联网连接,最后 Ping google。

//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);
      }   
    }
}

以下是 testApp(控制台应用程序)中的代码,它打印出所有数据

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

要设置监听器,你需要以下代码

  //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);

下面是 NetConnection Tester 的完整代码。

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);
        }
    }
}

关注点

这个库文件对我很有用,我通过构建它节省了大约 20-30 行代码。 我只需要几行代码来检查我的项目所需的一切。

历史

文章已更新 (2012-02-21)
文章已更新 (2012-02-20)
最新版本 1.0.0.0

© . All rights reserved.