JAVA得到计算机所有网卡的MAC地址

13年前

/*

     * 得到mac地址结集合

     */

    public ArrayList<String> getMacs(){

      

       ArrayList<String> macs = new ArrayList<String>();

      

       try {

           InetAddress inetAddress;

           Enumeration<NetworkInterface> ifaces =

               NetworkInterface.getNetworkInterfaces();

           while (ifaces.hasMoreElements()) {

               NetworkInterface iface = ifaces.nextElement();

               Enumeration<InetAddress> addrs = iface.getInetAddresses();

                while (addrs.hasMoreElements()) {

                    inetAddress = addrs.nextElement();

                    if (inetAddress instanceof Inet4Address){

                       NetworkInterface ni = NetworkInterface.getByInetAddress(inetAddress);

                       if(ni.getHardwareAddress() != null){

                           byte[] mac = ni.getHardwareAddress();

                           StringBuffer sb = new StringBuffer();

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

                               String str = new String().format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");

                               sb.append(str);

                            }

                            macs.add(sb.toString());

                       }

                    }

                }

           }

       } catch (SocketException e) {

           e.printStackTrace();

       }

      

       return macs;

    }

 

 

 

如果想得到网卡的其他信息,请参考API