How do you get the current DNS servers for Android?

后端 未结 8 789
孤街浪徒
孤街浪徒 2020-11-30 03:01

I\'m trying to get hold of the addresses to the currently used DNS servers in my application, either I\'m connected thru Wifi or mobile. The DhcpInfo object should provide t

相关标签:
8条回答
  • 2020-11-30 03:55

    Calling for the getRuntime().exec can hang your application.

    android.net.NetworkUtils.runDhcp() cause unnecessary network requests.

    So I prefer to do this:

    Class<?> SystemProperties = Class.forName("android.os.SystemProperties");
    Method method = SystemProperties.getMethod("get", new Class[] { String.class });
    ArrayList<String> servers = new ArrayList<String>();
    for (String name : new String[] { "net.dns1", "net.dns2", "net.dns3", "net.dns4", }) {
        String value = (String) method.invoke(null, name);
        if (value != null && !"".equals(value) && !servers.contains(value))
            servers.add(value);
    }
    
    0 讨论(0)
  • 2020-11-30 03:56

    android.net.ConnectivityManager will deliver you an array of NetworkInfo's using getAllNetworkInfo(). Then use android.net.NetworkUtils.runDhcp() to get a DhcpInfo for any given network interface - the DhcpInfo structure has the IP address for dns1 and dns2 for that interface (which are integer values representing the IP address).

    In case you are wondering how the hell you are going to transform the integer into an IP address, you can do this:

    /**
    * Convert int IP adress to String 
    * cf. http://teneo.wordpress.com/2008/12/23/java-ip-address-to-integer-and-back/
    */
    private String intToIp(int i) {
        return ( i & 0xFF) + "." +
            (( i >> 8 ) & 0xFF) + "." +
            (( i >> 16 ) & 0xFF) + "." +
            (( i >> 24 ) & 0xFF);
    }
    

    Edit

    You can also get a DchcpInfo object by doing something like this:

    WiFiManager wifi = (WifiManager) getSystemService(WIFI_SERVICE); 
    DhcpInfo info = wifi.getDhcpInfo();
    
    0 讨论(0)
提交回复
热议问题