阅读量:2
在Spring Boot中获取MAC地址可以通过以下步骤进行:
- 导入相关的依赖:
<dependency> <groupId>io.netty</groupId> <artifactId>netty-runtime</artifactId> <version>4.1.65.Final</version> </dependency>
- 创建一个工具类来获取MAC地址:
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; } }
- 在需要获取MAC地址的地方调用上述工具类的方法:
String macAddress = MacAddressUtils.getMacAddress(); System.out.println(macAddress);
请注意,这种方法获取的是本地主机的MAC地址。若要获取网络上其他设备的MAC地址,需要使用其他的方法。