1. 程式人生 > 其它 >java獲取Linux和window系統多網絡卡mac地址和IP

java獲取Linux和window系統多網絡卡mac地址和IP

   public static List<Map<String, String>> getMacAndIp() throws SocketException {
        List<Map<String, String>> listMap = new ArrayList<>();
        // 獲取當前主機的所有網路介面,至少包含一個迴環ip地址 127.0.0.1
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        
while (interfaces.hasMoreElements()) { // 當前節點 NetworkInterface anInterface = interfaces.nextElement(); Enumeration<InetAddress> addresses = anInterface.getInetAddresses(); // 該網絡卡介面下的ip會有多個,也需要一個個的遍歷,找到自己所需要的 while (addresses.hasMoreElements()) { InetAddress inetAddress
= addresses.nextElement(); Map<String, String> map = new HashMap<>(3); // 排除迴環地址,不是迴環的地址 if (!inetAddress.isLoopbackAddress() && inetAddress.isSiteLocalAddress()) { // 是否本地迴環地址 是 返回 true // 獲取 MAC地址 NetworkInterface network = NetworkInterface.getByInetAddress(inetAddress);
byte[] mac = network.getHardwareAddress(); StringBuilder macs = new StringBuilder(); for (int i = 0; i < mac.length; i++) { // 格式化十六進位制 macs.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); } map.put("mac", macs.toString()); map.put("ip", inetAddress.getHostAddress()); map.put("name", inetAddress.getHostName()); listMap.add(map); } } } return listMap; }