IPv6 validation

前端 未结 6 959
抹茶落季
抹茶落季 2021-01-01 22:06

I used IPAddressUtil.isIPv6LiteralAddress (ipAddress) method to validate IPv6, but this method fails for ipv6-address/prefix-length format (format is mentioned

6条回答
  •  爱一瞬间的悲伤
    2021-01-01 22:47

    My idea is to split it into two part, prefix address and prefix len.

    1. validate prefix address use the some regex to validate IPv6 address
    2. validate the prefix len that must be an integer
    3. prefix address can only have ':' s less than the result ofprefix len divided by 16
    4. other logic must be considered as well, leave TODOs here, sorry:(

      private int validateIPv6AddrWithPrefix(String address) {
            int occurCount = 0;
            for(char c : address) {
                if(c=='/'){
                    occurCount++;
                }
            }
            if(occurCount != 1){
             //not good, to much / character
                return -1;
            }
            /* 2nd element should be an integer */
            String[] ss = pool.getAddress().split("/");
            Integer prefixLen = null;
            try{
                prefixLen = Integer.valueOf(ss[1]);
                        // TODO validate the prefix range(1, 128)
    
            }catch(NumberFormatException e) {
                /* not a Integer */
                return -1;
            }
            /* 1st element should be ipv6 address */
            if(!IPaddrUtilities.isIPv6Address(ss[0])) {
                return -1;
            }
            /* validate ':' character logic */
            occurCount = 0;
            for(char c : ss[0].toCharArray()){
                if(c==':') {
                    occurCount++;
                }
            }
            if(occurCount >= prefixLen/16) {
                // to much ':' character
                return -1;
            }
            return 0;
        }
    

提交回复
热议问题