c# 检查一个端口是否正在监听?

标签 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 是否在该特定端口上主动监听?

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

最佳答案

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

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

在 .NET 中,您可以使用 System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners() 获取所有监听连接

关于c# 检查一个端口是否正在监听?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7373537/

相关文章:

c++ - 非阻塞关闭 - 如何确保数据已发送?

linux - Qt程序只接收来自特定IP地址的UDP

java - HTTPS 套接字 "javax.net.ssl.SSLHandshakeException: no cipher suites in common"

c# - 关闭和清理 Socket 连接的正确方法是什么?

c# - Asp.Net 中新窗口中的 Response.Redirect()

c# - 如何使用我自己的调试器可视化工具来编辑运行时变量?

c# - 编译器错误 CS0019 : comparing two integers

c# - EF 是否有一个事件系统,您可以在其中修改模型,然后再保存它?

c# - 对包含不同类型单元格的 DataGrid 列进行排序会引发 ArgumentException

networking - 如何获取套接字的非 ACK-ed TCP 数据量?