Pergunta

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.

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top