獲取mac地址

1、通過ifconfig去獲取mac地址(需要busybox,有些情況下獲取不到



 public static String getMacAddress() {
        String result = "";
        String Mac = "";
        result = callCmd("busybox ifconfig eth0", "HWaddr");
        //如果返回的result == null,則說明網絡不可取
        if (result == null) {
            return "eth0 is null";
        }

        //對該行數據進行解析
        //例如:eth0      Link encap:Ethernet  HWaddr 00:16:E8:3E:DF:67
        if (result.length() > 0 && result.contains("HWaddr") == true) {
            Mac = result.substring(result.indexOf("HWaddr") + 6, result.length() - 1);
            if (Mac.length() > 1) {
                LogDebugUtil.e(TAG, Mac.trim() + "=====");
                LogDebugUtil.e(TAG,readSysfs("/sys/class/net/eth0/address")+ "+++");
                return Mac.trim();
            }

        }


        return result;
    }


  /*
       * 通過ifconfig去獲取mac地址。。。
       *
       */

    public static String callCmd(String cmd, String filter) {
        String result = "";
        String line = "";
        try {
            Process proc = Runtime.getRuntime().exec(cmd);
            InputStreamReader is = new InputStreamReader(proc.getInputStream());
            BufferedReader br = new BufferedReader(is);

            //執行命令cmd,只取結果中含有filter的這一行
            while ((line = br.readLine()) != null && line.contains(filter) == false) {
                //result += line;
            }

            result = line;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

2、通過/sys/class/net/eth0/address 獲取


 public static String getMacAddress() {
        String Mac = readSysfs("/sys/class/net/eth0/address");
        if (Mac == null) {
            return "eth0 is null";
        }
        return Mac;
    }

    private static String readSysfs(String path) {
        if (!new File(path).exists()) {
            return null;
        }
        String str;
        StringBuilder value = new StringBuilder();

        try {
            FileReader fr = new FileReader(path);
            BufferedReader br = new BufferedReader(fr);
            try {
                while ((str = br.readLine()) != null) {
                    value.append(str);
                }
                fr.close();
                br.close();
                return value != null ? value.toString() : null;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章