4

我知道你可以在 Java 6 中使用java.net.NetworkInterface->getHardwareAddress(). 但我部署的环境仅限于 Java 5。

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

4

4 回答 4

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);
        }
    }
}
于 2009-08-26T09:08:30.013 回答
3

Butterchicken's solution is ok, but will only work on english versions of Windows.

A somewhat better (language independent) solution would be to match the pattern for MAC addresses. Here I also make sure that this address has an associated IP (e.g. to filter out bluetooth devices):

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;
}
于 2009-11-13T17:11:25.943 回答
2

据我所知,没有纯 Java 6 之前的解决方案。UUID解决了这个问题,但首先确定操作系统以确定它是否应该运行 ifconfig 或 ipconfig。

于 2009-08-26T09:10:13.567 回答
1

在 Linux 和 Mac OS X 机器上,您可能必须使用ifconfig -a.
ipconfig就像windows命令一样。

于 2012-04-09T07:02:45.637 回答