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; }
哇!又赚了一天人民币