android机顶盒获取有线mac

直接上代码:

public static String getLocalEthernetMacAddress() {
        String mac=null;
        try {
            Enumeration localEnumeration=NetworkInterface.getNetworkInterfaces();

            while (localEnumeration.hasMoreElements()) {
                NetworkInterface localNetworkInterface=(NetworkInterface) localEnumeration.nextElement();
                String interfaceName=localNetworkInterface.getDisplayName();

                if (interfaceName==null) {
                    continue;
                }

                if (interfaceName.equals("eth0")) {
                    // MACAddr = convertMac(localNetworkInterface
                    // .getHardwareAddress());
                    mac=convertToMac(localNetworkInterface.getHardwareAddress());
                    if (mac!=null&&mac.startsWith("0:")) {
                        mac="0"+mac;
                    }
                    break;
                }

                // byte[] address =
                // localNetworkInterface.getHardwareAddress();
                // Log.i(TAG, "mac=" + address.toString());
                // for (int i = 0; (address != null && i < address.length);
                // i++)
                // {
                // Log.i("Debug", String.format("  : %x", address[i]));
                // }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return mac;
    }

    private static String convertToMac(byte[] mac) {
        StringBuilder sb=new StringBuilder();
        for (int i=0; i<mac.length; i++) {
            byte b=mac[i];
            int value=0;
            if (b>=0&&b<=16) {
                value=b;
                sb.append("0"+Integer.toHexString(value));
            } else if (b>16) {
                value=b;
                sb.append(Integer.toHexString(value));
            } else {
                value=256+b;
                sb.append(Integer.toHexString(value));
            }
            if (i!=mac.length-1) {
                sb.append(":");
            }
        }
        return sb.toString();
    }

无线的:
private static String getWifiMacAddr(Context context, String macAddr) {
        WifiManager wifi=(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info=wifi.getConnectionInfo();
        if (null!=info) {
            String addr=info.getMacAddress();
            if (null!=addr) {
                KeelLog.d("getWifiMacAddr:"+addr);
                macAddr=addr;
            }
        }
        return macAddr;
    }

相关推荐