C# 如何实现快速扫描局域网中开放特定端口的目标主机
foreach (DirectoryEntry domain in entryPC.Children)
{
foreach (DirectoryEntry pc in domain.Children)
{
if (pc.Name != "Schema")//Schema是结束标记
{
try
{
IPHostEntry hostent = Dns.GetHostEntry(pc.Name); // 主机信息
Array addrs = hostent.AddressList; // IP地址数组
IEnumerator it = addrs.GetEnumerator(); // 迭代器
while (it.MoveNext())
{ // 循环到下一个IP 地址
IPAddress ip = (IPAddress)it.Current; // 获得 IP 地址
// list.Add(ip.ToString());
if (true == CanReceive(ip.ToString(), 8088))
{
list.Add(ip.ToString());
}
}
}
catch
{ }
}
}
}
public bool CanReceive(string m_host, int m_port)
{
bool result =false;
TcpClient tc = new TcpClient();
//设置超时时间
tc.SendTimeout = tc.ReceiveTimeout = 2000;
try
{
//尝试连接
tc.Connect(m_host, m_port);
if (tc.Connected)
{
//如果连接上,证明此端口为开放状态
result = true;
}
}
catch (System.Net.Sockets.SocketException e)
{
result = false;
}
finally
{
tc.Close();
tc = null;
}
return result;
}
这样效率太低了。花费了90多秒。