【问题标题】:Get FQDN in C# running on Mono在 Mono 上运行的 C# 中获取 FQDN
【发布时间】:2013-06-14 17:56:21
【问题描述】:

我正在使用 Xamarin.mac。我需要获取本地计算机的完全限定域名。在 Windows 上,此代码有效:

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

那么,Xamarin.mac 中的等价物是什么?还是只在 Mono 中?

仅仅获得计算机名称将是一个好的开始。

【问题讨论】:

    标签: macos xamarin mono xamarin.mac


    【解决方案1】:

    为此,您几乎可以在 UNIX 系统上执行与 C 语言相同的操作,即使用 gethostname() 检索主机名,然后使用 DNS 查找来查找主机的规范网络名称.幸运的是,System.Net 对此有现成的调用。下面的代码应该可以在 OS X 和 Linux 上运行(事实上,在 Linux 上它或多或少是hostname --fqdn 所做的):

    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”。

    如果你想模仿你原来的方法,你可以使用下面的代码来检索域名:

    var domainname = new StringBuilder(256);
    Mono.Unix.Native.Syscall.getdomainname(domainname,
      (ulong) domainname.Capacity - 1);
    

    为此,您需要将 Mono.Posix 程序集添加到您的构建中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      相关资源
      最近更新 更多