Java判断IP地址是否在CIDR范围内

Java原生算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//核心代码,检索IP所属网段
public boolean isInRange(String ip, String cidr) {
String[] ips = ip.split("\\.");
long ipAddr = (Long.parseInt(ips[0]) << 24)
| (Long.parseInt(ips[1]) << 16)
| (Long.parseInt(ips[2]) << 8)
| Long.parseInt(ips[3]);
long type = Long.parseInt(cidr.replaceAll(".*/", ""));
long mask = 0xFFFFFFFF << (32 - type);
String cidrIp = cidr.replaceAll("/.*", "");
String[] cidrIps = cidrIp.split("\\.");
long networkIpAddr = (Long.parseInt(cidrIps[0]) << 24)
| (Long.parseInt(cidrIps[1]) << 16)
| (Long.parseInt(cidrIps[2]) << 8)
| Long.parseInt(cidrIps[3]);
return (ipAddr & mask) == (networkIpAddr & mask);
}
1
System.out.println(isInRange("192.168.1.129", "192.168.1.132/25"));

Apache库

1
2
3
4
5
//也可以使用apache的net工具类
public boolean isInRange(String ip, String network) {
SubnetInfo subnetInfo = new SubnetUtils(network).getInfo();
return subnetInfo.isInRange(ip);
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :