Conversion IPv6 to long and long to IPv6

前端 未结 4 1487
小蘑菇
小蘑菇 2020-12-15 06:53

How should I perform conversion from IPv6 to long and vice versa?

So far I have:

    public static long IPTo         


        
4条回答
  •  孤街浪徒
    2020-12-15 07:08

    Vinod's answer is right. But there are still some things that can be improved.

    First, in method 'countChar', 'continue' should be replaced by 'break'.

    And second, Some boundary conditions must be considered.

    public static BigInteger ipv6ToNumber(String addr) {
        int startIndex = addr.indexOf("::");
        if (startIndex != -1) {
            String firstStr = addr.substring(0, startIndex);
            String secondStr = addr.substring(startIndex + 2, addr.length());
            BigInteger first = new BigInteger("0");
            BigInteger second = new BigInteger("0");
            if (!firstStr.equals("")) {
                int x = countChar(addr, ':');
                first = ipv6ToNumber(firstStr).shiftLeft(16 * (7 - x));
            }
            if (!secondStr.equals("")) {
                second = ipv6ToNumber(secondStr);
            }
            first = first.add(second);
            return first;
        }
    
        String[] strArr = addr.split(":");
        BigInteger retValue = BigInteger.valueOf(0);
        for (int i = 0; i < strArr.length; i++) {
            BigInteger bi = new BigInteger(strArr[i], 16);
            retValue = retValue.shiftLeft(16).add(bi);
        }
        return retValue;
    }
    
    public static int countChar(String str, char reg){
        char[] ch=str.toCharArray();
        int count=0;
        for(int i=0; i

提交回复
热议问题