【问题标题】:Get ALL IP addresses that contains X hostname in LAN (Multiple same hostnames)获取 LAN 中包含 X 主机名的所有 IP 地址(多个相同的主机名)
【发布时间】:2021-03-25 03:06:53
【问题描述】:

我正在尝试遍历范围 (192.168.1.1 - 192.168.1.255) 内的所有 IP 地址并打印出包含 X 主机名的 IP 地址。

我正在尝试使用此代码,但它只给了我最后一个包含 X 主机名的 IP 地址,但有多个 IP 地址与此主机名:

string customPc = "myCustomPc";
            IPHostEntry host = Dns.GetHostEntry(customPc);

            foreach (IPAddress theaddress in host.AddressList)
            {
                Console.WriteLine(theaddress.ToString());
            }

另外,我正在尝试这样做,但它打印出相同的结果 - 具有此主机名的最后一个 IP 地址:

string host = "myCustomPc";
                IPHostEntry hostEntry;

                hostEntry = Dns.GetHostEntry(host); 

                if (hostEntry.AddressList.Length > 0)
                {
                    var ip = hostEntry.AddressList[0];
                    Console.WriteLine(ip + ": Your custom PC is found!");
                }`

【问题讨论】:

    标签: c# asp.net network-programming ip-address hostname


    【解决方案1】:

    您是否只打印 AddressList 集合中的一个元素?

    试试这个:

    foreach(var a in hostEntry.AddressList) {
      Console.WriteLine(a + ": Your custom PC is found!");
    }
    

    或使用Dns.GetHostAddresses(String) Method

    foreach(var a in Dns.GetHostAddresses(host)) {
      Console.WriteLine(a);
    }
    

    如何从 192.168.1.1 循环到 192.168.1.255

    这是一种方法

    for(int d = 1; d <=255; d++)
    {
       var ipstr = $"192.161.1.{d}";
    }
    

    【讨论】:

    • 我试过了,它只给了我一个IP地址,但是我的局域网中大约有7-10台计算机具有相同的主机名
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 2014-04-12
    • 2018-01-02
    • 2018-08-26
    • 2012-04-12
    相关资源
    最近更新 更多