Wednesday, February 22, 2012

Network Reachability Test for .NET

The code below is used to test if a specific server and port is reachable. This code uses a socket to connect to the server and doesn't wait for a response so it is quicker than using a full WebClient request, etc. This code will return true if the server was reachable and false if it was not (within the provided timeout).

public class NetworkReachability
{
 public static bool IsReachable(string url, int timeout)
 {
  return IsReachable(new Uri(url), timeout);
 }

 public static bool IsReachable(Uri uri, int timeout)
 {
  return IsReachable(uri.Host, uri.Port, timeout);
 }

 public static bool IsReachable(string host, int port, int timeout)
 {
  if (AppConfig.IsDebugCompile)
  {
   Thread.Sleep(250);
   return true;
  }

  try
  {
   using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
   {
    var handler = new ManualResetEvent(false);
    var e = new SocketAsyncEventArgs();
    e.RemoteEndPoint = new DnsEndPoint(host, port);
    e.Completed += delegate { handler.Set(); };
    if (!socket.ConnectAsync(e))
     handler.Set();

    return handler.WaitOne(timeout) &&
     e.ConnectByNameError == null &&
     socket.Connected;
   }
  }
  catch
  {
   return false;
  }
 }
}

No comments:

Post a Comment