1、微软社区上介绍了使用Active Directory 来遍历局域网
利用DirectoryEntry组件来查看网络
网址:http://www.microsoft.com/china/communITy/program/originalarticles/techdoc/DirectoryEntry.mspx
private void EnumComputers()
{
using(DirectoryEntry root = new DirectoryEntry("WinNT:"))
{
foreach(DirectoryEntry domain in root.Children)
{
Console.WriteLine("Domain | WorkGroup: "+domain.Name);
foreach(DirectoryEntry computer in domain.Children)
{
Console.WriteLine("Computer: "+computer.Name);
}
}
}
}
效果评价:速度慢,效率低,还有一个无效结果 Computer: Schema 使用的过程中注意虑掉。
2、利用Dns.GetHostByAddress和IPHostEntry遍历局域网
private void EnumComputers()
{
for (int i = 1; i <= 255; i++)
{
string scanIP = "192.168.0." + i.ToString();
IPAddress myScanIP = IPAddress.Parse(scanIP);
IPHostEntry myScanHost = null;
try
{
myScanHost = Dns.GetHostByAddress(myScanIP);
}
catch
{
continue;
}
if (myScanHost != null)
{
Console.WriteLine(scanIP+"|"+myScanHost.HostName);
}
}
}
效果评价:效率低,速度慢,不是一般的慢。
3、使用System.Net.NetworkInformation.Ping来遍历局域网
private void EnumComputers()
{
try
{
for (int i = 1; i <= 255; i++)
{
Ping myPing;
myPing = new Ping();
myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted);
string pingIP = "192.168.0." + i.ToString();
myPing.SendAsync(pingIP, 1000, null);
}
}
catch
{
}
}
PRIVATE void _myPing_PingCompleted(object sender, PingCompletedEventArgs e)
{
if (e.Reply.Status == IPStatus.Success)
{
Console.WriteLine(e.Reply.Address.ToString() + "|" + Dns.GetHostByAddress(IPAddress.Parse(e.Reply.Address.ToString())).HostName);
}
}
效果评价:速度快,效率高,如果只取在线的IP,不取计算机名,速度会更快。
需要注意的是取计算机名称如果用Dns.GetHostByAddress取计算机名称,结果虽然正确,但VS2005会提示该方法已过时,但仍能使用。
如果用它推荐的替代方法Dns.GetHostEntry,则有个别计算机的名称会因超时而获得不到。