How do I find the DNS servers in Android from a Java program?

Tags: dns android java
By : Alnitak

The host) method can only return A records so to lookup other record types I need to be able to send DNS queries using the dnsjava library.

However that normally relies on being able to parse /etc/resolv.conf or similar to find the DNS server addresses and that doesn't work on Android.

The current DNS settings on Android can apparently only be obtained from within a shell by using the getprop command.

Can anyone tell me how to get those settings from Java other than by spawning a shell with Runtime.exec() and parsing the output from getprop?

By : Alnitak


The DNS protocol is not that complex - can't you just do the DNS accesses using raw sockets (either TCP or UDP)? After a quick look at the dnsjava doco it seems to provide low level DNS support to assist with this.

The other possible direction is, starting with dnsjava, to remove the dependence on /etc/resolv.conf. I would think about using getprop in your launch script to set properties in the JVM, or to create a localized resolv.conf file in your app's directory from which you can read the information needed. In other words, use getprop to inject information into the JVM instead of attempting to pull it in once the JVM is going. Surely creating a file that dnsjava can use directly should be doable.

Edit -

It looks like will deliver you an array of NetworkInfo's using getAllNetworkInfo(). Then use to get a DhcpInfo for any given network interface - the DhcpInfo structure has the IP address for dns1 and dns2 for that interface. Surprised that the DNS's are int, therefore implying IP4 only, though.

To get system properties of an android system, static methods in this class (android.os.SystemProperties) can be used. As it is not an open api, you can't compile it against the sdk. Work around is needed to do that, e.g. copy the code from AOSP to get thru the compilation. As this class is for internal use, do this at your own risk. Have fun.

By : accuya

I don't think it's possible for general case. For WiFi I found this:

WiFiManager wifi = (WifiManager) getSystemService(WIFI_SERVICE); 
DhcpInfo info = wifi.getDhcpInfo();

This video can help you solving your question :)
By: admin