private static final String NETMASK = "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"; private static final Pattern IP_PATTERN = Pattern.compile("^(?:" + NETMASK + "\\.){3}" + NETMASK + "$"); public static final String LOCAL_IP = "127.0.0.1"; /** * 获取本机的所有网卡IP列表 不包含127.0.0.1 * @return 本机网卡的IP列表 */ public static List<String> getServerIpList() { List<String> serverIpList = new ArrayList<>(); try { // 获取所有网络接口(网卡) Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); // 遍历每个网络接口 for (NetworkInterface networkInterface : Collections.list(interfaces)) { // 跳过回环接口和未激活的接口 if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; } // 获取每个网络接口的 IP 地址 Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); for (InetAddress inetAddress : Collections.list(inetAddresses)) { // 过滤掉IPv6地址(如果你只想要IPv4地址) if (inetAddress instanceof java.net.Inet4Address) { String ip = inetAddress.getHostAddress(); if (!LOCAL_IP.equals(ip) && isIPv4Valid(ip)) { serverIpList.add(inetAddress.getHostAddress()); } } } } } catch (SocketException e) { throw new RuntimeException("获取服务器网卡IP异常", e); } return serverIpList; } public static boolean isIPv4Valid(String ip) { return IP_PATTERN.matcher(ip).matches(); }
标签:JAVA,String,IP,IP地址,networkInterface,网卡,static,ip From: https://www.cnblogs.com/pxblog/p/18400960