获取局域网主机

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; }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值