检测服务器IP端口是否可用

时间:2023-03-09 15:46:45
检测服务器IP端口是否可用
private static double Scanner(string ip, int port)
{
try
{
System.Net.Sockets.TcpClient Tcp = new System.Net.Sockets.TcpClient();
System.IAsyncResult ias = Tcp.BeginConnect(ip, port, null, null);//port为空=> 80
DateTime tOut = DateTime.Now;
while (ias.IsCompleted == false)
{
//从tOut到目前为止的时间超过3秒,返回-1
if (DateTime.Now.Subtract(tOut).TotalMilliseconds >= 3000)
{
return -1;
}
}
Tcp.EndConnect(ias);
Tcp.Close();
Thread.Sleep(1);
//获取从tOut到目前为止的毫秒数
double tmp = DateTime.Now.Subtract(tOut).TotalMilliseconds / 1000;
return tmp;
}
catch
{
return -1;
}
}