You need to enable JavaScript to run this app. C#如何通过DNS类将AD域内主机名解析为对应的IP地址
优惠活动
大模型
产品
解决方案
定价
更多

C#如何通过DNS类将AD域内主机名解析为对应的IP地址

完全可以基于你现有的DNS查询逻辑扩展实现该需求。AD本身不存储设备的实时IP地址,通过主机名调用DNS接口解析是域环境下获取设备IP的标准实现方案。


前提条件

  • 程序运行设备的DNS服务器需配置为域控DNS,且网络可正常访问所有目标设备
  • 需提前引入System.Net、System.Net.Sockets两个命名空间

实现代码

1. 封装IP查询通用方法

// 传入计算机名,返回符合过滤规则的IPv4地址,解析失败返回空字符串
private string GetIPByComputerName(string computerName)
{
    try
    {
        // 若直接解析主机名失败,可拼接域后缀重试,比如 computerName += ".domain.com"
        var hostEntry = Dns.GetHostEntry(computerName);
        foreach (var ip in hostEntry.AddressList)
        {
            // 只保留IPv4地址
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                string ipStr = ip.ToString();
                // 复用原有过滤逻辑:排除结尾为.1的IP
                if (!ipStr.EndsWith(".1"))
                {
                    return ipStr;
                }
            }
        }
        return string.Empty;
    }
    catch (SocketException)
    {
        // 主机离线/无DNS记录时直接返回空,避免程序崩溃
        return string.Empty;
    }
}

2. 改造原有AD查询方法

private void FindComputersInADWithIP()
{
    // 同时存储计算机名和对应IP
    Dictionary<string, string> computerIpMap = new Dictionary<string, 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;
        adsearcher.PropertiesToLoad.Add("name");

        foreach (SearchResult searchResult in adsearcher.FindAll())
        {
            if (searchResult.Properties["name"].Count > 0)
            {
                string computer = (string)searchResult.Properties["name"][0];
                // 调用DNS解析方法获取IP
                string ip = GetIPByComputerName(computer);
                if (!string.IsNullOrEmpty(ip))
                {
                    computerIpMap.Add(computer, ip);
                }
            }
        }
    }
    // 按计算机名排序输出结果
    foreach (var item in computerIpMap.OrderBy(kv => kv.Key))
    {
        Console.WriteLine($"计算机名:{item.Key},IP地址:{item.Value}");
    }
}

优化建议与限制说明

  • 若域内设备数量较多,同步DNS解析耗时较长,可改用Parallel.ForEach并行查询,搭配ConcurrentDictionary存储结果提升效率
  • 仅能查询到当前在线、且DNS服务器存在对应记录的设备,离线设备会返回空值
  • 若设备存在多块网卡、多个IPv4地址,上述方法仅返回第一个符合过滤规则的IP,如需保留所有IP可将返回值修改为List<string>

内容的提问来源于stack exchange,提问作者Subscaper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 13:00:04