Android DNS 獲取


得到Android 客戶端的DNS信息

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

 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等一些網絡信息。

 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竟然有值,實在不解。

方法1在4G/wifi都關閉后,依然可以得到dns信息,表現比較靠譜,推薦使用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM