java 獲取本機的所有網絡卡的Mac地址
阿新 • • 發佈:2019-01-10
public class Mac { public static void main(String[] args) { try { Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces(); while (enumeration.hasMoreElements()) { StringBuffer stringBuffer = new StringBuffer(); NetworkInterface networkInterface = enumeration.nextElement(); if (networkInterface != null) { byte[] bytes = networkInterface.getHardwareAddress(); if (bytes != null) { for (int i = 0; i < bytes.length; i++) { if (i != 0) { stringBuffer.append("-"); } int tmp = bytes[i] & 0xff; // 位元組轉換為整數 String str = Integer.toHexString(tmp); if (str.length() == 1) { stringBuffer.append("0" + str); } else { stringBuffer.append(str); } } String mac = stringBuffer.toString().toUpperCase(); System.out.println(mac); } } } } catch (Exception e) { e.printStackTrace(); } } }
無論是否有網路,都可以正常獲取所有網絡卡的Mac資訊。