木子屋 Dnawo's BLOG

C#检测远程计算机指定端口是否打开的方法

👤 dnawo 📅 2020-03-22 👁 3582 👍 0 💬 0 🔄 来源:本站原创
1、Socket.Connect检测远程计算机指定端口是否打开

public bool CheckRemotePort(string ipAddress, int port)
{
    bool result = false;
    try
    {
        IPAddress ip = IPAddress.Parse(ipAddress);
        IPEndPoint point = new IPEndPoint(ip, port);
        Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sock.Connect(point);
        result = true;
    }
    catch (SocketException ex)
    {
        //10061 Connection is forcefully rejected.
        if (ex.ErrorCode != 10061)
        {
            throw;
        }
    }
    return result;
}

2、TcpClient.Connect检测远程计算机指定端口是否打开

public bool CheckRemotePort(string ipAddress, int port)
{
    bool result = false;
    try
    {
        IPAddress ip = IPAddress.Parse(ipAddress);
        IPEndPoint point = new IPEndPoint(ip, port);
        TcpClient tcp = new TcpClient();
        tcp.Connect(point);
        result = true;
    }
    catch (SocketException ex)
    {
        //10061 Connection is forcefully rejected.
        if (ex.ErrorCode != 10061)
        {
            throw;
        }
    }
    return result;
}

评论(0)

暂无评论。

验证码
评论需审核通过后显示
← 上一篇 C#生成远程桌面rdp文件示例 下一篇 → 项目解除SVN版本控制(无需导入注册表)