How do you get the current DNS servers for Android?

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

    I recommend dnsjava for complex DNS use on Android. Let's see how dnsjava determines the current active DNS server for the connection. From dnsjava ResolverConfig.java:428:

    /**
     * Parses the output of getprop, which is the only way to get DNS
     * info on Android. getprop might disappear in future releases, so
     * this code comes with a use-by date.
     */
    private void
    findAndroid() {
        // This originally looked for all lines containing .dns; but
        // http://code.google.com/p/android/issues/detail?id=2207#c73
        // indicates that net.dns* should always be the active nameservers, so
        // we use those.
        String re1 = "^\\d+(\\.\\d+){3}$";
        String re2 = "^[0-9a-f]+(:[0-9a-f]*)+:[0-9a-f]+$";
        try { 
            ArrayList lserver = new ArrayList(); 
            ArrayList lsearch = new ArrayList(); 
            String line; 
            Process p = Runtime.getRuntime().exec("getprop"); 
            InputStream in = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(in);
            BufferedReader br = new BufferedReader(isr);
            while ((line = br.readLine()) != null ) { 
                StringTokenizer t = new StringTokenizer(line, ":");
                String name = t.nextToken();
                if (name.indexOf( "net.dns" ) > -1) {
                    String v = t.nextToken();
                    v = v.replaceAll("[ \\[\\]]", "");
                    if ((v.matches(re1) || v.matches(re2)) &&
                        !lserver.contains(v))
                        lserver.add(v);
                }
            }
            configureFromLists(lserver, lsearch);
        } catch ( Exception e ) { 
            // ignore resolutely
        }
    }
    

提交回复
热议问题