如何在 C# 中找到我机器的完全限定主机名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/541635/
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
How do I find the fully qualified hostname of my machine in C#?
提问by user21246
Ex : I want something like abc.hyd.mycompany.com. My requirement is to parse this name and initialize appropriate service.
例如:我想要像 abc.hyd.mycompany.com 这样的东西。我的要求是解析这个名称并初始化相应的服务。
using System.Net;
Dns.GetHostName() // doesn't return fully qualified name it just gives "abc"
采纳答案by Powerlord
You may be able to get the whole DNS string like this:
您可以像这样获取整个 DNS 字符串:
System.Net.Dns.GetHostEntry("").HostName
We don't have full fledged DNS names where I work, but it does give me a three level faux domain name instead of just the hostname.
我们在我工作的地方没有成熟的 DNS 名称,但它确实给了我一个三级假域名,而不仅仅是主机名。
Edit 2011/03/17: Incorporated changes suggested by mark below.
编辑 2011/03/17:合并以下标记建议的更改。
回答by Powerlord
If the above doesn't work, you can also try retrieving it from the environment:
如果上述方法不起作用,您还可以尝试从环境中检索它:
var dnsName = new StringBuilder();
dnsName.Append(Environment.GetEnvironmentVariable("COMPUTERNAME")).Append(".");
dnsName.Append(Environment.GetEnvironmentVariable("USERDNSDOMAIN"));
回答by popofef
I used this very similar method:
我使用了这个非常相似的方法:
var serverName = System.Environment.MachineName; //host name sans domain
var fqhn = System.Net.Dns.GetHostEntry(serverName).HostName; //fully qualified hostname