解析Dhcp Option120

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/caoyuandi/article/details/85283795

    /**
    *    Code   Len   enc            Address 1               Address 2
    *  +--- +----+---+--- +---+ ---+---+----+----------
    *  | 120 |  n    |  1  | a1  | a2  | a3  | a4  | a1   |  ...
    *  +--- +----+---+--- +---+ ---+---+----+----------
    * modify ygcao
    */
    private static String decodeRfc3361(ByteBuffer buf, int byteCount) {
        Log.d(TAG, "decodeRfc3361 byteCount ="+byteCount);
        int[] unsigntbyte = new int[byteCount];
        int [] ipadresses =  new int[byteCount-1]; // remove the enc bit
        int [] dominNames = new int[byteCount-1]; // remove the enc bit
        int enc = -1;
        int ipaddresslength = -1;
        byte[] bytes = new byte[byteCount];
        buf.get(bytes);
        String sipServerIP= new String(bytes,0 ,bytes.length, StandardCharsets.US_ASCII).trim();
        ipaddresslength = bytes.length-1;
        for (int i=0 ; i< bytes.length ; i++) {
            unsigntbyte[i] =bytes[i] & 0xff;
            if (i==0) {
                enc = unsigntbyte[0];//get the rfc3361 enc bit
            } else {
                ipadresses[i-1] = unsigntbyte[i];
                dominNames[i-1] = bytes[i];
            }
        }
        StringBuffer buffer = new StringBuffer();
        Log.d(TAG, "decodeRfc3361 enc = "+enc);
        Log.d(TAG, "decodeRfc3361 ipaddresslength = "+ipaddresslength);
        if (enc ==1) { //RFC for 3361 this is user ipadtress
            for (int i= 0; i < ipadresses.length;i++) {
                if (ipaddresslength % 4 !=0) { // the same dhcp append "0x00" at the end
                   if (i == ipadresses.length-1) {
                        continue;  // remove the last "0x00"
                   }
                }
                buffer.append(ipadresses[i]);
                if ( i%4  != 3) {
                   buffer.append(".");
                } else {
                   buffer.append(" ");
                }
            }
            sipServerIP = buffer.toString();
        } else if (enc ==0) {
           // for do samethings
            int location = 0;
            while (location < dominNames.length) {
                int length = dominNames[location] & 0xff; //
                buffer.append(new String(dominNames, location + 1, length, StandardCharsets.US_ASCII));
                buffer.append(".");
                location = location + length + 1;
            }
            sipServerIP = buffer.toString().substring(0, buffer.toString().length() - 1); //remove the last "."
        }
        Log.d(TAG, "decodeRfc3361 buffer.toString ="+buffer.toString());
        Log.d(TAG, "decodeRfc3361 sipServerIP ="+sipServerIP);
        return sipServerIP;
    }

猜你喜欢

转载自blog.csdn.net/caoyuandi/article/details/85283795
120