Reputation: 2195
In Android emulator, the address (eth0
) is 10.0.2.15/24
On a tablet that supports Ethernet, eth0
has a similar address: e.g. 192.168.0.2/24
How can I find it through existing Android APIs? (existing versions - prior to Android L preview!).
I know it can be done for WiFi via WifiManager.getDhcpInfo() - but I am interested in Ethernet - or even better a generic way.
Upvotes: 1
Views: 3819
Reputation: 8381
Here's a method that will get the mask, AKA the network prefix length. The minimum API is 9 and the INTERNET permission is required. The address has a '/' prefix, but that can be easily removed by adding .toString.substring(1)
or the like.
public void logLocalIpAddresses() {
Enumeration<NetworkInterface> nwis;
try {
nwis = NetworkInterface.getNetworkInterfaces();
while (nwis.hasMoreElements()) {
NetworkInterface ni = nwis.nextElement();
for (InterfaceAddress ia : ni.getInterfaceAddresses())
Log.i(TAG, String.format("%s: %s/%d",
ni.getDisplayName(), ia.getAddress(), ia.getNetworkPrefixLength()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
Upvotes: 6