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类地址。
import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IPV4Test {
public static void main(String[] args) {
String ip1 = "127.0.0.1";
String ip2 = "255.255.36.6";
System.out.println("check > " + ip1 + " > " + isValidIpv4Addr(ip1));
System.out.println("check > " + ip2 + " > " + isValidIpv4Addr(ip2));
}
public static boolean isValidIpv4Addr(String ipAddr) {
String regex = "(^((22[0-3]|2[0-1][0-9]|[0-1][0-9][0-9]|([0-9]){1,2})"
+ "([.](25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9]|([0-9]){1,2})){3})$)";
if (ipAddr == null) {
System.out.println("ip addresss is null ");
return false;
}
ipAddr = Normalizer.normalize(ipAddr, Form.NFKC);
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(ipAddr);
boolean match = matcher.matches();
if (!match) {
// System.out.println("invalid ip addresss = " + ipAddr);
}
return match;
}
}