如何在C#/.NET中查找本地计算机的FQDN?

如何在C#/.NET中查找本地计算机的FQDN?,c#,localhost,fqdn,C#,Localhost,Fqdn,如何在C#?中获取本地计算机的FQDN注意:此解决方案仅在针对.NET 2.0(及更高版本)框架时有效 更新 因为很多人都评论说这更简洁,所以我决定在答案中添加一些评论 需要注意的最重要的一点是,我给出的代码与以下代码不等价: Dns.GetHostEntry("LocalHost").HostName 在一般情况下,当机器联网并且是域的一部分时,两种方法通常会产生相同的结果,而在其他情况下,结果会有所不同 当机器不是域的一部分时,输出将不同。在这种情况下,Dns.GetHostEntry(“

如何在C#?

中获取本地计算机的FQDN注意:此解决方案仅在针对.NET 2.0(及更高版本)框架时有效

更新

因为很多人都评论说这更简洁,所以我决定在答案中添加一些评论

需要注意的最重要的一点是,我给出的代码与以下代码不等价:

Dns.GetHostEntry("LocalHost").HostName
在一般情况下,当机器联网并且是域的一部分时,两种方法通常会产生相同的结果,而在其他情况下,结果会有所不同

当机器不是域的一部分时,输出将不同。在这种情况下,
Dns.GetHostEntry(“LocalHost”).HostName
将返回
LocalHost
,而上面的
GetFQDN()
方法将返回主机的NETBIOS名称

当查找计算机FQDN的目的是记录信息或生成报告时,此区别非常重要。大多数时候,我在日志或报告中使用了这种方法,这些日志或报告随后用于将信息映射回特定的机器。如果机器未联网,则
localhost
标识符无效,而名称提供了所需的信息

因此,最终取决于每个用户,根据他们需要的结果,哪种方法更适合他们的应用程序。但说这个答案不够简洁是错误的,充其量只是表面的


查看一个输出不同的示例:

稍微简化Miky D的代码

    public static string GetLocalhostFqdn()
    {
        var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
        return string.Format("{0}.{1}", ipProperties.HostName, ipProperties.DomainName);
    }

这是在PowerShell中,为了见鬼:

$ipProperties = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
"{0}.{1}" -f $ipProperties.HostName, $ipProperties.DomainName

对于框架1.1来说,它非常简单:

System.Net.Dns.GetHostByName("localhost").HostName

然后删除计算机NETBIOS名称以仅检索域名如果要整理它并处理异常,请尝试以下操作:

public static string GetLocalhostFQDN()
        {
            string domainName = string.Empty;
            try
            {
                domainName = NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
            }
            catch
            {
            }
            string fqdn = "localhost";
            try
            {
                fqdn = System.Net.Dns.GetHostName();
                if (!string.IsNullOrEmpty(domainName))
                {
                    if (!fqdn.ToLowerInvariant().EndsWith("." + domainName.ToLowerInvariant()))
                    {
                        fqdn += "." + domainName;
                    }
                }
            }
            catch
            {
            }
            return fqdn;
        }

对Matt Z的答案稍作改进,以便在计算机不是域成员时不会返回尾随的句号:

public static string GetLocalhostFqdn()
{
    var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
    return string.IsNullOrWhiteSpace(ipProperties.DomainName) ? ipProperties.HostName : string.Format("{0}.{1}", ipProperties.HostName, ipProperties.DomainName);
}
这一点已被包括在内。这种方法比公认的答案更简短,而且可能比下一个投票最多的答案更可靠。请注意,据我所知,此不使用NetBIOS名称,因此它应该适合Internet使用

.NET2.0+ .NET 1.0-1.1
您可以尝试以下操作:

return System.Net.Dns.GetHostEntry(Environment.MachineName).HostName;

这应该为您提供当前本地计算机的FQDN(或者您可以指定任何主机)。

将此作为我的选项之一,将主机名和域名结合起来以生成报告,添加了在未捕获域名时要填写的通用文本,这是客户的要求之一

