• 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信息,表现比较靠谱,推荐使用。

  • 相关阅读:
    python socket练习
    python异常处理
    python类的反射
    类的特殊成员方法
    staticmethod classmethod property方法
    类的多态
    类的析构、继承
    python subprocess模块
    python面向对象
    discuz 使模板中的函数不解析 正常使用
  • 原文地址:https://www.cnblogs.com/alex-zhao/p/5254624.html
Copyright © 2020-2023  润新知