java判断ip是否为指定网段

具体网络知识原理请看这个博文

    /***
     * @param address servletRequest.getRemoteAddr();
     * @param host servletRequest.getRemoteHost();
     * @return
     * Description 检验IP是否符合安全限定
     */
    private  boolean ipIsInNet(String address, String host){
        Set<String> iPset = allowedIP.setAllowedIPValues().getAllowedIP();
        if(iPset.contains(address) || iPset.contains(host)){
            return true;
        }
        String[] ipItems = host.split("\\.");
        if(ipItems.length!=4) return false;
        for(String addr:iPset){
            if(addr.indexOf("/")<0) continue;
            long ipAddress = (Long.parseLong(ipItems[0])<<24)|(Long.parseLong(ipItems[1])<<16)
                    |(Long.parseLong(ipItems[2])<<8)|Long.parseLong(ipItems[3]);
            int type = Integer.parseInt(addr.replaceAll(".*/", ""));
            long mask = 0xFFFFFFFF << (32 - type);
            String cidrIp = addr.replaceAll("/.*", "");
            String[] ipChildItems = cidrIp.split("\\.");
            long childIpAddress = (Long.parseLong(ipChildItems[0])<<24)|(Long.parseLong(ipChildItems[1])<<16)
                    |(Long.parseLong(ipChildItems[2])<<8)|Long.parseLong(ipChildItems[3]);
            if((ipAddress & mask)==(childIpAddress & mask)) return true;
        }
        return false;
    }

你可能感兴趣的:(java,tcp/ip,python)