我使用C#5.0、.Net 4.5.1对其进行了测试

private static string GetHostnameAndDomainName()
{
       // if No domain name return a generic string           
       string currentDomainName = IPGlobalProperties.GetIPGlobalProperties().DomainName ?? "nodomainname";
       string hostName = Dns.GetHostName();

    // check if current hostname does not contain domain name
    if (!hostName.Contains(currentDomainName))
    {
        hostName = hostName + "." + currentDomainName;
    }
    return hostName.ToLower();  // Return combined hostname and domain in lowercase
} 

使用Miky Dinescu解决方案的理念构建。

我们已经实施了建议的结果,以使用这种方式:

return System.Net.Dns.GetHostEntry(Environment.MachineName).HostName;
然而,事实证明,当计算机名超过15个字符并且使用NetBios名称时,这并不正确。Environment.MachineName只返回部分名称,解析主机名返回相同的计算机名

经过一些研究,我们找到了解决此问题的解决方案:

System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).HostName

这解决了包括计算机名在内的所有问题。

我使用了以下方法:

private static string GetLocalhostFQDN()
{
    var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
    return $"{ipProperties.HostName}.{ipProperties.DomainName}";
}

如果我测试的答案中没有一个确实提供了我想要的DNS后缀。这是我想到的

public static string GetFqdn()
{
    var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
    var ipprops = networkInterfaces.First().GetIPProperties();
    var suffix = ipprops.DnsSuffix;
    return $"{IPGlobalProperties.GetIPGlobalProperties().HostName}.{suffix}";
}

处理FQ Hostname/Hostname/NetBIOS Machinename/DomainName周围所有情况的方法集合

    /// <summary>
    /// Get the full qualified hostname
    /// </summary>
    /// <param name="throwOnMissingDomainName"></param>
    /// <returns></returns>
    public static string GetMachineFQHostName(bool throwOnMissingDomainName = false)
    {
        string domainName = GetMachineFQDomainName();
        string hostName = GetMachineHostName();

        if (string.IsNullOrEmpty(domainName) && throwOnMissingDomainName) throw new Exception($"Missing domain name on machine: { hostName }");
        else if (string.IsNullOrEmpty(domainName)) return hostName;
        //<----------

        return $"{ hostName }.{ domainName }";
    }


    /// <summary>
    /// Get the NetBIOS name of the local machine
    /// </summary>
    /// <returns></returns>
    public static string GetMachineName()
    {
        return Environment.MachineName;
    }

    /// <summary>
    /// Get the Hostname from the local machine which differs from the NetBIOS name when 
    /// longer than 15 characters
    /// </summary>
    /// <returns></returns>
    public static string GetMachineHostName()
    {
        /// I have been told that GetHostName() may return the FQName. Never seen that, but better safe than sorry ....
        string hostNameRaw = System.Net.Dns.GetHostName();
        return hostNameRaw.Split('.')[0];
    }

    /// <summary>
    /// Check if hostname and NetBIOS name are equal
    /// </summary>
    /// <returns></returns>
    public static bool AreHostNameAndNetBIOSNameEqual()
    {
        return GetMachineHostName().Equals(GetMachineName(), StringComparison.OrdinalIgnoreCase);
    }

    /// <summary>
    /// Get the domain name without the hostname
    /// </summary>
    /// <returns></returns>
    public static string GetMachineFQDomainName()
    {
        return IPGlobalProperties.GetIPGlobalProperties().DomainName;
    }
