Java Code Examples for android.net.LinkProperties#getDnsServers()

The following examples show how to use android.net.LinkProperties#getDnsServers() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Tethering.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
protected void setDnsForwarders(final Network network, final LinkProperties lp) {
    // TODO: Set v4 and/or v6 DNS per available connectivity.
    String[] dnsServers = mConfig.defaultIPv4DNS;
    final Collection<InetAddress> dnses = lp.getDnsServers();
    // TODO: Properly support the absence of DNS servers.
    if (dnses != null && !dnses.isEmpty()) {
        // TODO: remove this invocation of NetworkUtils.makeStrings().
        dnsServers = NetworkUtils.makeStrings(dnses);
    }
    try {
        mNMService.setDnsForwarders(network, dnsServers);
        mLog.log(String.format(
                "SET DNS forwarders: network=%s dnsServers=%s",
                network, Arrays.toString(dnsServers)));
    } catch (Exception e) {
        // TODO: Investigate how this can fail and what exactly
        // happens if/when such failures occur.
        mLog.e("setting DNS forwarders failed, " + e);
        transitionTo(mSetDnsForwardersErrorState);
    }
}
 
Example 2
Source File: Dns.java    From HttpInfo with Apache License 2.0 6 votes vote down vote up
private static String[] readDnsServersFromConnectionManager(Context context) {
    LinkedList<String> dnsServers = new LinkedList<>();
    if (Build.VERSION.SDK_INT >= 21 && context != null) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            for (Network network : connectivityManager.getAllNetworks()) {
                NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
                if (networkInfo.getType() == activeNetworkInfo.getType()) {
                    LinkProperties lp = connectivityManager.getLinkProperties(network);
                    for (InetAddress addr : lp.getDnsServers()) {
                        dnsServers.add(addr.getHostAddress());
                    }
                }
            }
        }
    }
    return dnsServers.isEmpty() ? new String[0] : dnsServers.toArray(new String[dnsServers.size()]);
}
 
Example 3
Source File: DNSFilterService.java    From personaldnsfilter with GNU General Public License v2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static String[] getDNSviaConnectivityManager() {

	if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
		return new String[0];

	HashSet<String> result = new HashSet<String>();
	ConnectivityManager connectivityManager = (ConnectivityManager) INSTANCE.getSystemService(CONNECTIVITY_SERVICE);
	Network[] networks = getConnectedNetworks(connectivityManager, ConnectivityManager.TYPE_WIFI); //prefer WiFi
	if (networks.length == 0)
		networks = getConnectedNetworks(connectivityManager, -1); //fallback all networks
	for (Network network : networks) {
		NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);

		LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
		List<InetAddress> dnsList = linkProperties.getDnsServers();
		for (int i = 0; i < dnsList.size(); i++)
			result.add(dnsList.get(i).getHostAddress());

	}
	return result.toArray(new String[result.size()]);
}
 
Example 4
Source File: MainActivity.java    From Intra with Apache License 2.0 6 votes vote down vote up
private String getSystemDnsServer() {
  if (Build.VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) {
    // getDnsServers requires Lollipop or later.
    return null;
  }
  LinkProperties linkProperties = getLinkProperties();
  if (linkProperties == null) {
    return null;
  }
  if (VERSION.SDK_INT >= VERSION_CODES.P) {
    String privateDnsServerName = linkProperties.getPrivateDnsServerName();
    if (privateDnsServerName != null) {
      return privateDnsServerName;
    }
  }
  for (InetAddress address : linkProperties.getDnsServers()) {
    // Show the first DNS server on the list.
    return address.getHostAddress();
  }
  return null;
}
 
