如何找到本地计算机的FQDN在C#/。NET? [英] How to find FQDN of local machine in C#/.NET ?

查看:727
本文介绍了如何找到本地计算机的FQDN在C#/。NET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你怎么能得到本地计算机的FQDN在C#?

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

推荐答案

注:此解决方案只针对.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
}

更新

由于有很多人评论说,萨姆的回答是更简洁,我决定加入到一些意见的回答。

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

要注意的最重要的事情是,code我给的不等于以下code:

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.

在输出会有所不同情景是当机器是不是域的一部分。在这种情况下, Dns.GetHostEntry(localhost的)。主机名将返回本地主机,而<$ C $上述C> GetFQDN()方法将返回主机的NETBIOS名称。

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.

这区别是重要的,当发现机器的目的FQDN是登录信息,或生成报告。大多数时候,我用在日志或报告这个方法随后被用来映射信息返回到特定的机器。如果机器没有联网,在本地主机标识符是没用的,而名字给人所需的信息。

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.

看到一个例子,其中,输出会有所不同: http://ideone.com/q4S4I0

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

这篇关于如何找到本地计算机的FQDN在C#/。NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