/** * 獲取本機的Mac地址 * @return */ public String getMac() { InetAddress ia; byte[] mac = null; try { // 獲取本地IP對象 ia = InetAddress.getLocalHost(); // 獲得網絡接口對象(即網卡),並得到mac地址,mac地址存在於一個byte數組中。 mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress(); } catch (Exception e) { e.printStackTrace(); } // 下面代碼是把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(); }