developer tip

C # /. NET에서 로컬 컴퓨터의 FQDN을 찾는 방법은 무엇입니까?

optionbox 2020. 9. 20. 09:31
반응형

C # /. NET에서 로컬 컴퓨터의 FQDN을 찾는 방법은 무엇입니까?


C #에서 로컬 컴퓨터의 FQDN을 어떻게 얻을 수 있습니까?


참고 :이 솔루션은 .NET 2.0 (및 최신) 프레임 워크를 대상으로하는 경우에만 작동합니다.

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
}

최신 정보

많은 사람들이 Sam의 답변 이 더 간결 하다고 언급했기 때문에 답변 에 몇 가지 의견을 추가하기로 결정했습니다.

주목해야 할 가장 중요한 것은 내가 제공 한 코드 가 다음 코드 와 동일하지 않다는 것입니다 .

Dns.GetHostEntry("LocalHost").HostName

머신이 네트워크에 연결되고 도메인의 일부인 일반적인 경우에는 두 방법 모두 일반적으로 동일한 결과를 생성하지만 다른 시나리오에서는 결과가 다릅니다.

출력이 다른 시나리오는 시스템이 도메인의 일부가 아닌 경우입니다. 이 경우 Dns.GetHostEntry("LocalHost").HostName는 반환 localhost되고 GetFQDN()메서드는 호스트의 NETBIOS 이름을 반환합니다.

이 구분은 시스템 FQDN을 찾는 목적이 정보를 기록하거나 보고서를 생성하는 것일 때 중요합니다. 대부분의 경우이 방법을 로그 또는 보고서에서 사용하여 나중에 특정 컴퓨터에 정보를 매핑하는 데 사용했습니다. 머신이 네트워크에 연결되어 있지 않으면 localhost식별자는 쓸모가 없지만 이름은 필요한 정보를 제공합니다.

따라서 궁극적으로 필요한 결과에 따라 애플리케이션에 더 적합한 방법은 각 사용자에게 달려 있습니다. 그러나이 대답이 충분히 간결하지 않아 틀렸다고 말하는 것은 기껏해야 피상적입니다.

출력이 다른 예를 참조하십시오. http://ideone.com/q4S4I0


Miky D의 코드를 약간 단순화

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

이것은 이 문서에서 다룹니다 . 이 기술은 허용 된 답변보다 간단하며 다음으로 가장 많이 득표 한 답변보다 더 신뢰할 수 있습니다. 내가 아는 한 이것은 NetBIOS 이름을 사용 하지 않으므로 인터넷 사용에 적합해야합니다.

.NET 2.0 이상

Dns.GetHostEntry("LocalHost").HostName

.NET 1.0-1.1

Dns.GetHostByName("LocalHost").HostName

여기 PowerShell에 있습니다.

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

그리고 Framework 1.1의 경우 다음과 같이 간단합니다.

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

그런 다음 컴퓨터 NETBIOS 이름을 제거하여 domainName 만 검색합니다.


다음을 시도 할 수 있습니다.

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

이 소리는 현재 로컬 컴퓨터의 FQDN을 제공합니다 (또는 호스트를 지정할 수 있음).


A slight improvement on Matt Z's answer so that a trailing full stop isn't returned if the computer is not a member of a domain:

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

Used this as one of my options to combine host name and domain name for building a report, added the generic text to fill in when domain name was not captured, this was one of the customers requirements.

I tested this using 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
} 

Built using ideas from Miky Dinescu solution.


We have implemented suggested result to use this way:

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

However, turned out that this does not work right when computer name is longer than 15 characters and using NetBios name. The Environment.MachineName returns only partial name and resolving host name returns same computer name.

After some research we found a solution to fix this problem:

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

This resolved all problems including computer name.


If you want to tidy it up, and handle exceptions, try this:

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;
        }

참고URL : https://stackoverflow.com/questions/804700/how-to-find-fqdn-of-local-machine-in-c-net

반응형