Allow ipv6 address blocks

This commit is contained in:
Zack Shoylev 2017-01-03 16:53:18 -06:00
parent a1733e5b68
commit 5dd1032b25
2 changed files with 49 additions and 8 deletions

View File

@ -41,6 +41,7 @@ import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Multimap;
import com.google.common.io.CharStreams;
import com.google.common.net.InetAddresses;
import com.google.common.primitives.Chars;
public class Strings2 {
@ -86,7 +87,31 @@ public class Strings2 {
private static final Pattern CIDR_PATTERN = Pattern.compile(SLASH_FORMAT);
public static boolean isCidrFormat(String in) {
return CIDR_PATTERN.matcher(in).matches();
return CIDR_PATTERN.matcher(in).matches() || isIPv6CIDR(in);
}
public static boolean isIPv6CIDR(String in) {
// ensure IPv6 notation (as opposed to parsing for IPv4)
if ( !in.contains(":"))
return false;
String[] parts = in.split("/");
if ( parts.length != 2 ) {
if (parts.length == 1)
return InetAddresses.isInetAddress(in);
else
return false;
}
// no leading zero
if ( parts[1].length() > 1 && parts[1].startsWith("0"))
return false;
int mask;
try {
mask = Integer.parseInt(parts[1]);
} catch (NumberFormatException e) {
return false;
}
if (mask < 0 || mask > 128) return false;
return InetAddresses.isInetAddress(parts[0]);
}
/**

View File

@ -42,6 +42,22 @@ public class Strings2Test {
public void testIsCidrFormat() {
assert Strings2.isCidrFormat("1.2.3.4/5");
assert Strings2.isCidrFormat("0.0.0.0/0");
assert Strings2.isCidrFormat("fe80::/64");
assert Strings2.isCidrFormat("fdcf:11a8:b89f::/64");
assert Strings2.isCidrFormat("fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af");
for (int n = 0; n <= 128; n = n + 1) {
assert Strings2.isCidrFormat("fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af/" + n);
}
assert !Strings2.isCidrFormat("fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af/129");
assert !Strings2.isCidrFormat("fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af/b");
assert !Strings2.isCidrFormat("fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af/*");
assert !Strings2.isCidrFormat("fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af/@");
assert !Strings2.isCidrFormat("fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af/00");
assert !Strings2.isCidrFormat("fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af/01");
assert !Strings2.isCidrFormat("fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af/");
assert !Strings2.isCidrFormat("banana");
assert !Strings2.isCidrFormat("1.2.3.4");
assert !Strings2.isCidrFormat("500.500.500.500/2423");