All Downloads are FREE. Search and download functionalities are using the official Maven repository.

matrix.boot.common.utils.IpUtil Maven / Gradle / Ivy

There is a newer version: 2.1.11
Show newest version
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;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy