很多软件都有获知局域网在线计算机IP的功能,但是在.net怎么实现呢,有好多方法, 下面我给大家介绍几种,供大家参考。
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 = ; i <= ; 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);
}
}
}<span style="color: rgb(51, 51, 51); line-height: 25px; font-family: Arial, Helvetica, simsun, u5b8bu4f53; font-size: 14px;"> </span>
效果评价:效率低,速度慢,不是一般的慢。
3、使用System.Net.NetworkInformation.Ping来遍历局域网
private void EnumComputers() {
try
{
for (int i = ; i <= ; i++)
{
Ping myPing;
myPing = new Ping();
myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted); string pingIP = "192.168.0." + i.ToString();
myPing.SendAsync(pingIP, , 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,则有个别计算机的名称会因超时而获得不到。
http://blog.163.com/ldy_3881685/blog/static/32380136200954112940184/