java获取计算机mac物理地址
时间: 2023-08-11 10:04:38 浏览: 126
以下是Java代码示例,用于获取计算机的MAC物理地址:
```java
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
public class MacAddress {
public static void main(String[] args) {
try {
InetAddress localhost = InetAddress.getLocalHost();
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localhost);
byte[] macBytes = networkInterface.getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < macBytes.length; i++) {
sb.append(String.format("%02X%s", macBytes[i], (i < macBytes.length - 1) ? "-" : ""));
}
System.out.println("MAC Address: " + sb.toString());
} catch (UnknownHostException | SocketException e) {
e.printStackTrace();
}
}
}
```
该代码获取本机的InetAddress对象,然后通过getHardwareAddress()方法获取MAC物理地址,最后将结果转换成十六进制格式输出。需要注意的是,获取MAC地址需要在本地计算机上执行,无法通过远程方式获取。
阅读全文