简体   繁体   English

如何通过具有脱机状态的Java获取MAC地址

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

I'm trying to get the MAC address of my PC without connecting to the internet, I used this code 我试图在不连接互联网的情况下获取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) {
}

it works when my computer is connected to internet, but when i go offline it doesn't. 当我的计算机连接到Internet时,它可以工作,但是当我离线时,它不能工作。

Here is the code for getting mac address for your PC even if it is not connected to 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());
        }
    }
}

Note: Many machines have multiple Mac Addresses as well. 注意:许多机器也具有多个Mac地址。 So this might return you multiple Mac Addresses 因此,这可能会返回多个Mac地址

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM