关闭

获取mac地址

标签: mac
88人阅读 评论(0) 收藏 举报
分类:

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;
        }
    }
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1969次
    • 积分:112
    • 等级:
    • 排名:千里之外
    • 原创:9篇
    • 转载:2篇
    • 译文:0篇
    • 评论:0条
    文章存档