c#怎么读取局域网内的所有主机的ip

2025-02-25 16:17:33
推荐回答(1个)
回答1:

            
          list ipList=new list();
          public void getIP()
          {
            
            //获取本地机器名 
            string _myHostName = Dns.GetHostName();
            //获取本机IP 
            string _myHostIP = Dns.GetHostEntry(_myHostName).AddressList[0].ToString();
            //截取IP网段
            string ipDuan = _myHostIP.Remove(_myHostIP.LastIndexOf('.'));
            //枚举网段计算机
            for (int i = 1; i <= 255; i++)
            {
                Ping myPing = new Ping();
                myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted);
                string pingIP = ipDuan + "." + i.ToString();
                myPing.SendAsync(pingIP, 1000, null);
                
            }
            }
            void _myPing_PingCompleted(object sender, PingCompletedEventArgs e)
        {
            if (e.Reply.Status == IPStatus.Success)
            {
                ipList.Add(e.Reply.Address.ToString());
            }
        }

 IP地址就在ipList里