REM:
1. 修改判断ip字段是否合法
This commit is contained in:
chenlinghy 2020-07-07 15:14:18 +08:00
parent f8a66100da
commit 3e06e8c776
1 changed files with 28 additions and 9 deletions

View File

@ -91,16 +91,35 @@ public enum IPAddrType {
* @return the boolean * @return the boolean
*/ */
public static boolean isIpAddress(String ipAddr) { 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; int counts = ipAddr.length() - ipAddr.replaceAll(GlobalVar.STRING_IPV6_FLAG, "").length();
} catch (AddressStringException e) {
return false; 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);
}
} }
} }
} }