Yesterday, I wrote about the Ping class for checking network availability on remote machines. Then I started thinking about checking the availability of web servers. Even if a remote server is available over the network, the web server instance might not response to requests so we need another method to check if it’s responding correctly.

What we really want is not a Boolean value telling us if the web server is responding or not. The best way is to get the HTTP status code so we can act appropriately. The status code for a properly working web server is 200 and 404 if there is no reply. There are a lot of other codes that we can act differently upon as we please. Here’s a list of possible status codes.

This static method returns a System.Net.HttpStatusCode enumeration value based on the specified URL.

private static HttpStatusCode HttpStatus(string url)

{

  HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

 

  try

  {

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())

    {

      return response.StatusCode;

    }

  }

  catch (System.Net.WebException)

  {

    return HttpStatusCode.NotFound;

  }

}

You can use it to write the status code to the response stream like this:

Response.Write((int)HttpStatus("http://www.google.com"));

By using this simple method it is very easy to build your own web server checking tool. If you want to run multiple URL checks from ASP.NET, it would be a good idea to use ASP.NET 2.0’s possibility for asynchronous processing for improved performance in situations where you are creating web requests.

The Ping class is new to .NET 2.0 and it let’s you ping remote addresses much the same way as the ping.exe command line tool does. It’s a great way to check the availability of different kinds of remote servers over the network in a very low cost and fast way. The most important result a ping can give you is the ping time. The ping time gives you an indication on the network speed between you and the server.

I’ve written a very small and easy to use method that returns the ping time of a given URL.

using System.Net.NetworkInformation;

 

/// <summary>

/// Pings the specified URL within the timeout period.

/// </summary>

/// <param name="url">The URL to ping.</param>

/// <param name="timeout">Number of milliseconds.</param>

/// <returns>Returns the ping time in milliseconds.</returns>

private static long PingTime(string url, int timeout)

{

  try

  {

    using (Ping ping = new Ping ())

    {

      PingReply reply = ping.Send(url, timeout);

      return reply.RoundtripTime;

    }

  }

  catch (System.Net.Sockets.SocketException)

  {

    return -1;

  }

}

You can use the method from whenever you want like the following an ASP.NET webpage.

Response.Write(PingTime("http://www.google.com", 2000));