如何在C#中获取本地计算机的完全限定域名(FQDN)?
/// <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;
}
private static string GetLocalhostFQDN()
{
var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
return $"{ipProperties.HostName}.{ipProperties.DomainName}";
}
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;
}