1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.handler.codec.socks;
17
18 final class SocksCommonUtils {
19 public static final SocksRequest UNKNOWN_SOCKS_REQUEST = new UnknownSocksRequest();
20 public static final SocksResponse UNKNOWN_SOCKS_RESPONSE = new UnknownSocksResponse();
21
22 private static final int SECOND_ADDRESS_OCTET_SHIFT = 16;
23 private static final int FIRST_ADDRESS_OCTET_SHIFT = 24;
24 private static final int THIRD_ADDRESS_OCTET_SHIFT = 8;
25 private static final int XOR_DEFAULT_VALUE = 0xff;
26
27
28
29
30 private SocksCommonUtils() {
31
32 }
33
34 public static String intToIp(int i) {
35 return String.valueOf(i >> FIRST_ADDRESS_OCTET_SHIFT & XOR_DEFAULT_VALUE) + '.' +
36 (i >> SECOND_ADDRESS_OCTET_SHIFT & XOR_DEFAULT_VALUE) + '.' +
37 (i >> THIRD_ADDRESS_OCTET_SHIFT & XOR_DEFAULT_VALUE) + '.' +
38 (i & XOR_DEFAULT_VALUE);
39 }
40
41 private static final char[] ipv6conseqZeroFiller = {':', ':'};
42 private static final char ipv6hextetSeparator = ':';
43
44
45
46
47
48 public static String ipv6toCompressedForm(byte[] src) {
49 assert src.length == 16;
50
51
52 int cmprHextet = -1;
53
54 int cmprSize = 0;
55 for (int hextet = 0; hextet < 8;) {
56 int curByte = hextet * 2;
57 int size = 0;
58 while (curByte < src.length && src[curByte] == 0
59 && src[curByte + 1] == 0) {
60 curByte += 2;
61 size++;
62 }
63 if (size > cmprSize) {
64 cmprHextet = hextet;
65 cmprSize = size;
66 }
67 hextet = curByte / 2 + 1;
68 }
69 if (cmprHextet == -1 || cmprSize < 2) {
70
71 return ipv6toStr(src);
72 }
73 StringBuilder sb = new StringBuilder(39);
74 ipv6toStr(sb, src, 0, cmprHextet);
75 sb.append(ipv6conseqZeroFiller);
76 ipv6toStr(sb, src, cmprHextet + cmprSize, 8);
77 return sb.toString();
78 }
79
80
81
82
83
84
85
86 public static String ipv6toStr(byte[] src) {
87 assert src.length == 16;
88 StringBuilder sb = new StringBuilder(39);
89 ipv6toStr(sb, src, 0, 8);
90 return sb.toString();
91 }
92
93 private static void ipv6toStr(StringBuilder sb, byte[] src,
94 int fromHextet, int toHextet) {
95 for (int i = fromHextet; i < toHextet; i++) {
96 sb.append(Integer.toHexString(src[i << 1] << 8 & 0xff00
97 | src[(i << 1) + 1] & 0xff));
98 if (i < toHextet - 1) {
99 sb.append(ipv6hextetSeparator);
100 }
101 }
102 }
103 }