Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround mapping between NetworkInfo and NetworkInterface

I'm facing an issue that was reported in this tracker issue back in 2011 and would like to develop a suitable workaround. I would like to display all of an Android device's network interfaces to the user, as well as categorize them by their type and whether or not they are currently active. I'm targeting API 15 at minimum.

As far as I know, there are two ways to get network interface information:

  1. Via the built-in Java NetworkInterface class using NetworkInterface.getNetworkInterfaces(). This will return NetworkInterface objects that contain information like the interface name, all IP addresses associated with the interface, etc. For my device (LG G3), I get interfaces like lo, wlan0, and rmnet0. This also returns information like the IP address, MTU, subnet mask, and broadcast address, which I need.

  2. Via the Android API ConnectivityManager service using aConnManager.getAllNetworkInfo(). This returns about 20 NetworkInfo objects for my device, most are unused, but they include types MOBILE, WIFI, BLUETOOTH, etc. This doesn't include any network parameters like IP addresses, MTU, etc. as mentioned above.

The issue as explained in the tracker is that there's no built-in way to map the NetworkInfo to a NetworkInterface or vice-versa, and I would like to avoid using the interface name to map to the appropriate NetworkInfo if at all possible.

Since I have a hunch that's not possible, is there a list somewhere of all of the potential network interface names for most vendors? rmnet[0-9] seems common for devices with Qualcomm baseband processors, and wlan[0-9] for WiFi, etc.

In the worst case I suppose I could list the interface type as unknown if the interface name doesn't match any common templates. Thanks in advance.

like image 938
jpalm Avatar asked Jul 11 '15 15:07

jpalm


1 Answers

Since API 21, you can use LinkProperties to get a NetworkInterface object out of a Network network object:

ConnectivityManager manager = getSystemService(ConnectivityManager.class);
LinkProperties prop = manager.getLinkProperties(network);    
NetworkInterface iface = NetworkInterface.getByName(prop.getInterfaceName());

However, although getAllNetworks() is supposed to replace getAllNetworkInfo() (the former, introduced in API 21, has deprecated the latter in API 23), as of Android 6.0.1, it does not. getAllNetworks() does not list all networks (see SO Q#33374766). Looks like a bug.

Alternatively, in order to inform the user about the status of all network connections, a set of callbacks may be registered for each transport type available in NetworkCapabilities (i.e. TRANSPORT_CELLULAR, TRANSPORT_WIFI, TRANSPORT_ETHERNET, TRANSPORT_BLUETOOTH & TRANSPORT_VPN) using registerNetworkCallback.

like image 181
cuihtlauac Avatar answered Sep 28 '22 07:09

cuihtlauac