最近项目中需要校验某个ipv4是否在某个网段中,从网上找到了一些方法,下面做一下总结。
1.通过直接判断的方式,代码如下
public static boolean isInRange(String ip, String cidr) {
String[] ips = ip.split("\\.");
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) {
//掩码位支持1-32
System.out.println(isInRange("1.2.3.9","1.2.3.6/1"));
System.out.println(isInRange("1.2.3.9","1.2.3.6/12"));
System.out.println(isInRange("1.2.3.9","1.2.3.6/29")