Get Android WiFi “net.hostname” from code

前端 未结 7 1555
北荒
北荒 2021-01-31 22:43

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

7条回答
  •  别那么骄傲
    2021-01-31 23:31

    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.

    import android.os.Build;
    import java.lang.reflect.Method;
    
    /**
     * 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;
        }
    }
    

提交回复
热议问题