Как найти FQDN локальной машины в C#/.NET?

Используйте Sqoop 2 и сделайте весь uppercase.it's SQL-запросов известной проблемой в Kylin.

84
задан Sam 13 June 2013 в 05:07
поделиться

4 ответа

NOTE: This solution only works when targeting the .NET 2.0 (and newer) frameworks.

using System;
using System.Net;
using System.Net.NetworkInformation;
//...

public static string GetFQDN()
{
    string domainName = IPGlobalProperties.GetIPGlobalProperties().DomainName;
    string hostName = Dns.GetHostName();

    domainName = "." + domainName;
    if(!hostName.EndsWith(domainName))  // if hostname does not already include domain name
    {
        hostName += domainName;   // add the domain name part
    }

    return hostName;                    // return the fully qualified name
}

UPDATE

Since a lot of people have commented that Sam's Answer is more concise I've decided to add some comments to the answer.

The most important thing to note is that the code I gave is not equivalent to the following code:

Dns.GetHostEntry("LocalHost").HostName

While in the general case when the machine is networked and part of a domain, both methods will generally produce the same result, in other scenarios the results will differ.

A scenario where the output will be different is when the machine is not part of a domain. In this case, the Dns.GetHostEntry("LocalHost").HostName will return localhost while the GetFQDN() method above will return the NETBIOS name of the host.

This distinction is important when the purpose of finding the machine FQDN is to log information, or generate a report. Most of the time I've used this method in logs or reports that are subsequently used to map information back to a specific machine. If the machines are not networked, the localhost identifier is useless, whereas the name gives the needed information.

So ultimately it's up to each user which method is better suited for their application, depending on what result they need. But to say that this answer is wrong for not being concise enough is superficial at best.

See an example where the output will be different: http://ideone.com/q4S4I0

135
ответ дан 24 November 2019 в 08:26
поделиться

Небольшое упрощение кода Miky D

    public static string GetLocalhostFqdn()
    {
        var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
        return string.Format("{0}.{1}", ipProperties.HostName, ipProperties.DomainName);
    }
63
ответ дан 24 November 2019 в 08:26
поделиться

Вот он в PowerShell, черт возьми:

$ipProperties = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
"{0}.{1}" -f $ipProperties.HostName, $ipProperties.DomainName
17
ответ дан 24 November 2019 в 08:26
поделиться

А для Framework 1.1 это так просто:

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

А затем удалите имя NETBIOS машины, чтобы получить только имя домена

15
ответ дан 24 November 2019 в 08:26
поделиться
Другие вопросы по тегам:

Похожие вопросы: