From: http://blog.163.com/ldy_3881685/blog/static/32380136200954112940184/
Many software have the IP address function of the LAN online computer, but there are many ways to implement it in. net,
Below I will introduce several types for your reference.
1. The Microsoft Community introduced the use of Active Directory to traverse LAN
Use the directoryentry component to view the network
Web: 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); } } } }
Performance evaluation: the speed is slow and the efficiency is low. There is also an invalid result, which should be taken into consideration during the use of the schema.
2. Use DNS. gethostbyaddress and iphostentry to traverse the LAN
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); } } }
Performance Evaluation: low efficiency, slow speed, not average.
3. Use System. net. networkinformation. Ping to traverse the LAN
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); }}
Performance Evaluation: fast and efficient. If you only use an online IP address and do not use a computer name, the speed will be faster.
Note that if you use DNS. gethostbyaddress to retrieve the computer name, though the result is correct, vs2005 will prompt that the method is outdated, but it can still be used.
If you use DNS. gethostentry, the names of some computers cannot be obtained due to timeout.