//
///获取完全限定的主机名
/// 
/// 
/// 
公共静态字符串GetMachineFQHostName(bool throwOnMissingDomainName=false)
{
字符串domainName=GetMachineFQDomainName();
字符串hostName=GetMachineHostName();
if(string.IsNullOrEmpty(domainName)&&throwOnMissingDomainName)抛出新异常($“计算机上缺少域名:{hostName}”);
else if(string.IsNullOrEmpty(domainName))返回主机名;

//“并处理异常”-失败。你认为catch本身可以处理异常!不,我认为你想如何处理异常是你需要自己决定的事情。如果你无法找回域名,你会建议如何处理它?记录错误报告并警告用户出了问题,而不是向客户机代码提供错误信息ion。与Micky D的代码不同,如果计算机不是域的成员,则返回带有附加全站的主机名。此外,它使用NetBIOS名称而不是DNS主机名。我相信NetBIOS名称仅适用于LAN。可能添加一个
.Trim(“.”)
到最后一行删除。如果存在。请注意,我认为这使用的是NetBIOS主机名,因此可能不适合Internet使用。2013年,
GetHostByName(“localhost”)
被淘汰。VS 2010建议我使用
GetHostEntry(“localhost”)
相反,这很好。@piedar,你可能错过了.NET 1.1的部分。我想在这个答案中添加更新信息,因为它是最简单的,也是我最喜欢的。我可能没有滚动足够远的距离来查看你的答案,这确实使我的评论变得不必要。@DexterLegaspi-Sam的答案很好(我自己甚至还加了点播)但这并不等同于我的答案,也不一定更好。有关详细信息,请参阅我的更新答案。@MikeDinescu问题是如何获得FQDN,这意味着机器位于网络上,并且是域的一部分。接受的答案可以解决问题,但Sam的答案更“精确”(因为没有更好的术语)这是正确的答案!但是不要执行
Dns.GetHostEntry(“LocalHost”).HostName
您最好像这样传递一个空字符串:
Dns.GetHostEntry(“”)。HostName
使用
Dns.GetHostEntry(“LocalHost”)。HostName
我总是得到主机名(不是netbios)使用主域后缀。这不取决于计算机是否是域的一部分,而是取决于DNS服务器
private static string GetLocalhostFQDN()
{
    var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
    return $"{ipProperties.HostName}.{ipProperties.DomainName}";
}
public static string GetFqdn()
{
    var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
    var ipprops = networkInterfaces.First().GetIPProperties();
    var suffix = ipprops.DnsSuffix;
    return $"{IPGlobalProperties.GetIPGlobalProperties().HostName}.{suffix}";
}
    /// <summary>
    /// Get the full qualified hostname
    /// </summary>
    /// <param name="throwOnMissingDomainName"></param>
    /// <returns></returns>
    public static string GetMachineFQHostName(bool throwOnMissingDomainName = false)
    {
        string domainName = GetMachineFQDomainName();
        string hostName = GetMachineHostName();

        if (string.IsNullOrEmpty(domainName) && throwOnMissingDomainName) throw new Exception($"Missing domain name on machine: { hostName }");
        else if (string.IsNullOrEmpty(domainName)) return hostName;
        //<----------

        return $"{ hostName }.{ domainName }";
    }


    /// <summary>
    /// Get the NetBIOS name of the local machine
    /// </summary>
    /// <returns></returns>
    public static string GetMachineName()
    {
        return Environment.MachineName;
    }

    /// <summary>
    /// Get the Hostname from the local machine which differs from the NetBIOS name when 
    /// longer than 15 characters
    /// </summary>
    /// <returns></returns>
    public static string GetMachineHostName()
    {
        /// I have been told that GetHostName() may return the FQName. Never seen that, but better safe than sorry ....
        string hostNameRaw = System.Net.Dns.GetHostName();
        return hostNameRaw.Split('.')[0];
    }

    /// <summary>
    /// Check if hostname and NetBIOS name are equal
    /// </summary>
    /// <returns></returns>
    public static bool AreHostNameAndNetBIOSNameEqual()
    {
        return GetMachineHostName().Equals(GetMachineName(), StringComparison.OrdinalIgnoreCase);
    }

    /// <summary>
    /// Get the domain name without the hostname
    /// </summary>
    /// <returns></returns>
    public static string GetMachineFQDomainName()
    {
        return IPGlobalProperties.GetIPGlobalProperties().DomainName;
    }