栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java获取本机MAC地址

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java获取本机MAC地址

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
  public static void main(String[] args) throws SocketException, UnknownHostException {
//        StringBuilder sb = new StringBuilder();
//        Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
//        byte[] mac = null;
//        while (allNetInterfaces.hasMoreElements()) {
//            NetworkInterface netInterface = allNetInterfaces.nextElement();
//            if (netInterface.isLoopback() || netInterface.isVirtual() || netInterface.isPointToPoint() || !netInterface.isUp()) {
//                continue;
//            } else {
//                mac = netInterface.getHardwareAddress();
//                if (mac != null) {
//                    for (int i = 0; i < mac.length; i++) {
//                        sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "n"));
//                    }
//                }
//            }
//        }
//        System.out.println(sb.toString());
//        InetAddress ia = InetAddress.getLocalHost();
//        System.out.println(ia);
        System.out.println("本机mac地址:" + getLocalMac());

    }

    private static String getLocalMac() throws SocketException, UnknownHostException {
        InetAddress ipAddress = InetAddress.getLocalHost();
        byte[] mac = NetworkInterface.getByInetAddress(ipAddress).getHardwareAddress();
        // System.out.println("mac数组长度:"+mac.length);
        StringBuffer sb = new StringBuffer("");
        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" + str);
            } else {
                sb.append(str);
            }
        }
        return sb.toString().toUpperCase();
    }

代码注释部分是获取多个mac地址,没注释的是正常获取mac地址的。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1032707.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号