https://blog.csdn.net/Kangyucheng/article/details/86497670

规则:
Ipv4地址分为ABCDE五大类,其中ABC类是普通ip地址,D类是组播地址,E类保留,作为研究之用。

范围分别为:
A: 1.0.0.1 一127.255.255.255
内网地址范围:10.0.0.0 一一10-255.255.255
B: 128.0.0.1 —191.255.255.255
内网地址范围:172.16.0.0——172.31.255.255
C: 192.0.0.1 —223.255.255.255
内网地址范围:192.168.0.0—一192.168.255.255
D: 224.0.0.1 —239.255.255.255
E: 240.0.0.1 —255.255.255.255

正则要求ip必须是ABC类地址。

  1. import java.text.Normalizer;
  2. import java.text.Normalizer.Form;
  3. import java.util.regex.Matcher;
  4. import java.util.regex.Pattern;
  5. public class IPV4Test {
  6. public static void main(String[] args) {
  7. String ip1 = "127.0.0.1";
  8. String ip2 = "255.255.36.6";
  9. System.out.println("check > " + ip1 + " > " + isValidIpv4Addr(ip1));
  10. System.out.println("check > " + ip2 + " > " + isValidIpv4Addr(ip2));
  11. }
  12. public static boolean isValidIpv4Addr(String ipAddr) {
  13. String regex = "(^((22[0-3]|2[0-1][0-9]|[0-1][0-9][0-9]|([0-9]){1,2})"
  14. + "([.](25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9]|([0-9]){1,2})){3})$)";
  15. if (ipAddr == null) {
  16. System.out.println("ip addresss is null ");
  17. return false;
  18. }
  19. ipAddr = Normalizer.normalize(ipAddr, Form.NFKC);
  20. Pattern pattern = Pattern.compile(regex);
  21. Matcher matcher = pattern.matcher(ipAddr);
  22. boolean match = matcher.matches();
  23. if (!match) {
  24. // System.out.println("invalid ip addresss = " + ipAddr);
  25. }
  26. return match;
  27. }
  28. }