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

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 | 引用: 0 | 查看次数: 2631
发表评论
登录后再发表评论!