同时效验ipv4和cidr ip的方法

以下代码已经过工业级效验,已满足我厂应用的需要。如有问题,可于我留言,谢谢。

代码块
    /**
     * 将ipv4转为32 bit. 返回结果cidr的二个部分
     * 
     * @param ip
     * @return
     * @throws IPv4Exception
     */
    public static int[] convert2Bit32(String ip) throws IPv4Exception {
        int[] result = { 0, NULL_NET };
        String[] cidr = ip.split("\\/" , -1);
        if (cidr.length > 2 || cidr.length == 0) {
            throw new IPv4Exception("Invalid IPv4 " + ip);
        } else if (cidr.length == 2) {
            if (!isPositive(cidr[1])) {
                throw new IPv4Exception("Invalid IPv4 " + ip);
            }
            result[1] = Integer.parseInt(cidr[1]);
            if (result[1] < 0 || result[1] > 32) {
                throw new IPv4Exception("Invalid IPv4 " + ip);
            } else if (result[1] == 0 && !"0.0.0.0".equals(cidr[0])) {
                throw new IPv4Exception("Invalid IPv4 " + ip);
            }
        }
        String[] addr = cidr[0].split("\\." , -1);
        if (addr.length != 4) {
            throw new IPv4Exception("Invalid IPv4 " + ip);
        }
        for (String f : addr) {
            if (!isPositive(f)) {
                throw new IPv4Exception("Invalid IPv4 " + ip);
            }
            int n = Integer.parseInt(f);
            if (n < 0 || n > 255) {
                throw new IPv4Exception("Invalid IPv4 " + ip);
            }
            result[0] = (result[0] << 8) | n;
        }
        return result;



    private static boolean isPositive(String val) {
        if (val == null || val.length() == 0) {
            return false;
        }
        int n = val.length();
        if (n == 0 || n > 3) {  //此处可以不加限制,即127.0.0.00001也是正确ip
            return false;
        }
        for (int i = 0; i < n; i++) {
            if (!Character.isDigit(val.charAt(i))) {
                return false;
            }
        }
        return true;
    }  
    }

注意:

  • 效验方法 :请调用convert2Bit32方法完成效验
  • split :使用split(String regex,int limit),将limit设置为-1,来防止split将分割后的字符串结尾空字符串丢弃。这样就消除了出现将“127.0.0.1.”效验为正确的bug。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值