2011-09-10 24 views
2

我用下面的代碼來實現這一目標:c#檢查端口是否在積極監聽?

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(); 
     } 
    } 

這裏是我的擴展方法的Socket類:

public static class SocketExtensions 
{ 
    public const int CONNECTION_TIMEOUT_ERROR = 10060; 

    /// <summary> 
    /// Connects the specified socket. 
    /// </summary> 
    /// <param name="socket">The socket.</param> 
    /// <param name="endpoint">The IP endpoint.</param> 
    /// <param name="timeout">The connection timeout interval.</param> 
    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. 
     } 
    } 
} 

問題是這樣的一段代碼工作在我的開發環境但是當我移動到生產環境中出它總是時間(無論是否我的超時時間間隔爲5秒或20秒)

有沒有我可以檢查如果IP是activel一些其他的方式聆聽特定港口?

究竟是爲什麼我無法從我的託管環境,這樣做的原因是什麼?

+0

防火牆這是在生產網絡活躍平凡解釋了這個問題。您在公共IP上使用不尋常的端口號。 –

+0

你爲什麼使用確切的IP? 一般來說['System.Net.IPAddress.Any'](http://msdn.microsoft.com/en-us/library/system.net.ipaddress.any)是偵聽所有IP的更好的解決方案(如果這是可以接受的)。 – Matej

+0

因爲我想檢查該IP是否在該端口上偵聽? – bevacqua

回答

7

您可以從命令行運行netstat -na看到所有(包括聽力)端口。

如果添加-b您還可以看到鏈接的可執行每個連接/聽。

在.NET中,你可以得到所有的監聽連接與System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners()

+0

我不需要命令,我需要C#代碼。 – bevacqua

+0

我已經更新了答案 - .NET解決方案,以'netstat的-na'是'GetActiveTcpListeners'和'GetActiveTcpConnections'在'IPGlobalProperties'。 – Matej

+0

但我希望聽衆在特定的IP,而不是本地IP – bevacqua

0

您可以使用此代碼檢查:

 TcpClient tc = new TcpClient(); 
     try 
     { 

      tc.Connect(<server ipaddress>, <port number>); 
      bool stat = tc.Connected; 
      if (stat) 
       MessageBox.Show("Connectivity to server available."); 

      tc.Close(); 
     } 
     catch(Exception ex) 
     { 
      MessageBox.Show("Not able to connect : " + ex.Message); 
      tc.Close(); 
     }