在Spring Boot中獲取MAC地址可以通過以下步驟進行:
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-runtime</artifactId>
<version>4.1.65.Final</version>
</dependency>
import io.netty.channel.socket.nio.NioDatagramChannel;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
public class MacAddressUtils {
public static String getMacAddress() {
try {
NetworkInterface network = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
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) ? "-" : ""));
}
return sb.toString();
} catch (SocketException | UnknownHostException e) {
e.printStackTrace();
}
return null;
}
}
String macAddress = MacAddressUtils.getMacAddress();
System.out.println(macAddress);
請注意,這種方法獲取的是本地主機的MAC地址。若要獲取網絡上其他設備的MAC地址,需要使用其他的方法。