正则表达式 _ 内网IP 过滤

本文详细介绍了如何使用正则表达式来过滤局域网内的私有IP地址,包括A、B、C三类私网地址段,并提供了测试用例验证过滤规则的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   

    我们在平时的生活中,可能会有 内网 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);
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值