code 参考:https://www.cnblogs.com/alex-zhao/p/5254624.html
/** * 获取DNS,优先返回本地网络DNS(插网线),其次选择Wifi网络的DNS * */ public static String getLocalDNS(Context context) { String TAG = "WiFiUtil_getLocalDNS"; Process cmdProcess = null; BufferedReader reader = null; String dnsIP = ""; try { cmdProcess = Runtime.getRuntime().exec("getprop net.dns1"); reader = new BufferedReader(new InputStreamReader(cmdProcess.getInputStream())); dnsIP = reader.readLine(); } catch (Exception ex) { slog.e(TAG, "获取Local网络DNS异常", ex); return null; } finally { try { reader.close(); } catch (IOException ex) { slog.e(TAG, "获取Local网络DNS,关闭BufferedReader异常", ex); } cmdProcess.destroy(); } if (Func.IsNullOrEmpty(dnsIP)) { try { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wifiManager != null) { // 获取WIFI的DHCP数据 DhcpInfo dhcpInfo = wifiManager.getDhcpInfo(); if (dhcpInfo != null) { String dns1 = intToIp(dhcpInfo.dns1); String dns2 = intToIp(dhcpInfo.dns2); String dnsDef = "0.0.0.0"; if (dnsDef.equals(dns1)) { dns1 = ""; } if (dnsDef.equals(dns2)) { dns2 = ""; } if (!Func.IsNullOrEmpty(dns1) && !Func.IsNullOrEmpty(dns2)) { dnsIP = dns1 + ";" + dns2; } else { dnsIP = dns1 + dns2; } } } } catch (Exception ex) { slog.e(TAG, "获取Wifi网络DNS异常", ex); } } return dnsIP; }
标签:String,dns2,dns1,Wifi,ex,DNS,dnsIP,本地网络 From: https://www.cnblogs.com/xsj1989/p/17649000.html