首页 > 解决方案 > C# 使用 Dns 将主机名解析为 IP 地址

问题描述

得到了我正在办公室用 C# 编写的这个程序。

所以我可以从域中读取所有计算机名称,将它们填充到列表中并打印出来。

使用此代码:

    `private void FindComputersInAD()
    {
    List<string> computerNames = new List<string>();
        DirectoryContext dirCtx = new DirectoryContext(DirectoryContextType.Domain, "domain.com");
        using (Domain usersDomain = Domain.GetDomain(dirCtx))
        using (DirectorySearcher adsearcher = new DirectorySearcher(usersDomain.GetDirectoryEntry()))
        {
            adsearcher.Filter = ("(objectCategory=computer)");                                                                                                          
            adsearcher.SizeLimit = 0;
            adsearcher.PageSize = 250;

            // Let searcher know which properties are going to be used, and only load those
            adsearcher.PropertiesToLoad.Add("name");

            foreach (SearchResult searchResult in adsearcher.FindAll())
            {
                if (searchResult.Properties["name"].Count > 0)
                {
                    string computer = (string)searchResult.Properties["name"][0];                      
                    computerNames.Add(computer);
                }
            }
        }
        computerNames.Sort();
        computerNames.ForEach(Console.WriteLine);
    }`

现在我得到了所有的计算机名称,我也想得到他们的 IP 地址。但是没有这样的属性。

我搜索了很多并尝试了一些东西,但没有任何效果。

我可以使用 DNS 类来执行此操作吗?

我使用这种方法来获取主机 IP 地址:

private void GetLocalIPAddress()
    {
        string _subString;
        var _host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var _ip in _host.AddressList)
        {
            if (_ip.AddressFamily == AddressFamily.InterNetwork)
            {
                _subString = _ip.ToString().Substring(_ip.ToString().Length - 2);
                //When a IP Address ends with .1, don't add it to the List.
                if (_subString != ".1")
                {
                    _hostIPAddress = _ip.ToString();
                }
            }
        }
    }

我也可以使用它来获取计算机的 IP 地址吗?

如果你能帮助我,我会很高兴:)

提前致谢

标签: c#dnsactive-directoryip-addresscomputer-name

解决方案


所以我找到了自己的答案。由于所有计算机都在同一个域中,我打开了 cmd 并尝试了 nslookup。它返回了我想要的 IP 地址。

所以我刚刚建立了一个 C# DNSLookup 方法,看起来像这样:

 private void DNSLookup(string computerNameOrAddress)
    {
        IPHostEntry hostEntry = Dns.GetHostEntry(computerNameOrAddress);

        IPAddress[] ips = hostEntry.AddressList;
        foreach (IPAddress ip in ips)
        {
            Console.WriteLine("  Address: {0}", ip);        
        }
    }

无论如何感谢您的关注:)


推荐阅读