如何以C#编程方式获取DNS后缀搜索列表

3

我该如何在C#中获取Windows 10机器的DNS后缀搜索列表?

例如,如果我在命令提示符中键入ipconfig,我会看到类似以下内容:

Windows IP Configuration

   Host Name . . . . . . . . . . . . : BOB
   Primary Dns Suffix  . . . . . . . : fred.george.com
   Node Type . . . . . . . . . . . . : Hybrid
   IP Routing Enabled. . . . . . . . : No
   WINS Proxy Enabled. . . . . . . . : No
   DNS Suffix Search List. . . . . . : fred.com
                                       george.com


我希望能够返回一个包含'fred.com'和'george.com'的数组。我已经尝试了一些不同的方法[1],但它们使用适配器属性(这些属性为空)。
[1] https://learn.microsoft.com/en-us/dotnet/api/system.net.networkinformation.ipinterfaceproperties.dnssuffix?view=netframework-4.8

1
为什么不直接运行该命令并提取这些行呢? - BugFinder
你可以在这里找到灵感(https://social.technet.microsoft.com/forums/scriptcenter/en-US/26a69f9c-d2d7-4cdd-8a1a-692963494622/wmi-script-for-dns-suffix),但我会选择使用BugFinder - 建立正确的列表是复杂的,因为信息是动态而不是静态的。 - RamblinRose
1个回答

3

域名后缀存储在注册表中:

System\CurrentControlSet\Services\Tcpip\Parameters
SearchList (REG_SZ)

这些设置是全局的,适用于整台机器(所有适配器和所有IP地址(IPv4和IPv6))。

使用以下代码获取字符串:

string searchList = "";
try
{
    using (var reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(tcpSettingsSubKey))
    {
        searchList = (reg.GetValue("SearchList") as string);
    }
}
catch(Exception ex)
{
    // something went wrong
}

我编写了这个类来获取更多的设置信息。在这个类中,后缀被存储在 DNSSearchListStringDNSSearchList 中。
using System;
using System.Linq;

/// <summary>
/// Retrieving some IP settings from the registry.
/// The default dns suffix is not stored there but cat be read from:
/// <see cref="System.Net.NetworkInformation.IPInterfaceProperties.DnsSuffix"/>
/// </summary>
public static class LocalMachineIpSettings
{
    private readonly static object dataReadLock = new object();
    private static bool dataReadFinished = false;

    private static string domain;
    private static string hostname;
    private static int? iPEnableRouter;

    /// <summary>
    /// Search list (the suffixes) as stored in registry
    /// </summary>
    private static string searchListString;

    /// <summary>
    /// Search list (the suffixes) as string array
    /// </summary>
    private static string[] searchList;

    /// <summary>
    /// also available at: <see cref="System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties()"/>
    /// </summary>
    public static string Domain { get { ReadValues(); return domain; } }
    /// <summary>
    /// also available at: <see cref="System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties()"/>
    /// </summary>
    public static string Hostname { get { ReadValues(); return hostname; } }
    public static int? IPEnableRouter { get { ReadValues(); return iPEnableRouter; } }
    public static string[] DNSSearchList { get { ReadValues(); return searchList; } }
    public static string DNSSearchListString { get { ReadValues(); return searchListString; } }

    private static void ReadValues()
    {
        lock (dataReadLock)
        {
            if (dataReadFinished == true)
            {
                return;
                //<----------
            }

            ForceRefresh();
        }
    }

    /// <summary>
    /// Reread the values
    /// </summary>
    public static void ForceRefresh()
    {
        const string tcpSettingsSubKey = @"System\CurrentControlSet\Services\Tcpip\Parameters";

        lock (dataReadLock)
        {
            try
            {
                Microsoft.Win32.RegistryKey reg = null;
                using (reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(tcpSettingsSubKey))
                {
                    domain = (reg.GetValue("Domain") as string);
                    hostname = (reg.GetValue("Hostname") as string);
                    iPEnableRouter = (reg.GetValue("IPEnableRouter") as int?);
                    searchListString = (reg.GetValue("SearchList") as string);
                    searchList = searchListString?.Split(new[] { ' ', ',', ';' }, StringSplitOptions.RemoveEmptyEntries).Select(o => o.Trim(' ', '.')).ToArray();
                }

                dataReadFinished = true;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"Cannot access HKLM\\{ tcpSettingsSubKey } or values beneath see inner exception for details", ex);
                //<----------
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接