我用下面的代碼來實現這一目標: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一些其他的方式聆聽特定港口?
究竟是爲什麼我無法從我的託管環境,這樣做的原因是什麼?
防火牆這是在生產網絡活躍平凡解釋了這個問題。您在公共IP上使用不尋常的端口號。 –
你爲什麼使用確切的IP? 一般來說['System.Net.IPAddress.Any'](http://msdn.microsoft.com/en-us/library/system.net.ipaddress.any)是偵聽所有IP的更好的解決方案(如果這是可以接受的)。 – Matej
因爲我想檢查該IP是否在該端口上偵聽? – bevacqua