javaandroidkotlinmac-addressnetwork-interface

NetworkInterface.getNetworkInterfaces() hardware address does not have wlan0 in list


I develop 2 mobile apps. First one is in Kotlin, second one is in Java. I use the same code to get MAC address in both. But in Kontlin it works:

            val all = Collections.list(NetworkInterface.getNetworkInterfaces())
        for (nif in all) {
            if (nif.name.contains("wlan") || nif.name.contains("eth")) {

                val macBytes = nif.hardwareAddress ?: return ""

                val res1 = StringBuilder()
                for (b in macBytes) {
                    res1.append(String.format("%02X:", b))
                }

                if (res1.length > 0) {
                    res1.deleteCharAt(res1.length - 1)
                }
                return res1.toString().toUpperCase()
            }
        }

Collections.list(NetworkInterface.getNetworkInterfaces()) returns 25 items, including wlan0,

but in Java code (the same device)

            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface nif : all) {
            if (nif.getName().contains("wlan") || nif.getName().contains("eth")) {
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                mac = res1.toString().toUpperCase();
            }
        }

Collections.list(NetworkInterface.getNetworkInterfaces()) returns 3 items, with no wlan0, but having swlan, and all of list items hardware addresses are null. Both apps have permissions

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

How can I fix that?


Solution

  • I think likely the two apps have different target SDK versions. The documentation for NetworkInterface.getNetworkInterfaces() states:

    For non-system apps with targetSdkVersion >= android.os.Build.VERSION_CODES.R, this method will only return information for NetworkInterfaces that are associated with an InetAddress.

    https://developer.android.com/reference/java/net/NetworkInterface#getNetworkInterfaces()