From 3e06e8c776c859f65f31fd4072b034997727b69a Mon Sep 17 00:00:00 2001 From: chenlinghy Date: Tue, 7 Jul 2020 15:14:18 +0800 Subject: [PATCH] =?UTF-8?q?OCT=20REM:=201.=20=E4=BF=AE=E6=94=B9=E5=88=A4?= =?UTF-8?q?=E6=96=ADip=E5=AD=97=E6=AE=B5=E6=98=AF=E5=90=A6=E5=90=88?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/dispose/common/IPAddrType.java | 37 ++++++++++++++----- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/dispose/common/IPAddrType.java b/src/main/java/com/dispose/common/IPAddrType.java index 4e5ff62e..d3f720d1 100644 --- a/src/main/java/com/dispose/common/IPAddrType.java +++ b/src/main/java/com/dispose/common/IPAddrType.java @@ -91,16 +91,35 @@ public enum IPAddrType { * @return the boolean */ public static boolean isIpAddress(String ipAddr) { - if (!ipAddr.contains(GlobalVar.STRING_IPV4_FLAG) && !ipAddr.contains(GlobalVar.STRING_IPV6_FLAG)) { - return false; - } - try { - IPAddressString str = new IPAddressString(ipAddr); - IPAddress addr = str.toAddress(); - return true; - } catch (AddressStringException e) { - return false; + int counts = ipAddr.length() - ipAddr.replaceAll(GlobalVar.STRING_IPV6_FLAG, "").length(); + + String ipv4Regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." + + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$"; + + String ipv6Regex = "^(([\\da-fA-F]{1,4}):){8}$"; + + switch (counts) { + // ipv4 + case 0: + return ipAddr.matches(ipv4Regex); + // v4 + port + case 1: + String ipv4 = ipAddr.substring(0, ipAddr.lastIndexOf(":")); + //String port = ipAddr.substring(ipAddr.lastIndexOf(":") + 1); + return ipv4.matches(ipv4Regex); + default: + // Ip v6 + port + if (ipAddr.contains("[")) { + String ipv6 = ipAddr.substring(1, ipAddr.lastIndexOf("]")); + //String port = ipAddr.substring(ipAddr.lastIndexOf("]:") + 1); + return ipv6.matches(ipv6Regex); + } else { + return ipAddr.matches(ipv6Regex); + } } } } + +