c#检查端口是否正在主动监听?

时间:2011-09-10 17:54:11

标签: c# sockets

我使用以下代码来实现这一目标:

    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是否正在该特定端口上主动侦听吗?

我无法在托管环境中执行此操作的原因是什么?

2 个答案:

答案 0 :(得分:7)

您可以从命令行运行netstat -na以查看所有(包括侦听)端口。

如果您添加-b,您还会看到每个连接/收听的链接可执行文件。

在.NET中,您可以使用System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners()

获取所有侦听连接

答案 1 :(得分: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();
       }