方法一:自定义方法获取本地mac地址

1.工具方法

/** * 获取本地mac地址 * 注意:物理地址是48位,别和ipv6搞错了 * @param inetAddress * @return 本地mac地址 */private static String getLocalMac(InetAddress inetAddress) {try {//获取网卡,获取地址byte[] mac = NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress();StringBuilder sb = new StringBuilder();for (int i = 0; i < mac.length; i++) {if (i != 0) {sb.append("-");}//字节转换为整数int temp = mac[i] & 0xff;String str = Integer.toHexString(temp);if (str.length() == 1) {sb.append("0").append(str);} else {sb.append(str);}}return sb.toString();} catch (Exception exception) {}return null;}

2.执行代码

public static void main(String[] args) throws UnknownHostException {InetAddress inetAddress = InetAddress.getLocalHost();//第一种方式:利用自己写的方法获取本地mac地址String localMacAddress1 = getLocalMac(inetAddress);System.out.println("localMacAddress1 = " + localMacAddress1);}

方法二:利用hutool工具类中的封装方法获取本机mac地址

1.引入依赖

<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.4.0</version></dependency>

2.java代码

public static void main(String[] args) throws UnknownHostException {InetAddress inetAddress = InetAddress.getLocalHost();//第二种方式:利用hutool工具类中的封装方法获取本机mac地址String localMacAddress2 = NetUtil.getMacAddress(inetAddress);System.out.println("localMacAddress2 = " + localMacAddress2);}

参考文章:https://blog.csdn.net/LRXmrlirixing/article/details/127281628