Get android Ethernet MAC Address (not wifi interface)

后端 未结 8 1904
南旧
南旧 2021-02-05 12:12

I\'m using Android with Api level 8 and I want to get the Address of my Ethernet interface (eth0).

On API level 8, the NetworkInterface class don\'t have the function ge

8条回答
  •  我寻月下人不归
    2021-02-05 12:33

    public static String getEthernetMacAddress() {
        String macAddress = "Not able to read";
        try {
            List allNetworkInterfaces = Collections.list(NetworkInterface
                    .getNetworkInterfaces());
            for (NetworkInterface nif : allNetworkInterfaces) {
                if (!nif.getName().equalsIgnoreCase("eth0")) 
                    continue;
    
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return macAddress;
                }
    
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }
    
                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                macAddress = res1.toString();
            }
        } catch (Exception ex) {
            log(LogLevel.ERROR, "getEthernetMacAddress e :" + ex.getMessage());
            ex.printStackTrace();
        }
        return macAddress;
    }
    

提交回复
热议问题