寻找Zihuatanejo

C#编程小实例(一)(Check internet connectivity and ping a host in C# 用C#查看互联网连接以及ping一个主机)(未看)

This is a snippet that has 4 methods, 1 enum and 1 Win32 API that will first check to make sure the "pinger" has an actual connection, then it sends the ping 4 times to the pinged host and returns the results
 

Language: C#

Last Modified: November 10, 2008
Instructions: Need references to the following Namespaces:

using System.Runtime.InteropServices;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

Snippet


  1. //Namespace References
  2. using System;
  3. using System.Runtime.InteropServices;
  4. using System.Net;
  5. using System.Net.NetworkInformation;
  6. using System.Net.Sockets;
  7.  
  8. public static class CheckInternetConnectivity
  9. {
  10.     [DllImport("wininet", CharSet = CharSet.Auto)]
  11.     static extern bool InternetGetConnectedState(ref ConnectionStatusEnum flags, int dw);
  12.  
  13.     /// <summary>
  14.     /// enum to hold the possible connection states
  15.     /// </summary>
  16.     [Flags]
  17.     enum ConnectionStatusEnum : int
  18.     {
  19.         INTERNET_CONNECTION_MODEM = 0x1,
  20.         INTERNET_CONNECTION_LAN = 0x2,
  21.         INTERNET_CONNECTION_PROXY = 0x4,
  22.         INTERNET_RAS_INSTALLED = 0x10,
  23.         INTERNET_CONNECTION_OFFLINE = 0x20,
  24.         INTERNET_CONNECTION_CONFIGURED = 0x40
  25.     }
  26.  
  27.     /// <summary>
  28.     /// method to check the status of the pinging machines internet connection
  29.     /// </summary>
  30.     /// <returns></returns>
  31.     private static bool HasConnection()
  32.     {
  33.         //instance of out ConnectionStatusEnum
  34.         ConnectionStatusEnum state = 0;
  35.  
  36.         //call the API
  37.         InternetGetConnectedState(ref state, 0);
  38.  
  39.         //check the status, if not offline and the returned state
  40.         //isnt 0 then we have a connection
  41.         if (((int)ConnectionStatusEnum.INTERNET_CONNECTION_OFFLINE & (int)state) != 0)
  42.         {
  43.             //return true, we have a connection
  44.             return false;
  45.         }
  46.         //return false, no connection available
  47.         return true;
  48.     }
  49.  
  50.     /// <summary>
  51.     /// method for retrieving the IP address from the host provided
  52.     /// </summary>
  53.     /// <param name="host">the host we need the address for</param>
  54.     /// <returns></returns>
  55.     private static IPAddress GetIpFromHost(ref string host)
  56.     {
  57.         string returnMessage = string.Empty;
  58.         //IPAddress instance for holding the returned host
  59.         IPAddress address = null;
  60.  
  61.         //wrap the attempt in a try..catch to capture
  62.         //any exceptions that may occur
  63.         try
  64.         {
  65.             //get the host IP from the name provided
  66.             address = Dns.GetHostEntry(host).AddressList[0];
  67.         }
  68.         catch (SocketException ex)
  69.         {
  70.             //some DNS error happened, return the message
  71.             returnMessage = string.Format("DNS Error: {0}", ex.Message);
  72.         }
  73.         return address;
  74.     }
  75.  
  76.     /// <summary>
  77.     /// method to check the ping status of a provided host
  78.     /// </summary>
  79.     /// <param name="addr">the host we need to ping</param>
  80.     /// <returns></returns>
  81.     public static string CheckSiteStatus(string host)
  82.     {
  83.         //string to hold our return messge
  84.         string returnMessage = string.Empty;
  85.  
  86.         //IPAddress instance for holding the returned host
  87.         IPAddress address = GetIpFromHost(ref host);
  88.  
  89.         //set the ping options, TTL 128
  90.         PingOptions options = new PingOptions(128, true);
  91.  
  92.         //create a new ping instance
  93.         Ping ping = new Ping();
  94.  
  95.         //32 byte buffer
  96.         byte[] data = new byte[32];
  97.  
  98.         //first make sure we actually have an internet connection
  99.         if (HasConnection())
  100.         {
  101.             //here we will ping the host 4 times (standard)
  102.             for (int i = 0; i < 4; i++)
  103.             {
  104.                 try
  105.                 {
  106.                     //send the ping 4 times to the host and record the returned data
  107.                     PingReply reply = ping.Send(address, 1000, data, options);
  108.  
  109.                     //make sure we dont have a null reply
  110.                     if (!(reply == null))
  111.                     {
  112.                         switch (reply.Status)
  113.                         {
  114.                             case IPStatus.Success:
  115.                                 returnMessage = string.Format("Reply from {0}: bytes={1} time={2}ms TTL={3}", reply.Address, reply.Buffer.Length, reply.RoundtripTime, reply.Options.Ttl);
  116.                                 break;
  117.                             case IPStatus.TimedOut:
  118.                                 returnMessage = "Connection has timed out...";
  119.                                 break;
  120.                             default:
  121.                                 returnMessage = string.Format("Ping failed: {0}", reply.Status.ToString());
  122.                                 break;
  123.                         }
  124.                     }
  125.                     else
  126.                         returnMessage = "Connection failed for an unknown reason...";
  127.                 }
  128.                 catch (PingException ex)
  129.                 {
  130.                     returnMessage = string.Format("Connection Error: {0}", ex.Message);
  131.                 }
  132.                 catch (SocketException ex)
  133.                 {
  134.                     returnMessage = string.Format("Connection Error: {0}", ex.Message);
  135.                 }
  136.             }
  137.         }
  138.         else
  139.             returnMessage = "No Internet connection found...";
  140.  
  141.         //return the message
  142.         return returnMessage;
  143.     }
  144. }

posted on 2009-01-23 17:11  Zihuatanejo  阅读(439)  评论(0)    收藏  举报

导航