【问题标题】:Get FQDN using C# bypassing alias in hosts file使用 C# 绕过主机文件中的别名获取 FQDN
【发布时间】:2021-01-25 17:58:35
【问题描述】:

在域环境中,我有几个客户端通过本地主机文件中的别名引用服务器。我需要获取服务器的真实主机名。使用 Net.Dns.GetHostEntry 或 Net.Dns.Resolve 时,仅返回 hosts 文件中的别名。

var addr = System.Net.Dns.GetHostAddresses("FileServer")[0];  // assume at least one entry
var fqdn = System.Net.Dns.GetHostEntry(addr).HostName;

使用 NSLOOKUP 的反向查找按预期工作。是否可以强制 Dns 方法忽略 hosts 文件?

【问题讨论】:

标签: c# .net windows networking


【解决方案1】:

您可以在 C# 上调用 NSLOOKUP 这是c#的一个方法。

        /// <summary>
        /// Get HostName from IPv4
        /// </summary>
        /// <param name="ipv4"></param>
        /// <returns></returns>
        public static string NslookupIP(string ipv4, string dnsServerIpv4)
        {

            if (IPAddress.TryParse(ipv4, out IPAddress ipaddress))
            {
                if (ipaddress.AddressFamily != AddressFamily.InterNetwork)
                {
                    throw new Exception("ipv4 is no a valid IPv4");
                }

            }
            else
            {
                throw new Exception("ipv4 is no a valid IPv4");
            }

            Process pProcess = new Process();
            pProcess.StartInfo.FileName = "nslookup";
            pProcess.StartInfo.Arguments = $"{ipv4}";
            pProcess.StartInfo.UseShellExecute = false;
            pProcess.StartInfo.RedirectStandardOutput = true;
            pProcess.StartInfo.CreateNoWindow = true;
            pProcess.Start();
            string cmdOutput = pProcess.StandardOutput.ReadToEnd();
            string pattern = @"^Name:\s*(?<host>(.*))$";

            foreach (Match m in Regex.Matches(cmdOutput, pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline))
            {
                    return m.Groups["host"].Value;
            }

            return "";
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 2010-09-14
    • 2015-07-08
    • 2013-02-17
    • 2020-01-25
    • 2020-03-11
    • 1970-01-01
    相关资源
    最近更新 更多