求助这个函数到底怎么实现的获取MAC地址

情深不及哈士奇 发布于 2018/05/21 11:34
阅读 65
收藏 0

这个函数应该是读取arp表然后通过ip寻找Mac地址,但是不懂具体的实现细节

private final static String MAC_RE =

"^%s\\s+0x1\\s+0x2\\s+([:0-9a-fA-F]+)\\s+\\*\\s+\\w+$";  //这个是正则表达式吗?具体是转化成啥?
    public final static int BUF = 8 * 1024;
    public final static String NOMAC = "00:00:00:00:00:00";

    public static String getHardwareAddress(String ip) {
        String hw = NOMAC;
        try {
            if (ip != null) {
                System.out.println("hhh"+ip);
                String ptrn = String.format(MAC_RE, ip.replace(".", "\\."));
                System.out.println("hhh"+ptrn);
                Pattern pattern = Pattern.compile(ptrn);
                System.out.println("hhh"+pattern);

//这个pattern是将ip地址转化为在arp表中ip地址的格式吗
                BufferedReader bufferedReader = new BufferedReader(new FileReader("/proc/net/arp"), BUF);
                String line;
                Matcher matcher;
                while ((line = bufferedReader.readLine()) != null) {
                    matcher = pattern.matcher(line);                   //根据这句猜的pattern
                    System.out.println("hhh"+matcher);
                    if (matcher.matches()) {
                        hw = matcher.group(1);
                        break;
                    }
                }
                bufferedReader.close();
            }
        } catch (IOException e) {
            return hw;
        }
        return hw;
    }

我自己看了下ip,ptrn,pattern三个参数

ip:172.17.100.1
ptrn:^172\.17\.100\.1\s+0x1\s+0x2\s+([:0-9a-fA-F]+)\s+\*\s+\w+$
pattern:^172\.17\.100\.1\s+0x1\s+0x2\s+([:0-9a-fA-F]+)\s+\*\s+\w+$

加载中
返回顶部
顶部