001/*
002 * Copyright 2015-2020 the original author or authors
003 *
004 * This software is licensed under the Apache License, Version 2.0,
005 * the GNU Lesser General Public License version 2 or later ("LGPL")
006 * and the WTFPL.
007 * You may choose either license to govern your use of this software only
008 * upon the condition that you accept all of the terms of either
009 * the Apache License 2.0, the LGPL 2.1+ or the WTFPL.
010 */
011package org.minidns.dnsserverlookup;
012
013import org.minidns.util.PlatformDetection;
014
015import java.lang.reflect.Method;
016import java.net.InetAddress;
017import java.util.ArrayList;
018import java.util.List;
019import java.util.logging.Level;
020
021/**
022 * Try to retrieve the list of DNS server by calling SystemProperties.
023 */
024public class AndroidUsingReflection extends AbstractDnsServerLookupMechanism {
025
026    public static final DnsServerLookupMechanism INSTANCE = new AndroidUsingReflection();
027    public static final int PRIORITY = 1000;
028
029    protected AndroidUsingReflection() {
030        super(AndroidUsingReflection.class.getSimpleName(), PRIORITY);
031    }
032
033    @Override
034    public List<String> getDnsServerAddresses() {
035        try {
036            Class<?> SystemProperties =
037                    Class.forName("android.os.SystemProperties");
038            Method method = SystemProperties.getMethod("get",
039                    new Class<?>[] { String.class });
040
041            ArrayList<String> servers = new ArrayList<String>(5);
042
043            for (String propKey : new String[] {
044                    "net.dns1", "net.dns2", "net.dns3", "net.dns4"}) {
045
046                String value = (String) method.invoke(null, propKey);
047
048                if (value == null) continue;
049                if (value.length() == 0) continue;
050                if (servers.contains(value)) continue;
051
052                InetAddress ip = InetAddress.getByName(value);
053
054                if (ip == null) continue;
055
056                value = ip.getHostAddress();
057
058                if (value == null) continue;
059                if (value.length() == 0) continue;
060                if (servers.contains(value)) continue;
061
062                servers.add(value);
063            }
064
065            if (servers.size() > 0) {
066                return servers;
067            }
068        } catch (Exception e) {
069            // we might trigger some problems this way
070            LOGGER.log(Level.WARNING, "Exception in findDNSByReflection", e);
071        }
072        return null;
073    }
074
075    @Override
076    public boolean isAvailable() {
077        return PlatformDetection.isAndroid();
078    }
079
080}