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