我们在平时的生活中,可能会有 内网 IP 过滤的需求。
一般需要过滤以下几个网段跟 ip
局域网可使用的网段(私网地址段)有三大段:
10.0.0.0~10.255.255.255(A类)
172.16.0.0~172.31.255.255(B类)
192.168.0.0~192.168.255.255(C类)
小技巧:如果你在网络出口上使用NAT技术,使用任何网段都是可以的,比如说1.1.1.1。
此外
0.0.0.0 非法ip
127.0.0.1 本地ip
10.0.0.0~10.255.255.255(A类)
A类网段的正则表达式 :
^10\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])$
172.16.0.0~172.31.255.255(B类)
B类网段的正则表达式
^172\.(1[6789]|2[0-9]|3[01])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])$
192.168.0.0~192.168.255.255(C类)
C类网段的正则表达式
^192\.168\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])$
测试用例:
@Test
public void testRegexInnerIP() {
List<String> testIPList = new ArrayList<>();
testIPList.add("127.0.0.1");
testIPList.add("0.0.0.0");
testIPList.add("192.168.0.1");
testIPList.add("192.168.255.255");
testIPList.add("111.111.11.11");
Set<String> ipFilter = new HashSet<>();
//A类地址范围:10.0.0.0—10.255.255.255
ipFilter.add("^10\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])$");
//B类地址范围: 172.16.0.0---172.31.255.255
ipFilter.add("^172\\.(1[6789]|2[0-9]|3[01])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])$");
//C类地址范围: 192.168.0.0---192.168.255.255
ipFilter.add("^192\\.168\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])$");
ipFilter.add("127.0.0.1");
ipFilter.add("0.0.0.0");
List<Pattern> ipFilterRegexList = new ArrayList<>();
for (String tmp : ipFilter) {
//System.out.println(tmp);
ipFilterRegexList.add(Pattern.compile(tmp));
}
for (String testIP : testIPList) {
Boolean valid = true;
for (Pattern tmp : ipFilterRegexList) {
Matcher matcher = tmp.matcher(testIP);
if (matcher.find()) {
System.out.println("black inner : " + testIP);
valid = false;
break;
}
}
if (valid) {
System.out.println("valid ip : " + testIP);
}
}
}