你如何为Android当前的DNS服务器?何为、服务器、Android、DNS

2023-09-13 00:06:36 作者:指尖下的忧伤

我想弄个地址当前使用的DNS服务器,在我的应用程序,无论是我连接直通Wifi或移动。 该DhcpInfo对象应该提供这一点,但我要如何才能找到一个有效的DhcpInfo对象?

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 this but how can I get hold of a valid DhcpInfo object?

推荐答案

呼唤 getRuntime()。EXEC 能挂您的应用程序。

android.net.NetworkUtils.runDhcp()造成不必要的网络请求。

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

所以我preFER做到这一点:

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);
}