很多软件都有获知局域网在线计算机IP的功能,但是在.net怎么实现呢,有好多方法, 下面我给大家介绍几种,供大家参考。
1、微软社区上介绍了使用Active Directory 来遍历局域网 利用DirectoryEntry组件来查看网络 网址:http://www.microsoft.com/china/communITy/program/originalarticles/techdoc/DirectoryEntry.mspx

1 private void EnumComputers() 2 { 3 using(DirectoryEntry root = new DirectoryEntry("WinNT:")) 4 { 5 foreach(DirectoryEntry domain in root.Children) 6 { 7 Console.WriteLine("Domain | WorkGroup: "+domain.Name); 8 foreach(DirectoryEntry computer in domain.Children) 9 { 10 Console.WriteLine("Computer: "+computer.Name); 11 } 12 } 13 } 14 }
效果评价:速度慢,效率低,还有一个无效结果 Computer: Schema 使用的过程中注意虑掉。
2、利用Dns.GetHostByAddress和IPHostEntry遍历局域网

1 private void EnumComputers() 2 3 { 4 for (int i = 1; i <= 255; i++) 5 { 6 string scanIP = "192.168.0." + i.ToString(); 7 8 IPAddress myScanIP = IPAddress.Parse(scanIP); 9 10 IPHostEntry myScanHost = null; 11 12 try 13 { 14 myScanHost = Dns.GetHostByAddress(myScanIP); 15 } 16 17 catch 18 { 19 continue; 20 } 21 22 if (myScanHost != null) 23 { 24 Console.WriteLine(scanIP+"|"+myScanHost.HostName); 25 } 26 } 27 }<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来遍历局域网

1 private void EnumComputers() 2 3 { 4 try 5 { 6 for (int i = 1; i <= 255; i++) 7 { 8 Ping myPing; 9 myPing = new Ping(); 10 myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted); 11 12 string pingIP = "192.168.0." + i.ToString(); 13 myPing.SendAsync(pingIP, 1000, null); 14 } 15 } 16 catch 17 { 18 } 19 } 20 21 PRIVATE void _myPing_PingCompleted(object sender, PingCompletedEventArgs e) 22 { 23 if (e.Reply.Status == IPStatus.Success) 24 { 25 Console.WriteLine(e.Reply.Address.ToString() + "|" + Dns.GetHostByAddress(IPAddress.Parse(e.Reply.Address.ToString())).HostName); 26 } 27 28 }
效果评价:速度快,效率高,如果只取在线的IP,不取计算机名,速度会更快。
需要注意的是取计算机名称如果用Dns.GetHostByAddress取计算机名称,结果虽然正确,但VS2005会提示该方法已过时,但仍能使用。 如果用它推荐的替代方法Dns.GetHostEntry,则有个别计算机的名称会因超时而获得不到。
http://blog.163.com/ldy_3881685/blog/static/32380136200954112940184/