When an Android device connects to a wifi AP, it identifies itself with a name like:
android_cc1dec12345e6054
How can that string be obtained from within an Andr
Use the NetworkInterface object to enumerate the interfaces and get the canonical host name from the interfaces' InetAddress
. Since you want the wifi name, as a shortcut you can query for wlan0
directly and if that fails you can enumerate them all like this:
import android.test.InstrumentationTestCase;
import android.util.Log;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
public class NetworkInterfaceTest extends InstrumentationTestCase {
private static final String TAG = NetworkInterfaceTest.class.getSimpleName();
public void testNetworkName() throws Exception {
Enumeration it_ni = NetworkInterface.getNetworkInterfaces();
while (it_ni.hasMoreElements()) {
NetworkInterface ni = it_ni.nextElement();
Enumeration it_ia = ni.getInetAddresses();
if (it_ia.hasMoreElements()) {
Log.i(TAG, "++ NI: " + ni.getDisplayName());
while (it_ia.hasMoreElements()) {
InetAddress ia = it_ia.nextElement();
Log.i(TAG, "-- IA: " + ia.getCanonicalHostName());
Log.i(TAG, "-- host: " + ia.getHostAddress());
}
}
}
}
}
That will give you an output like this:
TestRunner﹕ started: testNetworkName
++ NI: lo
-- IA: ::1%1
-- host: ::1%1
-- IA: localhost
-- host: 127.0.0.1
++ NI: p2p0
-- IA: fe80::1234:1234:1234:1234%p2p0
-- host: fe80::1234:1234:1234:1234%p2p0
++ NI: wlan0
-- IA: fe80::1234:1234:1234:1234%wlan0
-- host: fe80::1234:1234:1234:1234%wlan0
-- IA: android-1234567812345678 <--- right here
-- host: 192.168.1.234
Tip: if InetAddress.getCanonicalHostName().equals(InetAddress.getHostAddress())
you can ignore it as it's not a "real" name.