java 记录mac地址
在Java中,可以使用InetAddress类来获取本地主机的MAC地址。以下是一个示例代码:
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
public class Main {
public static void main(String[] args) {
try {
InetAddress localhost = InetAddress.getLocalHost();
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localhost);
byte[] macAddressBytes = networkInterface.getHardwareAddress();
StringBuilder macAddress = new StringBuilder();
for (int i = 0; i < macAddressBytes.length; i++) {
macAddress.append(String.format("%02X%s", macAddressBytes[i], (i < macAddressBytes.length - 1) ? "-" : ""));
}
System.out.println("MAC Address: " + macAddress);
} catch (UnknownHostException | SocketException e) {
e.printStackTrace();
}
}
}
该代码首先获取本地主机的InetAddress对象,然后使用getByInetAddress()方法获取与该主机关联的网络接口。接着,通过调用getHardwareAddress()方法获取MAC地址的字节数组,最后将字节数组转换为十六进制字符串表示的MAC地址。
请注意,以上代码可能会返回多个MAC地址,因为一台主机可能会有多个网络接口
原文地址: https://www.cveoy.top/t/topic/h9ml 著作权归作者所有。请勿转载和采集!