Alex D
Alex D

Reputation: 739

Default DNS server in monotouch

I'm wondering how do I get default DNS server in monotouch?

this code works perfectly in simulator, but gives 0 records on device.

NetworkInterface.GetAllNetworkInterfaces();
foreach (IPAddress ipAddr in ipProps.DnsAddresses)
   Console.WriteLine(ipAddr);

from the other hand, this code works on both simulator and device:

IPHostEntry he = Dns.GetHostEntry(domain);
dns = he.HostName.ToString();

having all this, I assume DNS server address is stored somewhere. I mean it is accessible. How to get its IP?

Upvotes: 2

Views: 821

Answers (2)

Dave Brooks
Dave Brooks

Reputation: 66

This will get the IP Address in MonoTouch:-

    public string GetIPAddress()
    {
        string address = "Not Connected";
        try
        {
            #if SIM
                address = IPAddress.FileStyleUriParser("127.0.0.1"); 
            #else
                string str = Dns.GetHostName() + ".local";
                IPHostEntry hostEntry = Dns.GetHostEntry(str);
                address = (
                           from addr in hostEntry.AddressList
                           where addr.AddressFamily == AddressFamily.InterNetwork
                           select addr.ToString()
                           ).FirstOrDefault();
            #endif
        }
        catch (Exception ex)
        {
            // Add error handling....
        }
        return address;
    }

Note the difference between using the simulator and device.

Upvotes: 5

poupou
poupou

Reputation: 43553

I do not believe such an API exists on iOS (but I would be happy to be proven wrong). Other projects, that needs this information, relies on hacks like using well known, static address to DNS servers) to overcome this.

Now the reason code like this:

        var all = NetworkInterface.GetAllNetworkInterfaces ();
        foreach (NetworkInterface ni in all) {
            var props = ni.GetIPProperties ();
            foreach (var dns in props.DnsAddresses) {
                Console.WriteLine (dns);
            }
        }

works on the simulator is because it's a simulator and not an emulator. IOW the host (Mac) computer allows far more things than a real iOS device will allow.

More precisely props will be an instance of System.Net.NetworkInformation.MacOsIPInterfaceProperties, which inherits from UnixIPInterfaceProperties, and ends up reading the /etc/resolv.conf file (which iOS disallow your application from reading).

The second case, calling Dns.GetHostEntry, goes down into the Mono runtime but end up calling gethostname which does not require the caller to know the DNS server address.

Upvotes: 0

Related Questions