c# Checking whether a port is actively listening?
I use the following piece of code to achieve this goal:
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.", exceptio开发者_高级运维n);
return false;
}
finally
{
socket.Close();
}
}
Here is my extension method to the Socket
class:
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.
}
}
}
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)
Is there some other way I could check if that IP is actively listening at that particular port?
What is the reason why I can't do this from my hosting environment?
You can run netstat -na
from command line to see all (including listening) ports.
If you add -b
you will also see linked executable to each connection/listening.
In .NET you can get all listening connections with System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners()
You can check it by using this code:
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();
}
精彩评论