4

を使用してJava 6でこれを実行できることを私は知っていますjava.net.NetworkInterface->getHardwareAddress()。しかし、私がデプロイしている環境は Java 5 に制限されています。

Java 5以前でこれを行う方法を知っている人はいますか? どうもありがとう。

4

4 に答える 4

6

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

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

私の知る限り、Java 6 より前の純粋なソリューションはありません。UUIDはこれを解決しますが、最初にOSを決定して、ifconfig または ipconfig を実行する必要があるかどうかを調べます。

于 2009-08-26T09:10:13.567 に答える
1

Linux および Mac OS X マシンでは、ifconfig -a.
ipconfigWindowsコマンドと同じです。

于 2012-04-09T07:02:45.637 に答える