I just checked this post for IP checking and this SubnetUtils to check CIDR format.
private boolean isValidCidrIp(String cidrIp) {
boolean isValid = true;
try {
new SubnetUtils(cidrIp);
} catch (IllegalArgumentException e) {
isValid = false;
}
return isValid;
}
But I really do not want to import
a package because I want to check a IP and CIDR if I have other choices.
So I came up with this Regx pattern:
private static final Pattern IP_V4_PATTERN = Pattern.compile(
"^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])(/([0-2]?\\d?|3[0-2]))?$");
But it really seems not good enough, which will include some ugly leading 0
for each field. What's even worse, there will lots of invalid IP addresses.
Have some better ideas?