码上敲享录 > java入门知识分享 > java 获取本地ip地址,mac物理网卡地址

java 获取本地ip地址,mac物理网卡地址

上一章章节目录下一章 2019-09-05已有1702人阅读 评论(0)

public String index(Model model,String code) throws Exception {

       if(!StringUtils.isEmpty(code)){

           InetAddress ia = null;

           try {

               ia = ia.getLocalHost();

               String localName = ia.getHostName();

               String localIp = ia.getHostAddress();

               model.addAttribute("localName",localName);

               model.addAttribute("localIp",localIp);

           } catch (Exception e) {

               e.printStackTrace();

           }

           InetAddress ia1 = InetAddress.getLocalHost();// 获取本地IP对象

           String macAddress = getMACAddress(ia1);

           model.addAttribute("macAddress",macAddress);

           model.addAttribute("projectCode",code);

       }

       return "index";

   }




private static String getMACAddress(InetAddress ia) throws Exception {

         //获得网络接口对象(即网卡),并得到mac地址,mac地址存在于一个byte数组中。

       byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();

       // 下面代码是把mac地址拼装成String

       StringBuffer sb = new StringBuffer();

       for (int i = 0; i < mac.length; i++) {

           if (i != 0) {

               sb.append("-");

           }

           // mac[i] & 0xFF 是为了把byte转化为正整数

           String s = Integer.toHexString(mac[i] & 0xFF);

           sb.append(s.length() == 1 ? 0 + s : s);

       }

       // 把字符串所有小写字母改为大写成为正规的mac地址并返回

       return sb.toString().toUpperCase();

   }



向大家推荐《Activiti工作流实战教程》:https://xiaozhuanlan.com/activiti
0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交