c# 掃描區域網路IP列表的幾種方法

來源:互聯網
上載者:User

出自: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,則有個別電腦的名稱會因逾時而獲得不到。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.