C#实现查看局域网电脑PC名和IP的几种方式
1.微软社区上介绍了使用Active Directory 来遍历局域网利用DirectoryEntry组件来查看网络
网址:http://www.microsoft.com/china/communITy/program/originalarticles/techdoc/DirectoryEntry.mspxprivate 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);
}
}
谢谢分享!!!
页:
[1]