Example 5
Source File: AndroidNetworkLibrary.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
@CalledByNative
private static byte[][] getDnsServers() {
    ConnectivityManager connectivityManager =
            (ConnectivityManager) ContextUtils.getApplicationContext().getSystemService(
                    Context.CONNECTIVITY_SERVICE);
    if (connectivityManager == null) {
        return new byte[0][0];
    }
    Network network = connectivityManager.getActiveNetwork();
    if (network == null) {
        return new byte[0][0];
    }
    LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
    if (linkProperties == null) {
        return new byte[0][0];
    }
    List<InetAddress> dnsServersList = linkProperties.getDnsServers();
    byte[][] dnsServers = new byte[dnsServersList.size()][];
    for (int i = 0; i < dnsServersList.size(); i++) {
        dnsServers[i] = dnsServersList.get(i).getAddress();
    }
    return dnsServers;
}
 
Example 6
Source File: AndroidResolverConfigProvider.java    From dnsjava with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void initializeApi26Nameservers() throws InitializationException {
  if (context == null) {
    throw new InitializationException("Context must be initialized by calling setContext");
  }

  ConnectivityManager cm = context.getSystemService(ConnectivityManager.class);
  Network network = cm.getActiveNetwork();
  if (network == null) {
    // if the device is offline, there's no active network
    return;
  }

  LinkProperties lp = cm.getLinkProperties(network);
  if (lp == null) {
    // can be null for an unknown network, which may happen if networks change
    return;
  }

  for (InetAddress address : lp.getDnsServers()) {
    addNameserver(new InetSocketAddress(address, SimpleResolver.DEFAULT_PORT));
  }

  parseSearchPathList(lp.getDomains(), ",");
}
 
Example 7
Source File: IPv6TetheringCoordinator.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static LinkProperties getIPv6OnlyLinkProperties(LinkProperties lp) {
    final LinkProperties v6only = new LinkProperties();
    if (lp == null) {
        return v6only;
    }

    // NOTE: At this time we don't copy over any information about any
    // stacked links. No current stacked link configuration has IPv6.

    v6only.setInterfaceName(lp.getInterfaceName());

    v6only.setMtu(lp.getMtu());

    for (LinkAddress linkAddr : lp.getLinkAddresses()) {
        if (linkAddr.isGlobalPreferred() && linkAddr.getPrefixLength() == 64) {
            v6only.addLinkAddress(linkAddr);
        }
    }

    for (RouteInfo routeInfo : lp.getRoutes()) {
        final IpPrefix destination = routeInfo.getDestination();
        if ((destination.getAddress() instanceof Inet6Address) &&
            (destination.getPrefixLength() <= 64)) {
            v6only.addRoute(routeInfo);
        }
    }

    for (InetAddress dnsServer : lp.getDnsServers()) {
        if (isIPv6GlobalAddress(dnsServer)) {
            // For now we include ULAs.
            v6only.addDnsServer(dnsServer);
        }
    }

    v6only.setDomains(lp.getDomains());

    return v6only;
}
 
Example 8
Source File: Util.java    From tracker-control-android with GNU General Public License v3.0 5 votes vote down vote up
public static List<String> getDefaultDNS(Context context) {
    List<String> listDns = new ArrayList<>();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        Network an = cm.getActiveNetwork();
        if (an != null) {
            LinkProperties lp = cm.getLinkProperties(an);
            if (lp != null) {
                List<InetAddress> dns = lp.getDnsServers();
                if (dns != null)
                    for (InetAddress d : dns) {
                        Log.i(TAG, "DNS from LP: " + d.getHostAddress());
                        listDns.add(d.getHostAddress().split("%")[0]);
                    }
            }
        }
    } else {
        String dns1 = jni_getprop("net.dns1");
        String dns2 = jni_getprop("net.dns2");
        if (dns1 != null)
            listDns.add(dns1.split("%")[0]);
        if (dns2 != null)
            listDns.add(dns2.split("%")[0]);
    }

    return listDns;
}
 
Example 9
Source File: Util.java    From InviZible with GNU General Public License v3.0 5 votes vote down vote up
public static List<String> getDefaultDNS(Context context) {
    List<String> listDns = new ArrayList<>();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        Network an = null;
        if (cm != null) {
            an = cm.getActiveNetwork();
        }
        if (an != null) {
            LinkProperties lp = cm.getLinkProperties(an);
            if (lp != null) {
                List<InetAddress> dns = lp.getDnsServers();
                for (InetAddress d : dns) {
                    Log.i(LOG_TAG, "DNS from LP: " + d.getHostAddress());
                    listDns.add(d.getHostAddress().split("%")[0]);
                }
            }
        }
    } else {
        String dns1 = jni_getprop("net.dns1");
        String dns2 = jni_getprop("net.dns2");
        if (dns1 != null)
            listDns.add(dns1.split("%")[0]);
        if (dns2 != null)
            listDns.add(dns2.split("%")[0]);
    }

    return listDns;
}
 
Example 10
Source File: DnsHelper.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
private static String getDnsServer(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm == null)
        return DEFAULT_DNS;

    LinkProperties props = null;

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
        for (Network network : cm.getAllNetworks()) {
            NetworkInfo ni = cm.getNetworkInfo(network);
            if (ni != null && ni.isConnected()) {
                props = cm.getLinkProperties(network);
                Log.i("Old props=" + props);
                break;
            }
        }
    else {
        Network active = cm.getActiveNetwork();
        if (active == null)
            return DEFAULT_DNS;
        props = cm.getLinkProperties(active);
        Log.i("New props=" + props);
    }

    if (props == null)
        return DEFAULT_DNS;

    List<InetAddress> dns = props.getDnsServers();
    if (dns.size() == 0)
        return DEFAULT_DNS;
    else
        return dns.get(0).getHostAddress();
}
 
Example 11
Source File: Util.java    From NetGuard with GNU General Public License v3.0 5 votes vote down vote up
public static List<String> getDefaultDNS(Context context) {
    List<String> listDns = new ArrayList<>();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        Network an = cm.getActiveNetwork();
        if (an != null) {
            LinkProperties lp = cm.getLinkProperties(an);
            if (lp != null) {
                List<InetAddress> dns = lp.getDnsServers();
                if (dns != null)
                    for (InetAddress d : dns) {
                        Log.i(TAG, "DNS from LP: " + d.getHostAddress());
                        listDns.add(d.getHostAddress().split("%")[0]);
                    }
            }
        }
    } else {
        String dns1 = jni_getprop("net.dns1");
        String dns2 = jni_getprop("net.dns2");
        if (dns1 != null)
            listDns.add(dns1.split("%")[0]);
        if (dns2 != null)
            listDns.add(dns2.split("%")[0]);
    }

    return listDns;
}
 
Example 12
Source File: AndroidNetworkLibrary.java    From cronet with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Returns list of IP addresses of DNS servers.
 * If private DNS is active, then returns a 1x1 array.
 */
@TargetApi(Build.VERSION_CODES.M)
@CalledByNative
private static byte[][] getDnsServers() {
    if (!haveAccessNetworkState()) {
        return new byte[0][0];
    }
    ConnectivityManager connectivityManager =
            (ConnectivityManager) ContextUtils.getApplicationContext().getSystemService(
                    Context.CONNECTIVITY_SERVICE);
    if (connectivityManager == null) {
        return new byte[0][0];
    }
    Network network = ApiHelperForM.getActiveNetwork(connectivityManager);
    if (network == null) {
        return new byte[0][0];
    }
    LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
    if (linkProperties == null) {
        return new byte[0][0];
    }
    List<InetAddress> dnsServersList = linkProperties.getDnsServers();
    // Determine if any DNS servers could be auto-upgraded to DNS-over-HTTPS.
    boolean autoDoh = false;
    for (InetAddress dnsServer : dnsServersList) {
        if (sAutoDohServers.contains(dnsServer)) {
            autoDoh = true;
            break;
        }
    }
    if (isPrivateDnsActive(linkProperties)) {
        String privateDnsServerName = getPrivateDnsServerName(linkProperties);
        // If user explicitly selected a DNS-over-TLS server...
        if (privateDnsServerName != null) {
            // ...their DNS-over-HTTPS support depends on the DNS-over-TLS server name.
            autoDoh = sAutoDohDotServers.contains(privateDnsServerName.toLowerCase(Locale.US));
        }
        RecordHistogram.recordBooleanHistogram(
                "Net.DNS.Android.DotExplicit", privateDnsServerName != null);
        RecordHistogram.recordBooleanHistogram("Net.DNS.Android.AutoDohPrivate", autoDoh);
        return new byte[1][1];
    }
    RecordHistogram.recordBooleanHistogram("Net.DNS.Android.AutoDohPublic", autoDoh);
    byte[][] dnsServers = new byte[dnsServersList.size()][];
    for (int i = 0; i < dnsServersList.size(); i++) {
        dnsServers[i] = dnsServersList.get(i).getAddress();
    }
    return dnsServers;
}
 
Example 13
Source File: JainSipNotificationManager.java    From restcomm-android-sdk with GNU Affero General Public License v3.0 4 votes vote down vote up
static public NetworkStatus checkConnectivity(Context context)
{
   NetworkStatus networkStatus = NetworkStatus.NetworkStatusNone;
   RCLogger.d(TAG, "checkConnectivity()");
   ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

   try {
      NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
      if (activeNetwork != null) {
         if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI && activeNetwork.isConnected()) {
            RCLogger.w(TAG, "Connectivity status: WIFI");
            networkStatus = NetworkStatus.NetworkStatusWiFi;
         }

         if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE && activeNetwork.isConnected()) {
            RCLogger.w(TAG, "Connectivity status: CELLULAR DATA");
            networkStatus = NetworkStatus.NetworkStatusCellular;
         }

         if (activeNetwork.getType() == ConnectivityManager.TYPE_ETHERNET && activeNetwork.isConnected()) {
            RCLogger.w(TAG, "Connectivity status: ETHERNET");
            networkStatus = NetworkStatus.NetworkStatusEthernet;
         }
      }

      // Sadly we cannot use getActiveNetwork right away as its added in API 23 (and we want to support > 21), so let's iterate
      // until we find above activeNetwork
      for (Network network : connectivityManager.getAllNetworks()) {
         NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
         if (networkInfo.isConnected() &&
                 (networkInfo.getType() == activeNetwork.getType()) &&
                 (networkInfo.getSubtype() == activeNetwork.getSubtype()) &&
                 (networkInfo.getExtraInfo().equals(activeNetwork.getExtraInfo()))) {
            LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
            //Log.d("DnsInfo", "iface = " + linkProperties.getInterfaceName());
            //Log.d("DnsInfo", "dns = " + linkProperties.getDnsServers());
            //Log.d("DnsInfo", "domains search = " + linkProperties.getDomains());
            StringBuilder stringBuilder = new StringBuilder();
            for (InetAddress inetAddress : linkProperties.getDnsServers()) {
               if (stringBuilder.length() != 0) {
                  stringBuilder.append(",");
               }
               stringBuilder.append(inetAddress.getHostAddress());
            }
            // From Oreo and above we need to explicitly retrieve and provide the name servers used for our DNS queries.
            // Reason for that is that prior to Oreo underlying dnsjava library for jain-sip.ext (i.e. providing facilities for DNS SRV),
            // used some system properties prefixed 'net.dns1', etc. The problem is that those got removed in Oreo so we have to use
            // alternative means, and that is to use 'dns.server' that 'dnsjava' tries to use before trying 'net.dns1';
            if (stringBuilder.length() != 0) {
               RCLogger.i(TAG, "Updating DNS servers for dnsjava with: " + stringBuilder.toString() + ", i/f: " + linkProperties.getInterfaceName());
               System.setProperty("dns.server", stringBuilder.toString());
            }
            if (linkProperties.getDomains() != null) {
               RCLogger.i(TAG, "Updating DNS search domains for dnsjava with: " + linkProperties.getDomains() + ", i/f: " + linkProperties.getInterfaceName());
               System.setProperty("dns.search", linkProperties.getDomains());
            }
         }
      }
   }
   catch (NullPointerException e) {
      throw new RuntimeException("Failed to retrieve active networks info", e);
   }

   if (networkStatus == NetworkStatus.NetworkStatusNone) {
      RCLogger.w(TAG, "Connectivity status: NONE");
   }

   return networkStatus;
}