using System.Net;
using System.Net.NetworkInformation;
using System.Collections.Generic;
using System.DirectoryServices;
namespace ConApp
{
public class ListLanNet
{
List<LocalMachine> hostLst=null;
public ListLanNet()
{
hostLst =new List<LocalMachine>();
}
public List<LocalMachine> HostList
{
get { return hostLst; }
}
/// <summary>
/// 方法不够好,本想写外面的,想想ip是不确定的,先这么招吧?
/// </summary>
public void EnumComputersByPing()
{
try
{
hostLst.Clear();
for (int i = 1; i <= 254; i++)
{
string ip = "192.168.0.";
ip+=i.ToString();
Ping pg = new Ping();
pg.PingCompleted += new PingCompletedEventHandler(Ping_PingCompleted);
pg.SendAsync(ip, 1000, null);
}
}
catch {}
}
private void Ping_PingCompleted(object sender, PingCompletedEventArgs e)
{
if (e.Reply.Status == IPStatus.Success)
{
LocalMachine localMachine = new LocalMachine();
localMachine.IP = e.Reply.Address.ToString();
localMachine.Name = Dns.GetHostEntry(IPAddress.Parse(e.Reply.Address.ToString())).HostName;
hostLst.Add(localMachine);
}
}
/// <summary>
/// 类型可以是WinNT:区分大小写
/// </summary>
/// <param name="type"></param>
public void EnumComputersByDirectoryEntry(string type)
{
hostLst.Clear();
using (DirectoryEntry root = new DirectoryEntry(type))
{
foreach (DirectoryEntry domain in root.Children)
{
foreach (DirectoryEntry computer in domain.Children)
{
if (computer.Name == "Schema")
{
continue;
}
try
{
LocalMachine localMachine = new LocalMachine();
localMachine.IP = Dns.GetHostEntry(computer.Name).AddressList[0].ToString();
localMachine.Name = computer.Name;
hostLst.Add(localMachine);
}
catch { }
}
}
}
}
}
public class LocalMachine
{
public string IP { get; set; }
public string Name { get; set; }
}
}
获取局域网主机
最新推荐文章于 2021-04-29 14:26:37 发布