TheGraeme TheGraeme - 4 months ago 25
Android Question

Get Android WiFi "net.hostname" from code

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 Android app? Not for the purpose of changing it, just for readout.

EDIT:

This is a screenshot of my router's web interface, showing a list of all connected devices. Note the two Android devices on the list -- How can that string be read from Java code running on the device?

Router's connection list

Answer

Building off of @Merlevede's answer, here's a quick and dirty way to get the property. It's a private API, so it's subject to change, but this code hasn't been modified since at least Android 1.5 so it's probably safe to use.

/**
 * Retrieves the net.hostname system property
 * @param defValue the value to be returned if the hostname could
 * not be resolved
 */
public static String getHostName(String defValue) {
    try {
        Method getString = Build.class.getDeclaredMethod("getString", String.class);
        getString.setAccessible(true);
        return getString.invoke(null, "net.hostname").toString();
    } catch (Exception ex) {
        return defValue;
    }
}