在Mono上运行的C#中获取FQDN [英] Get FQDN in C# running on Mono
问题描述
我正在使用Xamarin.mac.我需要获取本地计算机的标准域名.在Windows上,此代码有效:
I'm using Xamarin.mac. I need to get the fully qualified domain name of the local computer. On Windows this code works:
public string GetFQDN()
{
string domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
string hostName = Dns.GetHostName();
string fqdn = "";
if (!hostName.Contains(domainName))
fqdn = hostName + "." + domainName;
else
fqdn = hostName;
return fqdn;
}
在Mac上,此代码会导致以下错误: System.NotSupportedException: This platform is not supported
.
On a mac this code causes this error: System.NotSupportedException: This platform is not supported
.
那么,Xamarin.mac中的等效项是什么?还是只在Mono中?
So, what is the equivalent in Xamarin.mac? Or just in Mono?
仅获取计算机名称将是一个好的开始.
Just getting the computer name would be a good start.
推荐答案
要做到这一点,您几乎可以像在UNIX系统上的C语言中一样进行操作,即使用gethostname()
和然后使用DNS查找来查找主机的规范网络名称.幸运的是,System.Net已经为此提供了现成的调用.以下代码在OS X和Linux上均应正常工作(实际上,在Linux上,它或多或少是hostname --fqdn
的作用):
To do this, you can pretty much do the same you'd do in C on a UNIX system, which is to retrieve the hostname with gethostname()
and then use a DNS lookup to find the canonical network name for the host. Luckily, System.Net has ready-made calls for this. The following code should work on both OS X and Linux (in fact, on Linux it is more or less what hostname --fqdn
does):
using System;
using System.Net;
class Program {
static void Main() {
// Step 1: Get the host name
var hostname = Dns.GetHostName();
// Step 2: Perform a DNS lookup.
// Note that the lookup is not guaranteed to succeed, especially
// if the system is misconfigured. On the other hand, if that
// happens, you probably can't connect to the host by name, anyway.
var hostinfo = Dns.GetHostEntry(hostname);
// Step 3: Retrieve the canonical name.
var fqdn = hostinfo.HostName;
Console.WriteLine("FQDN: {0}", fqdn);
}
}
请注意,如果DNS配置错误,则DNS查找可能会失败,或者您可能会获得无用的"localhost.localdomain".
Note that with a misconfigured DNS, the DNS lookup may fail, or you may get the rather useless "localhost.localdomain".
如果您想模仿原始方法,则可以使用以下代码来检索域名:
If you wish to emulate your original approach, you can use the following code to retrieve the domainname:
var domainname = new StringBuilder(256);
Mono.Unix.Native.Syscall.getdomainname(domainname,
(ulong) domainname.Capacity - 1);
为此,您需要将Mono.Posix
程序集添加到您的构建中.
You will need to add the Mono.Posix
assembly to your build for this.
这篇关于在Mono上运行的C#中获取FQDN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!