簡體   English   中英

如何通過具有脫機狀態的Java獲取MAC地址

[英]How to get MAC address by java with offline state

我試圖在不連接互聯網的情況下獲取PC的MAC地址,因此使用了此代碼

InetAddress ip;
try {
    ip = InetAddress.getLocalHost(); 

    NetworkInterface network = NetworkInterface.getByInetAddress(ip);

    byte[] mac = network.getHardwareAddress();

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < mac.length; i++) {
        sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));        
    }
            System.out.println(sb.toString());

} catch (UnknownHostException | SocketException e) {
}

當我的計算機連接到Internet時,它可以工作,但是當我離線時,它不能工作。

這是即使您的PC未連接到Internet時也要獲取其Mac地址的代碼:

public static void main(String[] args) throws SocketException {
final Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
    while (e.hasMoreElements()) {
        final byte [] mac = e.nextElement().getHardwareAddress();
        if (mac != null) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++)
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
            System.out.println(sb.toString());
        }
    }
}

注意:許多機器也具有多個Mac地址。 因此,這可能會返回多個Mac地址

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM