title: How to check IP and CIDR format in Java effectively?
body: <p>I just checked this <a href="https://stackoverflow.com/questions/5667371/validate-ipv4-address-in-java">post</a> for IP checking and this <a href="https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/util/SubnetUtils.html" rel="nofollow noreferrer">SubnetUtils</a> to check CIDR format. </p>
  
  <pre><code>private boolean isValidCidrIp(String cidrIp) {
      boolean isValid = true;
      try {
          new SubnetUtils(cidrIp);
      } catch (IllegalArgumentException e) {
          isValid = false;
      }
      return isValid;
  }
  </code></pre>
  
  <p>But I really do not want to <code>import</code> a package because I want to check a IP and CIDR if I have other choices. </p>
  
  <p>So I came up with this Regx pattern: </p>
  
  <p><code>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]))?$");</code></p>
  
  <p>But it really seems not good enough, which will include some ugly leading <code>0</code> for each field. What's even worse, there will lots of invalid IP addresses.</p>
  
  <p>Have some better ideas? </p>