Android DNS 獲取

獲得Android 客戶端的DNS信息網絡

方法1,運行command獲得DNS,(getprop net.dns1/getprop net.dns2)ide

 1     private String getLocalDNS(){
 2         Process cmdProcess = null;
 3         BufferedReader reader = null;
 4         String dnsIP = "";
 5         try {
 6             cmdProcess = Runtime.getRuntime().exec("getprop net.dns1");
 7             reader = new BufferedReader(new InputStreamReader(cmdProcess.getInputStream()));
 8             dnsIP = reader.readLine();
 9             return dnsIP;
10         } catch (IOException e) {
11             return null;
12         } finally{
13             try {
14                 reader.close();
15             } catch (IOException e) {
16             }
17             cmdProcess.destroy();
18         }
19     }
View Code

方法2,獲得WiFiManager,WiFiManager中能夠獲得wifi的dns,ip等一些網絡信息。spa

 1     public static Map<String,String> getWifiNetInfo(Context context){
 2         Map<String,String> wifiInfo = new HashMap<>();
 3         WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
 4         if(wifi  != null){
 5             DhcpInfo info = wifi.getDhcpInfo();
 6             wifiInfo.put("wifi-dns", intToIp(info.dns1) + ";" + intToIp(info.dns2));
 7             wifiInfo.put("wifi-gateway", intToIp(info.gateway));
 8             wifiInfo.put("wifi-ip", intToIp(info.ipAddress));
 9             wifiInfo.put("wifi-netmask", intToIp(info.netmask));
10             wifiInfo.put("wifi-leaseTime", String.valueOf(info.leaseDuration));
11             wifiInfo.put("wifi-dhcpServer", intToIp(info.serverAddress));
12         }
13         return wifiInfo;
14     }
15 
16     public static String intToIp(int addr) {
17         return  ((addr & 0xFF) + "." +
18                 ((addr >>>= 8) & 0xFF) + "." +
19                 ((addr >>>= 8) & 0xFF) + "." +
20                 ((addr >>>= 8) & 0xFF));
21     }
View Code

 

在Android5.1上實驗了方法1和方法2,方法2在手機wifi關閉後,dns,gateway,ip,netmask,leaseTime都得不到了,神奇的是dhcpServer居然有值,實在不解。.net

方法1在4G/wifi都關閉後,依然能夠獲得dns信息,表現比較靠譜,推薦使用。code

相關文章
相關標籤/搜索