Get FQDN in C# running on Mono

依然范特西╮ 提交于 2019-12-25 01:55:33

问题


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

On a mac this code causes this error: System.NotSupportedException: This platform is not supported.

So, what is the equivalent in Xamarin.mac? Or just in Mono?

Just getting the computer name would be a good start.


回答1:


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

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

You will need to add the Mono.Posix assembly to your build for this.



来源:https://stackoverflow.com/questions/17114536/get-fqdn-in-c-sharp-running-on-mono

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!