我试图在不连接互联网的情况下获取我电脑的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) {
}
当我的电脑连接到互联网时,它可以工作,但当我离线时,它就不工作了。
以下是获取电脑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地址