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

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.NetworkInformation;
using System.IO;
using System.Collections;
using System.Diagnostics;
using System.DirectoryServices;
using System.Management; namespace SocketTransferFile
{
/// <summary>
///
/// </summary>
public partial class Form1 : Form
{
//局域网计算机列表
List<LocalMachine> machineList = new List<LocalMachine>(); //Form构造函数
public Form1()
{
InitializeComponent();
InitData();
} /// <summary>
/// 初始化数据
/// </summary>
private void InitData()
{
lvLocalMachine.Items.Clear();
machineList.Clear(); //获取当前域的计算机列表
label4.Text = DateTime.Now.ToString();
GetAllLocalMachines(); foreach (LocalMachine machine in machineList)
{
ListViewItem item = new ListViewItem(new string[] { machine.Name, machine.IP });
lvLocalMachine.Items.Add(item);
}
label5.Text = DateTime.Now.ToString(); //获取Active Directory中的计算机节点
//label4.Text = DateTime.Now.ToString();
//EnumComputers();
//label5.Text = DateTime.Now.ToString(); //获取指定IP范围内的计算机
//label4.Text = DateTime.Now.ToString();
//EnumComputersByPing();
//label5.Text = DateTime.Now.ToString();
} /// <summary>
/// Handles the Click event of the button1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void button1_Click(object sender, EventArgs e)
{
InitData();
} /// <summary>
/// 获取指定IP范围内的计算机
/// </summary>
private void EnumComputersByPing()
{
try
{
for (int i = ; i <= ; i++)
{
Ping myPing;
myPing = new Ping();
myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted); string pingIP = "192.168.1." + i.ToString();
myPing.SendAsync(pingIP, , null);
}
}
catch
{
}
} /// <summary>
/// Handles the PingCompleted event of the _myPing control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Net.NetworkInformation.PingCompletedEventArgs"/> instance containing the event data.</param>
private void _myPing_PingCompleted(object sender, PingCompletedEventArgs e)
{
if (e.Reply.Status == IPStatus.Success)
{
LocalMachine localMachine = new LocalMachine();
localMachine.IP = e.Reply.Address.ToString();
//localMachine.Name = Dns.GetHostByAddress(IPAddress.Parse(e.Reply.Address.ToString())).HostName;
localMachine.Name = Dns.Resolve(e.Reply.Address.ToString()).HostName; ListViewItem item = new ListViewItem(new string[] { localMachine.Name, localMachine.IP });
lvLocalMachine.Items.Add(item);
}
} /// <summary>
/// 获取Active Directory中的计算机节点
/// </summary>
private void EnumComputers()
{
using (DirectoryEntry root = new DirectoryEntry("WinNT:"))
{
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[].ToString();
localMachine.Name = computer.Name; ListViewItem item = new ListViewItem(new string[] { localMachine.Name, localMachine.IP });
lvLocalMachine.Items.Add(item);
}
catch
{ }
}
}
}
} /// <summary>
/// 获取当前域的计算机列表
/// </summary>
/// <returns></returns>
private void GetAllLocalMachines()
{
Process p = new Process();
p.StartInfo.FileName = "net";
p.StartInfo.Arguments = "view";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine("exit"); StreamReader reader = p.StandardOutput; for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
line = line.Trim();
if (line.StartsWith(@"\\"))
{
string name = line.Substring().Trim(); //如果有路由器,会列出路由器,但是获取不到IP地址,会报错
try
{
LocalMachine localMachine = new LocalMachine(); localMachine.IP = Dns.GetHostEntry(name).AddressList[].ToString();
localMachine.Name = name; machineList.Add(localMachine);
}
catch
{
}
}
}
}
} public class LocalMachine
{
public string IP { get; set; }
public string Name { get; set; }
}
}

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

最新文章

  1. Redis集群~StackExchange.redis连接Twemproxy代理服务器
  2. ios学习-制作一个浏览图片的Demo
  3. C语言程序设计第二次作业
  4. Ext.Net 学习随笔 003 超链接按钮
  5. 5分钟实现VS2010整合NUnit进行单元测试
  6. SQL Server连接数据库失败,可能的问题!
  7. Android --ListView模板
  8. pageX,clientX,offsetX,layerX的区别
  9. Basic Vlan Concepts
  10. 基于WebForm+EasyUI的业务管理系统形成之旅 -- 施工计划查询(Ⅷ)
  11. [Java]重载,重写以及继承,多态的区别
  12. reflact中GetMethod方法的使用
  13. Android抽屉效果 DrawerLayout 入门经验总结
  14. mssql sqlserver 三种数据表数据去重方法分享
  15. 模板std::mutex用法:
  16. java常见报错及解决
  17. Python module ---- abc
  18. 欧拉函数-gcd-快速幂(牛客寒假算法基础集训营1-D-小a与黄金街道)
  19. Django 系列博客(七)
  20. ionic2/cordova自定义插件集成aar包

热门文章

  1. 每日一题-——LeetCode(111)二叉树的最小深度
  2. Chkdsk /f 修复无法识别EXFAT卷文件系统
  3. 常见错误 RuntimeError: expected type torch.FloatTensor but got torch.cuda.FloatTensor
  4. JDBC课程2--实现Statement(用于执行SQL语句)--使用自定义的JDBCTools的工具类静态方法,包括insert/update/delete三合一
  5. 第八届蓝桥杯C/C++程序设计本科B组决赛 ——发现环(编程大题_签到题_tarjan判环)
  6. python3 读取avro文件
  7. 前端笔记-bom
  8. dos中查找端口的PID,并在任务管理器中处理端口
  9. 01_Tutorial 1: Serialization 序列化
  10. PowerDesigner创建表 拷贝创建表语句 SQLSERVER创建数据库 使用查询 创建表 并且添加数据