Quantcast
Channel: 木子屋 - Win编程
Viewing all articles
Browse latest Browse all 206

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

$
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;
}

Viewing all articles
Browse latest Browse all 206

Trending Articles