如何使用Java 5获取主机mac地址?
我知道你可以使用java.net.NetworkInterface->getHardwareAddress()
在Java 6中完成这项工作。 但是我部署的环境仅限于Java 5。
有人知道如何在Java 5或更早版本中执行此操作吗? 非常感谢。
Java 5中的标准方法是启动本机进程以运行ipconfig
或ifconfig
并解析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); } } }
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 = "[AZ].*$"; 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; }
据我所知,没有纯Java 6解决方案。 UUID解决了这个问题,但首先确定操作系统是否应该运行ifconfig或ipconfig。
在Linux和Mac OS X Machine上,您可能必须使用ifconfig -a
。
ipconfig
是as windows命令。