c# 遍历局域网计算机(电脑)获取IP和计算机名称

c#可以遍历局域网计算机,获取全部计算机的名称和IP地址,网上提供了相关的几种方法,并对效率进行了比较,但是没有对各种方法进行比较,以确定可以使用的情况。这篇文章将对这几种方法进行分析,以帮助了解各种方法适用的情况。

  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.Linq;
  7 using System.Text;
  8 using System.Windows.Forms;
  9 using System.Net;
 10 using System.Net.NetworkInformation;
 11 using System.IO;
 12 using System.Collections;
 13 using System.Diagnostics;
 14 using System.DirectoryServices;
 15 using System.Management;
 16 
 17 namespace SocketTransferFile
 18 {
 19     /// <summary>
 20     ///
 21     /// </summary>
 22     public partial class Form1 : Form
 23     {
 24         //局域网计算机列表
 25         List<LocalMachine> machineList = new List<LocalMachine>();
 26 
 27         //Form构造函数
 28         public Form1()
 29         {
 30             InitializeComponent();
 31             InitData();
 32         }
 33 
 34         /// <summary>
 35         /// 初始化数据
 36         /// </summary>
 37         private void InitData()
 38         {
 39             lvLocalMachine.Items.Clear();
 40             machineList.Clear();
 41 
 42             //获取当前域的计算机列表
 43             label4.Text = DateTime.Now.ToString();
 44             GetAllLocalMachines();
 45 
 46             foreach (LocalMachine machine in machineList)
 47             {
 48                 ListViewItem item = new ListViewItem(new string[] { machine.Name, machine.IP });
 49                 lvLocalMachine.Items.Add(item);
 50             }
 51             label5.Text = DateTime.Now.ToString();
 52 
 53             //获取Active Directory中的计算机节点
 54             //label4.Text = DateTime.Now.ToString();
 55             //EnumComputers();
 56             //label5.Text = DateTime.Now.ToString();
 57 
 58             //获取指定IP范围内的计算机
 59             //label4.Text = DateTime.Now.ToString();
 60             //EnumComputersByPing();
 61             //label5.Text = DateTime.Now.ToString();
 62         }
 63 
 64         /// <summary>
 65         /// Handles the Click event of the button1 control.
 66         /// </summary>
 67         /// <param name="sender">The source of the event.</param>
 68         /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
 69         private void button1_Click(object sender, EventArgs e)
 70         {
 71             InitData();
 72         }
 73 
 74         /// <summary>
 75         /// 获取指定IP范围内的计算机
 76         /// </summary>
 77         private void EnumComputersByPing()
 78         {
 79             try
 80             {
 81                 for (int i = 1; i <= 254; i++)
 82                 {
 83                     Ping myPing;
 84                     myPing = new Ping();
 85                     myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted);
 86 
 87                     string pingIP = "192.168.1." + i.ToString();
 88                     myPing.SendAsync(pingIP, 1000, null);
 89                 }
 90             }
 91             catch
 92             {
 93             }
 94         }
 95 
 96         /// <summary>
 97         /// Handles the PingCompleted event of the _myPing control.
 98         /// </summary>
 99         /// <param name="sender">The source of the event.</param>
100         /// <param name="e">The <see cref="System.Net.NetworkInformation.PingCompletedEventArgs"/> instance containing the event data.</param>
101         private void _myPing_PingCompleted(object sender, PingCompletedEventArgs e)
102         {
103             if (e.Reply.Status == IPStatus.Success)
104             {
105                 LocalMachine localMachine = new LocalMachine();
106                 localMachine.IP = e.Reply.Address.ToString();
107                 //localMachine.Name = Dns.GetHostByAddress(IPAddress.Parse(e.Reply.Address.ToString())).HostName;
108                 localMachine.Name = Dns.Resolve(e.Reply.Address.ToString()).HostName;
109 
110                 ListViewItem item = new ListViewItem(new string[] { localMachine.Name, localMachine.IP });
111                 lvLocalMachine.Items.Add(item);
112             }
113         }
114 
115         /// <summary>
116         /// 获取Active Directory中的计算机节点
117         /// </summary>
118         private void EnumComputers()
119         {
120             using (DirectoryEntry root = new DirectoryEntry("WinNT:"))
121             {
122                 foreach (DirectoryEntry domain in root.Children)
123                 {
124                     foreach (DirectoryEntry computer in domain.Children)
125                     {
126                         if (computer.Name == "Schema")
127                         {
128                             continue;
129                         }
130 
131                         try
132                         {
133                             LocalMachine localMachine = new LocalMachine();
134                             localMachine.IP = Dns.GetHostEntry(computer.Name).AddressList[0].ToString();
135                             localMachine.Name = computer.Name;
136 
137                             ListViewItem item = new ListViewItem(new string[] { localMachine.Name, localMachine.IP });
138                             lvLocalMachine.Items.Add(item);
139                         }
140                         catch
141                         {
142 
143                         }
144                     }
145                 }
146             }
147         }
148 
149         /// <summary>
150         /// 获取当前域的计算机列表
151         /// </summary>
152         /// <returns></returns>
153         private void GetAllLocalMachines()
154         {
155             Process p = new Process();
156             p.StartInfo.FileName = "net";
157             p.StartInfo.Arguments = "view";
158             p.StartInfo.UseShellExecute = false;
159             p.StartInfo.RedirectStandardInput = true;
160             p.StartInfo.RedirectStandardOutput = true;
161             p.StartInfo.RedirectStandardError = true;
162             p.StartInfo.CreateNoWindow = true;
163             p.Start();
164             p.StandardInput.WriteLine("exit");
165 
166             StreamReader reader = p.StandardOutput;
167 
168             for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
169             {
170                 line = line.Trim();
171                 if (line.StartsWith(@"\"))
172                 {
173                     string name = line.Substring(2).Trim();
174 
175                     //如果有路由器,会列出路由器,但是获取不到IP地址,会报错
176                     try
177                     {
178                         LocalMachine localMachine = new LocalMachine();
179 
180                         localMachine.IP = Dns.GetHostEntry(name).AddressList[0].ToString();
181                         localMachine.Name = name;
182 
183                         machineList.Add(localMachine);
184                     }
185                     catch
186                     {
187                     }
188                 }
189             }
190         }
191     }
192 
193 public class LocalMachine
194 {
195     public string IP { get; set; }
196     public string Name { get; set; }
197 }
198 }
View Code

 http://blog.bossma.cn/dotnet/csharp_winform_lan_get_ip_and_computername/

原文地址:https://www.cnblogs.com/tianciliangen/p/3478489.html