出自:http://blog.163.com/ldy_3881685/blog/static/32380136200954112940184/
很多軟體都有獲知區域網路線上電腦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 = 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,則有個別電腦的名稱會因逾時而獲得不到。