如何在 C#/.NET 中找到本地机器的 FQDN?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/804700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:52:25  来源:igfitidea点击:

How to find FQDN of local machine in C#/.NET ?

c#localhostfqdn

提问by

How can you get the FQDN of a local machine in C#?

如何在 C# 中获取本地机器的 FQDN?

采纳答案by Mike Dinescu

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

注意:此解决方案仅在面向 .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
}

UPDATE

更新

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

由于很多人评论说Sam 的答案更简洁,因此我决定在答案中添加一些评论。

The most important thing to note is that the code I gave is not equivalentto 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").HostNamewill return localhostwhile the GetFQDN()method above will return the NETBIOS name of the host.

当机器不属于域时,输出会有所不同的一种情况。在这种情况下,Dns.GetHostEntry("LocalHost").HostName将返回localhost而上述GetFQDN()方法将返回主机的 NETBIOS 名称。

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 localhostidentifier is useless, whereas the name gives the needed information.

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

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

查看输出不同的示例:http: //ideone.com/q4S4I0

回答by Matt Z

A slight simplification of Miky D's code

Miky D 的代码略有简化

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

回答by halr9000

Here it is in PowerShell, for the heck of it:

这是在 PowerShell 中的,因为它很重要:

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

回答by javizcaino

And for Framework 1.1 is as simple as this:

而对于 Framework 1.1 来说就这么简单:

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

And then remove the machine NETBIOS name to retrieve only the domainName

然后删除机器NETBIOS名称以仅检索domainName

回答by Roger Willcocks

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

回答by Bosco

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:

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

回答by Sam

This is covered by this article. This technique is more brief than the accepted answer and probably more reliable than the next most-voted answer. Note that as far as I understand, this doesn'tuse NetBIOS names, so it should be suitable for Internet use.

这是本文所涵盖的。这种技术比公认的答案更简短,并且可能比下一个投票最多的答案更可靠。请注意,据我所知,这使用 NetBIOS 名称,因此它应该适合 Internet 使用。

.NET 2.0+

.NET 2.0+

Dns.GetHostEntry("LocalHost").HostName

.NET 1.0 - 1.1

.NET 1.0 - 1.1

Dns.GetHostByName("LocalHost").HostName

回答by UT-Fan-05

You can try the following:

您可以尝试以下操作:

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

This shoud give you the FQDN of the current local machine (or you can specify any host).

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

回答by user3500031

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

我使用 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.

使用 Miky Dinescu 解决方案的想法构建。

回答by btomas

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.

但是,事实证明,当计算机名称超过 15 个字符并使用 NetBios 名称时,这不起作用。Environment.MachineName 仅返回部分名称,解析主机名返回相同的计算机名称。

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.

这解决了所有问题,包括计算机名称。