如何使用Java 5获取主机mac地址?

时间:2009-08-26 09:05:12

标签: java java-5

我知道您可以使用java.net.NetworkInterface->getHardwareAddress()在Java 6中执行此操作。但是我部署的环境仅限于Java 5.

有人知道如何在Java 5或更早版本中执行此操作吗?非常感谢。

4 个答案:

答案 0 :(得分:6)

Java 5中的标准方法是启动本机进程以运行ipconfigifconfig并解析OutputStream以获得答案。

例如:

private String getMacAddress() throws IOException {
    String command = “ipconfig /all”;
    Process pid = Runtime.getRuntime().exec(command);
    BufferedReader in = new BufferedReader(new InputStreamReader(pid.getInputStream()));
    Pattern p = Pattern.compile(”.*Physical Address.*: (.*)”);
    while (true) {
        String line = in.readLine();
        if (line == null)
            break;
        Matcher m = p.matcher(line);
        if (m.matches()) {
            return m.group(1);
        }
    }
}

答案 1 :(得分:3)

Butterchicken的解决方案没问题,但只适用于英文版的Windows。

更好(独立于语言)的解决方案是匹配MAC地址的模式。在这里,我还要确保此地址具有关联的IP(例如,过滤掉蓝牙设备):

public String obtainMacAddress()
throws Exception {
    Process aProc = Runtime.getRuntime().exec("ipconfig /all");
    InputStream procOut = new DataInputStream(aProc.getInputStream());
    BufferedReader br = new BufferedReader(new InputStreamReader(procOut));

    String aMacAddress = "((\\p{XDigit}\\p{XDigit}-){5}\\p{XDigit}\\p{XDigit})";
    Pattern aPatternMac = Pattern.compile(aMacAddress);
    String aIpAddress = ".*IP.*: (([0-9]*\\.){3}[0-9]).*$";
    Pattern aPatternIp = Pattern.compile(aIpAddress);
    String aNewAdaptor = "[A-Z].*$";
    Pattern aPatternNewAdaptor = Pattern.compile(aNewAdaptor);

    // locate first MAC address that has IP address
    boolean zFoundMac = false;
    boolean zFoundIp = false;
    String foundMac = null;
    String theGoodMac = null;

    String strLine;
    while (((strLine = br.readLine()) != null) && !(zFoundIp && zFoundMac)) {
        Matcher aMatcherNewAdaptor = aPatternNewAdaptor.matcher(strLine);
        if (aMatcherNewAdaptor.matches()) {
            zFoundMac = zFoundIp = false;
        }
        Matcher aMatcherMac = aPatternMac.matcher(strLine);
        if (aMatcherMac.find()) {
            foundMac = aMatcherMac.group(0);
            zFoundMac = true;
        }
        Matcher aMatcherIp = aPatternIp.matcher(strLine);
        if (aMatcherIp.matches()) {
            zFoundIp = true;
            if(zFoundMac && (theGoodMac == null)) theGoodMac = foundMac;
        }
    }

    aProc.destroy();
    aProc.waitFor();

    return theGoodMac;
}

答案 2 :(得分:1)

据我所知,没有纯粹的Java 6解决方案。 UUID解决了这个问题,但首先determine OS找出它是否应该运行ifconfig或ipconfig。

答案 3 :(得分:1)

在Linux和Mac OS X Machine上,您可能必须使用ifconfig -a ipconfig与windows命令一样。