How do you get the current DNS servers for Android?

后端 未结 8 791
孤街浪徒
孤街浪徒 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:48

    Following works for API 21 and above. It returns correct dns servers for both WiFi and Cellular interfaces. I've verified the values returned with shell utility 'getprop'

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        for (Network network : connectivityManager.getAllNetworks()) {
            NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
            if (networkInfo.isConnected()) {
                LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
                Log.d("DnsInfo", "iface = " + linkProperties.getInterfaceName());
                Log.d("DnsInfo", "dns = " + linkProperties.getDnsServers());
                return linkProperties.getDnsServers();
            }
        }
    

提交回复
热议问题