title: c# Checking whether a port is actively listening?
body: <p>I use the following piece of code to achieve this goal:</p>
  
  <pre><code>    public static bool IsServerListening()
      {
          var endpoint = new IPEndPoint(IPAddress.Parse("201.212.1.167"), 2593);
          var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  
          try
          {
              socket.Connect(endpoint, TimeSpan.FromSeconds(5));
              return true;
          }
          catch (SocketException exception)
          {
              if (exception.SocketErrorCode == SocketError.TimedOut)
              {
                  Logging.Log.Warn("Timeout while connecting to UO server game port.", exception);
              }
              else
              {
                  Logging.Log.Error("Exception while connecting to UO server game port.", exception);
              }
  
              return false;
          }
          catch (Exception exception)
          {
              Logging.Log.Error("Exception while connecting to UO server game port.", exception);
              return false;
          }
          finally
          {
              socket.Close();
          }
      }
  </code></pre>
  
  <p>Here is my extension method to the <code>Socket</code> class:</p>
  
  <pre><code>public static class SocketExtensions
  {
      public const int CONNECTION_TIMEOUT_ERROR = 10060;
  
      /// &lt;summary&gt;
      /// Connects the specified socket.
      /// &lt;/summary&gt;
      /// &lt;param name="socket"&gt;The socket.&lt;/param&gt;
      /// &lt;param name="endpoint"&gt;The IP endpoint.&lt;/param&gt;
      /// &lt;param name="timeout"&gt;The connection timeout interval.&lt;/param&gt;
      public static void Connect(this Socket socket, EndPoint endpoint, TimeSpan timeout)
      {
          var result = socket.BeginConnect(endpoint, null, null);
  
          bool success = result.AsyncWaitHandle.WaitOne(timeout, true);
          if (!success)
          {
              socket.Close();
              throw new SocketException(CONNECTION_TIMEOUT_ERROR); // Connection timed out.
          }
      }
  }
  </code></pre>
  
  <p>The problem is this piece of code works on my development environment but when I move it into production environment it always times out (regardless of whether I set the timeout interval to 5 or 20 seconds)</p>
  
  <p>Is there some other way I could check if that IP is actively listening at that particular port?</p>
  
  <p>What is the reason why I can't do this from my hosting environment?</p>