Friday, October 10, 2008

Internet/Network connection status

There are many methods for checking whether the machine is connected to Internet. I use one simple method for doing it (cannot say it is 100% foolproof. But it serves the purpose very well). What I used to do is to ping a couple of standard web sites like Google, Yahoo etc. to determine whether we are connected. The downtime of these servers is so small that we can assume that if we are not able to connect to at least one of these servers, there is probably something wrong with the connection.

To start with, there is a simple method for detecting whether the machine is connected to the network. Just enumerate the IP addresses of the local machine and if the media is disconnected, it will not have any other address than the loopback address.

using System.Net;

public bool IsNetworkAvailable()
{
   bool available = false;

   try
   {
      IPHostEntry iphostentry = Dns.GetHostEntry(Environment.MachineName);
      foreach (IPAddress ipaddress in iphostentry.AddressList)
      {
         if (!ipaddress.Equals(IPAddress.Loopback))
         {
            available = true;
            break;
         }
      }
   }
   catch (Exception ex)
   {
      System.Diagnostics.Trace.WriteLine("IsNetworkAvailable(): " + ex.ToString());
   }

   return available;
}

To ping a remote machine, the following function can be used.

using System.Net;
using System.Net.NetworkInformation;

public bool Ping(string url)
{
   bool available = false;

   try
   {
      Ping pingSender = new Ping();
      PingOptions options = new PingOptions();

      // Use the default TTL value, which is 128,
      // but change the fragmentation behavior.
      options.DontFragment = true;

      // Create a buffer of 32 bytes of data to be transmitted.
      string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
      byte[] buffer = System.Text.Encoding.ASCII.GetBytes(data);

      PingReply reply = pingSender.Send(url);

      available = (reply.Status == System.Net.NetworkInformation.IPStatus.Success);
   }
   catch (Exception ex)
   {
      System.Diagnostics.Trace.WriteLine("Ping(): " + ex.ToString());
   }

   return available;
}

Finally, to check whether the URL is available, we can use the following function (Ping() given above cannot be used for all URLs. e.g. we cannot determine whether a page is available in the remote machine. That can be found out by using the code given below).

using System.IO;
using System.Net;

private bool IsURLAvailable(string url)
{
    bool available = false;

    try
    {
        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);

        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

        using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
        {
            string html = sr.ReadToEnd();
            if (html.Trim() == string.Empty)
                throw new Exception("No data available");

            // Close the stream
            sr.Close();
        }

        resp.Close();
        available = true;
    }
    catch (Exception ex)
    {
        System.Diagnostics.Trace.WriteLine("IsURLAvailable(): " + ex.ToString());
    }

    return available;
}

The above function can be used as shown below. Check multiple urls and if at least one is available, we can assume that we are connected to Internet.

if (IsURLAvailable("http://www.google.com") ||
    IsURLAvailable("http://www.yahoo.com") ||
    IsURLAvailable("http://www.hotmail.com"))
{
    // Connected
}

No comments: