Java Code Examples for android.net.ConnectivityManager#getLinkProperties()

The following examples show how to use android.net.ConnectivityManager#getLinkProperties() . 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: 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 2
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 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 LinkProperties getLinkProperties() {
  ConnectivityManager connectivityManager =
      (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
    // getActiveNetwork() requires M or later.
    return null;
  }
  Network activeNetwork = connectivityManager.getActiveNetwork();
  if (activeNetwork == null) {
    return null;
  }
  return connectivityManager.getLinkProperties(activeNetwork);
}
 
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: 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 7
Source File: JNIUtilities.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
@TargetApi(23)
public static String getCurrentNetworkInterfaceName(){
	ConnectivityManager cm=(ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
	Network net=cm.getActiveNetwork();
	if(net==null)
		return null;
	LinkProperties props=cm.getLinkProperties(net);
	if(props==null)
		return null;
	return props.getInterfaceName();
}
 
Example 8
Source File: AndroidUsingLinkProperties.java    From Conversations with GNU General Public License v3.0 5 votes vote down vote up
@Override
@TargetApi(21)
public String[] getDnsServerAddresses() {
    final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final Network[] networks = connectivityManager == null ? null : connectivityManager.getAllNetworks();
    if (networks == null) {
        return new String[0];
    }
    final Network activeNetwork = getActiveNetwork(connectivityManager);
    final List<String> servers = new ArrayList<>();
    int vpnOffset = 0;
    for(Network network : networks) {
        LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
        if (linkProperties == null) {
            continue;
        }
        final NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
        final boolean isActiveNetwork = network.equals(activeNetwork);
        final boolean isVpn = networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_VPN;
        if (isActiveNetwork && isVpn) {
            final List<String> tmp = getIPv4First(linkProperties.getDnsServers());
            servers.addAll(0, tmp);
            vpnOffset += tmp.size();
        } else if (hasDefaultRoute(linkProperties) || isActiveNetwork || activeNetwork == null || isVpn) {
            servers.addAll(vpnOffset, getIPv4First(linkProperties.getDnsServers()));
        }
    }
    return servers.toArray(new String[0]);
}
 
Example 9
Source File: JNIUtilities.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@TargetApi(23)
public static String getCurrentNetworkInterfaceName(){
	ConnectivityManager cm=(ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
	Network net=cm.getActiveNetwork();
	if(net==null)
		return null;
	LinkProperties props=cm.getLinkProperties(net);
	if(props==null)
		return null;
	return props.getInterfaceName();
}
 
Example 10
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 11
Source File: AndroidUsingLinkProperties.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
@Override
@TargetApi(21)
public String[] getDnsServerAddresses() {
    final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final Network[] networks = connectivityManager == null ? null : connectivityManager.getAllNetworks();
    if (networks == null) {
        return new String[0];
    }
    final Network activeNetwork = getActiveNetwork(connectivityManager);
    final List<String> servers = new ArrayList<>();
    int vpnOffset = 0;
    for (Network network : networks) {
        LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
        if (linkProperties == null) {
            continue;
        }
        final NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
        final boolean isActiveNetwork = network.equals(activeNetwork);
        final boolean isVpn = networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_VPN;
        if (isActiveNetwork && isVpn) {
            final List<String> tmp = getIPv4First(linkProperties.getDnsServers());
            servers.addAll(0, tmp);
            vpnOffset += tmp.size();
        } else if (hasDefaultRoute(linkProperties) || isActiveNetwork || activeNetwork == null || isVpn) {
            servers.addAll(vpnOffset, getIPv4First(linkProperties.getDnsServers()));
        }
    }
    return servers.toArray(new String[0]);
}
 
Example 12
Source File: GnirehtetService.java    From gnirehtet with Apache License 2.0 5 votes vote down vote up
private Network findVpnNetwork() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    Network[] networks = cm.getAllNetworks();
    for (Network network : networks) {
        LinkProperties linkProperties = cm.getLinkProperties(network);
        List<LinkAddress> addresses = linkProperties.getLinkAddresses();
        for (LinkAddress addr : addresses) {
            if (addr.getAddress().equals(VPN_ADDRESS)) {
                return network;
            }
        }
    }
    return null;
}
 
Example 13
Source File: LocalIPUtil.java    From DanDanPlayForAndroid with MIT License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private LinkProperties getLinkProperties(ConnectivityManager connectivityManager, int cap) {
    Network nets[] = connectivityManager.getAllNetworks();
    for (Network n: nets) {
        LinkProperties linkProperties = connectivityManager.getLinkProperties(n);
        NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(n);
        String interfaceName =  linkProperties.getInterfaceName();
        if (interfaceName != null && networkCapabilities != null) {
            if (networkCapabilities.hasTransport(cap))
                return linkProperties;
        }
    }
    return null;
}
 
Example 14
Source File: JNIUtilities.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@TargetApi(23)
public static String getCurrentNetworkInterfaceName(){
	ConnectivityManager cm=(ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
	Network net=cm.getActiveNetwork();
	if(net==null)
		return null;
	LinkProperties props=cm.getLinkProperties(net);
	if(props==null)
		return null;
	return props.getInterfaceName();
}
 
Example 15
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 16
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 17
Source File: JNIUtilities.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@TargetApi(23)
public static String getCurrentNetworkInterfaceName(){
	ConnectivityManager cm=(ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
	Network net=cm.getActiveNetwork();
	if(net==null)
		return null;
	LinkProperties props=cm.getLinkProperties(net);
	if(props==null)
		return null;
	return props.getInterfaceName();
}
 
Example 18
Source File: Vpn.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
    super(TAG);
    mConfig = config;
    mDaemons = new String[] {"racoon", "mtpd"};
    // TODO: clear arguments from memory once launched
    mArguments = new String[][] {racoon, mtpd};
    mSockets = new LocalSocket[mDaemons.length];

    // This is the interface which VPN is running on,
    // mConfig.interfaze will change to point to OUR
    // internal interface soon. TODO - add inner/outer to mconfig
    // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
    // we will leave the VPN up.  We should check that it's still there/connected after
    // registering
    mOuterInterface = mConfig.interfaze;

    if (!TextUtils.isEmpty(mOuterInterface)) {
        final ConnectivityManager cm = ConnectivityManager.from(mContext);
        for (Network network : cm.getAllNetworks()) {
            final LinkProperties lp = cm.getLinkProperties(network);
            if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
                final NetworkInfo networkInfo = cm.getNetworkInfo(network);
                if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
            }
        }
    }

    IntentFilter filter = new IntentFilter();
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    mContext.registerReceiver(mBroadcastReceiver, filter);
}
 
Example 19
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 20
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;
}