0

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?

Hearen
  • 7,420
  • 4
  • 53
  • 63
  • 1
    According to https://commons.apache.org/proper/commons-net/apidocs/src-html/org/apache/commons/net/util/SubnetUtils.html they use `private static final String IP_ADDRESS = "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})";` – Scary Wombat Mar 29 '18 at 02:13
  • Also have you seen https://stackoverflow.com/questions/17025046/java-library-to-check-if-ipv4-or-ipv6-address-is-in-a-given-subnet – Scary Wombat Mar 29 '18 at 02:18
  • @Scary Thank you so much. Sorry to reply late, I just checked the `Source Code`, I think the Regx I enclosed is good now. Seems more robust. – Hearen Mar 29 '18 at 02:30

1 Answers1

0
Pattern cidrPattern = Pattern.compile("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,3})");

System.out.println(cidrPattern.matcher("192.168.30.0/24").matches());
System.out.println(cidrPattern.matcher("192.168.30.160").matches());
4b0
  • 21,981
  • 30
  • 95
  • 142
  • This will not work for invalid ip addresses. 999.999.999.999/999 will also be deemed valid by this regex, and we all know this is not a valid ip v4 address. – Remcoder Mar 23 '20 at 09:18