1、Socket.Connect检测远程计算机指定端口是否打开
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);
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;
}
{
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;
}
{
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;
}