matrix.boot.common.utils.IpUtil Maven / Gradle / Ivy
package matrix.boot.common.utils;
import lombok.extern.slf4j.Slf4j;
/**
* ip工具
*
* @author wangcheng
* date 2022/4/24
*/
@Slf4j
public class IpUtil {
/**
* 是否在范围内
*
* @param ip 例如:127.0.0.1
* @param cidr 例如:192.168.0.1/24
* @return 是否
*/
public static boolean isInRange(String ip, String cidr) {
try {
if ("0.0.0.0/0".equals(cidr)) {
return true;
}
String[] ips = ip.split("\\.");
int ipAddress = (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 cidrIpAddress = (Integer.parseInt(cidrIps[0]) << 24)
| (Integer.parseInt(cidrIps[1]) << 16)
| (Integer.parseInt(cidrIps[2]) << 8)
| (Integer.parseInt(cidrIps[3]));
return (ipAddress & mask) == (cidrIpAddress & mask);
} catch (Exception e) {
if (!StringUtil.isEmpty(cidr) && cidr.equals(ip)) {
//直接相等,放行
return true;
}
log.warn(String.format("ip match error ip:%s cidr:%s", ip, cidr));
return false;
}
}
}