Ipv4地址段匹配

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class IpMatcher {
public static boolean matchIPV4(String ip, String cidr) {
String[] ips = ip.split("\\.");
if (ips.length != 4) {
return false;
}
int ipAddr = (Integer.parseInt(ips[0]) << 24)
| (Integer.parseInt(ips[1]) << 16)
| (Integer.parseInt(ips[2]) << 8) | Integer.parseInt(ips[3]);
int type = Integer.parseInt(cidr.replaceAll(".*/", ""));
int mask = 0xFFFFFFFF << (32 - type);
String cidrIp = cidr.replaceAll("/.*", "");
String[] cidrIps = cidrIp.split("\\.");
int cidrIpAddr = (Integer.parseInt(cidrIps[0]) << 24)
| (Integer.parseInt(cidrIps[1]) << 16)
| (Integer.parseInt(cidrIps[2]) << 8)
| Integer.parseInt(cidrIps[3]);
return (ipAddr & mask) == (cidrIpAddr & mask);
}

public static void main(String[] args) {
System.out.println(matchIPV4("172.16.0.1", "172.16.0.0/20"));
}
}
作者

雾非雾的情思

发布于

2022-03-30

更新于

2023-03-30

许可协议

评论