を使用してJava 6でこれを実行できることを私は知っていますjava.net.NetworkInterface->getHardwareAddress()
。しかし、私がデプロイしている環境は 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 が関連付けられていることも確認します (たとえば、Bluetooth デバイスを除外するため)。
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;
}
Linux および Mac OS X マシンでは、ifconfig -a
.
ipconfig
Windowsコマンドと同じです。