DnsServersDetector.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 |
import android.annotation.TargetApi; import android.content.Context; import android.net.ConnectivityManager; import android.net.LinkProperties; import android.net.Network; import android.net.NetworkInfo; import android.net.RouteInfo; import android.os.Build; import android.util.Log; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.lang.reflect.Method; import java.net.InetAddress; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * DNS servers detector * <p> * IMPORTANT: don't cache the result. * <p> * Or if you want to cache the result make sure you invalidate the cache * on any network change. * <p> * It is always better to use a new instance of the detector when you need * current DNS servers otherwise you may get into troubles because of invalid/changed * DNS servers. * <p> * This class combines various methods and solutions from: * Dnsjava http://www.xbill.org/dnsjava/ * Minidns https://github.com/MiniDNS/minidns * <p> * Unfortunately both libraries are not aware of Orero changes so new method was added to fix this. * <p> * Created by Madalin Grigore-Enescu on 2/24/18. */ public class DnsServersDetector { private static final String TAG = "DnsServersDetector"; /** * Holds some default DNS servers used in case all DNS servers detection methods fail. * Can be set to null if you want caller to fail in this situation. */ private static final String[] FACTORY_DNS_SERVERS = { "8.8.8.8", "8.8.4.4" }; /** * Properties delimiter used in exec method of DNS servers detection */ private static final String METHOD_EXEC_PROP_DELIM = "]: ["; /** * Holds context this was created under */ private Context context; //region - public ////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// /** * Constructor */ public DnsServersDetector(Context context) { this.context = context; } /** * Returns android DNS servers used for current connected network * * @return Dns servers array */ public String[] getServers() { // METHOD 1: old deprecated system properties String[] result = getServersMethodSystemProperties(); if (result != null && result.length > 0) { return result; } // METHOD 2 - use connectivity manager result = getServersMethodConnectivityManager(); if (result != null && result.length > 0) { return result; } // LAST METHOD: detect android DNS servers by executing getprop string command in a separate process // This method fortunately works in Oreo too but many people may want to avoid exec // so it's used only as a failsafe scenario result = getServersMethodExec(); if (result != null && result.length > 0) { return result; } // Fall back on factory DNS servers return FACTORY_DNS_SERVERS; } //endregion //region - private ///////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// /** * Detect android DNS servers by using connectivity manager * <p> * This method is working in android LOLLIPOP or later * * @return Dns servers array */ private String[] getServersMethodConnectivityManager() { // This code only works on LOLLIPOP and higher if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { try { final ArrayList<String> priorityServersArrayList = new ArrayList<>(); final ArrayList<String> serversArrayList = new ArrayList<>(); final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(android.content.Context.CONNECTIVITY_SERVICE); if (connectivityManager != null) { // Iterate all networks // Notice that android LOLLIPOP or higher allow iterating multiple connected networks of SAME type for (Network network : connectivityManager.getAllNetworks()) { final NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network); if (networkInfo.isConnected()) { final LinkProperties linkProperties = connectivityManager.getLinkProperties(network); final List<InetAddress> dnsServersList = linkProperties.getDnsServers(); // Prioritize the DNS servers for link which have a default route if (linkPropertiesHasDefaultRoute(linkProperties)) { for (InetAddress element : dnsServersList) { final String dnsHost = element.getHostAddress(); priorityServersArrayList.add(dnsHost); } } else { for (InetAddress element : dnsServersList) { final String dnsHost = element.getHostAddress(); serversArrayList.add(dnsHost); } } } } } // Append secondary arrays only if priority is empty if (priorityServersArrayList.isEmpty()) { priorityServersArrayList.addAll(serversArrayList); } // Stop here if we have at least one DNS server if (priorityServersArrayList.size() > 0) { return priorityServersArrayList.toArray(new String[0]); } } catch (Exception ex) { Log.d(TAG, "Exception detecting DNS servers using ConnectivityManager method", ex); } } // Failure return null; } /** * Detect android DNS servers by using old deprecated system properties * <p> * This method is NOT working anymore in Android 8.0 * Official Android documentation state this in the article Android 8.0 Behavior Changes. * The system properties net.dns1, net.dns2, net.dns3, and net.dns4 are no longer available, * a change that improves privacy on the platform. * <p> * https://developer.android.com/about/versions/oreo/android-8.0-changes.html#o-pri * * @return Dns servers array */ private String[] getServersMethodSystemProperties() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { // 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. final String re1 = "^\\d+(\\.\\d+){3}$"; final String re2 = "^[0-9a-f]+(:[0-9a-f]*)+:[0-9a-f]+$"; ArrayList<String> serversArrayList = new ArrayList<>(); try { Class<?> SystemProperties = Class.forName("android.os.SystemProperties"); Method method = SystemProperties.getMethod("get", new Class[]{String.class}); final String[] netdns = new String[]{"net.dns1", "net.dns2", "net.dns3", "net.dns4"}; for (String netdn : netdns) { Object[] args = new Object[]{netdn}; String v = (String) method.invoke(null, args); if (v != null && (v.matches(re1) || v.matches(re2)) && !serversArrayList.contains(v)) { serversArrayList.add(v); } } // Stop here if we have at least one DNS server if (serversArrayList.size() > 0) { return serversArrayList.toArray(new String[0]); } } catch (Exception e) { Log.d(TAG, "Exception detecting DNS servers using SystemProperties method", e); } } // Failed return null; } /** * Detect android DNS servers by executing getprop string command in a separate process * <p> * Notice there is an android bug when Runtime.exec() hangs without providing a Process object. * This problem is fixed in Jelly Bean (Android 4.1) but not in ICS (4.0.4) and probably it will never be fixed in ICS. * https://stackoverflow.com/questions/8688382/runtime-exec-bug-hangs-without-providing-a-process-object/11362081 * * @return Dns servers array */ private String[] getServersMethodExec() { // We are on the safe side and avoid any bug if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { try { Process process = Runtime.getRuntime().exec("getprop"); InputStream inputStream = process.getInputStream(); LineNumberReader lineNumberReader = new LineNumberReader(new InputStreamReader(inputStream)); Set<String> serversSet = methodExecParseProps(lineNumberReader); if (serversSet != null && serversSet.size() > 0) { return serversSet.toArray(new String[0]); } } catch (Exception e) { Log.d(TAG, "Exception in getServersMethodExec", e); } } // Failed return null; } /** * Parse properties produced by executing getprop command * * @param lineNumberReader lineNumberReader * @return Set of parsed properties * @throws Exception Exception */ private Set<String> methodExecParseProps(BufferedReader lineNumberReader) throws Exception { String line; Set<String> serversSet = new HashSet<String>(10); while ((line = lineNumberReader.readLine()) != null) { int split = line.indexOf(METHOD_EXEC_PROP_DELIM); if (split == -1) { continue; } String property = line.substring(1, split); int valueStart = split + METHOD_EXEC_PROP_DELIM.length(); int valueEnd = line.length() - 1; if (valueEnd < valueStart) { // This can happen if a newline sneaks in as the first character of the property value. For example // "[propName]: [\n…]". Log.d(TAG, "Malformed property detected: \"" + line + '"'); continue; } String value = line.substring(valueStart, valueEnd); if (value.isEmpty()) { continue; } if (property.endsWith(".dns") || property.endsWith(".dns1") || property.endsWith(".dns2") || property.endsWith(".dns3") || property.endsWith(".dns4")) { // normalize the address InetAddress ip = InetAddress.getByName(value); if (ip == null) continue; value = ip.getHostAddress(); if (value == null) continue; if (value.length() == 0) continue; serversSet.add(value); } } return serversSet; } /** * Returns true if the specified link properties have any default route * * @param linkProperties linkProperties * @return true if the specified link properties have default route or false otherwise */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) private boolean linkPropertiesHasDefaultRoute(LinkProperties linkProperties) { for (RouteInfo route : linkProperties.getRoutes()) { if (route.isDefaultRoute()) { return true; } } return false; } //endregion } |