Java获取本地Mac地址

方法一:自定义方法获取本地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.hutoolgroupId>
     <artifactId>hutool-allartifactId>
     <version>5.4.0version>
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

你可能感兴趣的:(Java,java,macos,开发语言)