zoukankan      html  css  js  c++  java
  • C#中怎么用代码来实现查看局域网的电脑和IP

    1、微软社区上介绍了使用Active Directory 来遍历局域网
    利用DirectoryEntry组件来查看网络
    网址:http://www.microsoft.com/china/communITy/program/originalarticles/techdoc/DirectoryEntry.mspx


    private void EnumComputers()
    {
        using(DirectoryEntry root = new DirectoryEntry("WinNT:"))
        {
          foreach(DirectoryEntry domain in root.Children)
          {
            Console.WriteLine("Domain | WorkGroup: "+domain.Name);
            foreach(DirectoryEntry computer in domain.Children)
        {
         Console.WriteLine("Computer: "+computer.Name);
        }
       }
    }
    }


    效果评价:速度慢,效率低,还有一个无效结果 Computer: Schema 使用的过程中注意虑掉。

    2、利用Dns.GetHostByAddress和IPHostEntry遍历局域网


    private void EnumComputers()
    {
    for (int i = 1; i <= 255; i++)
    {
    string scanIP = "192.168.0." + i.ToString();

    IPAddress myScanIP = IPAddress.Parse(scanIP);

    IPHostEntry myScanHost = null;

    try
    {
        myScanHost = Dns.GetHostByAddress(myScanIP);
    }

    catch
    {
        continue;
    }

    if (myScanHost != null)
    {
        Console.WriteLine(scanIP+"|"+myScanHost.HostName);
    }
    }
    }


    效果评价:效率低,速度慢,不是一般的慢。

    3、使用System.Net.NetworkInformation.Ping来遍历局域网


    private void EnumComputers()
    {
    try
    {
       for (int i = 1; i <= 255; i++)
       {
         Ping myPing;
         myPing = new Ping();
         myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted);

         string pingIP = "192.168.0." + i.ToString();
         myPing.SendAsync(pingIP, 1000, null);
       }
    }
    catch
    {
    }
    }

    PRIVATE void _myPing_PingCompleted(object sender, PingCompletedEventArgs e)
    {
    if (e.Reply.Status == IPStatus.Success)
    {
        Console.WriteLine(e.Reply.Address.ToString() + "|" + Dns.GetHostByAddress(IPAddress.Parse(e.Reply.Address.ToString())).HostName);
    }

    }


    效果评价:速度快,效率高,如果只取在线的IP,不取计算机名,速度会更快。
    需要注意的是取计算机名称如果用Dns.GetHostByAddress取计算机名称,结果虽然正确,但VS2005会提示该方法已过时,但仍能使用。
    如果用它推荐的替代方法Dns.GetHostEntry,则有个别计算机的名称会因超时而获得不到。

  • 相关阅读:
    KNN 与 K
    k 近邻算法(k-Nearest Neighbor,简称kNN)
    ANN神经网络——Sigmoid 激活函数编程练习 (Python实现)
    ANN神经网络——实现异或XOR (Python实现)
    Logistic Regression 之错误翻译
    浅谈回归(二)——Regression 之历史错误翻译
    浅谈回归Regression(一)
    交叉验证 Cross validation
    Git学习-Git时光机之版本回退(二)
    ubuntu16.04安装网易云音乐
  • 原文地址:https://www.cnblogs.com/xiaowei0705/p/2038066.html
Copyright © 2011-2022 走看看