View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.util;
17  
18  import io.netty.util.internal.PlatformDependent;
19  import io.netty.util.internal.SocketUtils;
20  import io.netty.util.internal.StringUtil;
21  import io.netty.util.internal.SystemPropertyUtil;
22  import io.netty.util.internal.logging.InternalLogger;
23  import io.netty.util.internal.logging.InternalLoggerFactory;
24  
25  import java.io.BufferedReader;
26  import java.io.File;
27  import java.io.FileReader;
28  import java.io.IOException;
29  import java.io.InputStream;
30  import java.io.InputStreamReader;
31  import java.net.Inet4Address;
32  import java.net.Inet6Address;
33  import java.net.InetAddress;
34  import java.net.InetSocketAddress;
35  import java.net.NetworkInterface;
36  import java.net.SocketException;
37  import java.net.UnknownHostException;
38  import java.security.AccessController;
39  import java.security.PrivilegedAction;
40  import java.util.ArrayList;
41  import java.util.Enumeration;
42  import java.util.List;
43  
44  import static io.netty.util.AsciiString.indexOf;
45  
46  /**
47   * A class that holds a number of network-related constants.
48   * <p/>
49   * This class borrowed some of its methods from a  modified fork of the
50   * <a href="http://svn.apache.org/repos/asf/harmony/enhanced/java/branches/java6/classlib/modules/luni/
51   * src/main/java/org/apache/harmony/luni/util/Inet6Util.java">Inet6Util class</a> which was part of Apache Harmony.
52   */
53  public final class NetUtil {
54  
55      /**
56       * The {@link Inet4Address} that represents the IPv4 loopback address '127.0.0.1'
57       */
58      public static final Inet4Address LOCALHOST4;
59  
60      /**
61       * The {@link Inet6Address} that represents the IPv6 loopback address '::1'
62       */
63      public static final Inet6Address LOCALHOST6;
64  
65      /**
66       * The {@link InetAddress} that represents the loopback address. If IPv6 stack is available, it will refer to
67       * {@link #LOCALHOST6}.  Otherwise, {@link #LOCALHOST4}.
68       */
69      public static final InetAddress LOCALHOST;
70  
71      /**
72       * The loopback {@link NetworkInterface} of the current machine
73       */
74      public static final NetworkInterface LOOPBACK_IF;
75  
76      /**
77       * The SOMAXCONN value of the current machine.  If failed to get the value,  {@code 200}  is used as a
78       * default value for Windows or {@code 128} for others.
79       */
80      public static final int SOMAXCONN;
81  
82      /**
83       * This defines how many words (represented as ints) are needed to represent an IPv6 address
84       */
85      private static final int IPV6_WORD_COUNT = 8;
86  
87      /**
88       * The maximum number of characters for an IPV6 string with no scope
89       */
90      private static final int IPV6_MAX_CHAR_COUNT = 39;
91  
92      /**
93       * Number of bytes needed to represent and IPV6 value
94       */
95      private static final int IPV6_BYTE_COUNT = 16;
96  
97      /**
98       * Maximum amount of value adding characters in between IPV6 separators
99       */
100     private static final int IPV6_MAX_CHAR_BETWEEN_SEPARATOR = 4;
101 
102     /**
103      * Minimum number of separators that must be present in an IPv6 string
104      */
105     private static final int IPV6_MIN_SEPARATORS = 2;
106 
107     /**
108      * Maximum number of separators that must be present in an IPv6 string
109      */
110     private static final int IPV6_MAX_SEPARATORS = 8;
111 
112     /**
113      * Maximum amount of value adding characters in between IPV4 separators
114      */
115     private static final int IPV4_MAX_CHAR_BETWEEN_SEPARATOR = 3;
116 
117     /**
118      * Number of separators that must be present in an IPv4 string
119      */
120     private static final int IPV4_SEPARATORS = 3;
121 
122     /**
123      * {@code true} if IPv4 should be used even if the system supports both IPv4 and IPv6.
124      */
125     private static final boolean IPV4_PREFERRED = SystemPropertyUtil.getBoolean("java.net.preferIPv4Stack", false);
126 
127     /**
128      * {@code true} if an IPv6 address should be preferred when a host has both an IPv4 address and an IPv6 address.
129      */
130     private static final boolean IPV6_ADDRESSES_PREFERRED =
131             SystemPropertyUtil.getBoolean("java.net.preferIPv6Addresses", false);
132 
133     /**
134      * The logger being used by this class
135      */
136     private static final InternalLogger logger = InternalLoggerFactory.getInstance(NetUtil.class);
137 
138     static {
139         logger.debug("-Djava.net.preferIPv4Stack: {}", IPV4_PREFERRED);
140         logger.debug("-Djava.net.preferIPv6Addresses: {}", IPV6_ADDRESSES_PREFERRED);
141 
142         byte[] LOCALHOST4_BYTES = {127, 0, 0, 1};
143         byte[] LOCALHOST6_BYTES = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
144 
145         // Create IPv4 loopback address.
146         Inet4Address localhost4 = null;
147         try {
148             localhost4 = (Inet4Address) InetAddress.getByAddress("localhost", LOCALHOST4_BYTES);
149         } catch (Exception e) {
150             // We should not get here as long as the length of the address is correct.
151             PlatformDependent.throwException(e);
152         }
153         LOCALHOST4 = localhost4;
154 
155         // Create IPv6 loopback address.
156         Inet6Address localhost6 = null;
157         try {
158             localhost6 = (Inet6Address) InetAddress.getByAddress("localhost", LOCALHOST6_BYTES);
159         } catch (Exception e) {
160             // We should not get here as long as the length of the address is correct.
161             PlatformDependent.throwException(e);
162         }
163         LOCALHOST6 = localhost6;
164 
165         // Retrieve the list of available network interfaces.
166         List<NetworkInterface> ifaces = new ArrayList<NetworkInterface>();
167         try {
168             Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
169             if (interfaces != null) {
170                 while (interfaces.hasMoreElements()) {
171                     NetworkInterface iface = interfaces.nextElement();
172                     // Use the interface with proper INET addresses only.
173                     if (SocketUtils.addressesFromNetworkInterface(iface).hasMoreElements()) {
174                         ifaces.add(iface);
175                     }
176                 }
177             }
178         } catch (SocketException e) {
179             logger.warn("Failed to retrieve the list of available network interfaces", e);
180         }
181 
182         // Find the first loopback interface available from its INET address (127.0.0.1 or ::1)
183         // Note that we do not use NetworkInterface.isLoopback() in the first place because it takes long time
184         // on a certain environment. (e.g. Windows with -Djava.net.preferIPv4Stack=true)
185         NetworkInterface loopbackIface = null;
186         InetAddress loopbackAddr = null;
187         loop: for (NetworkInterface iface: ifaces) {
188             for (Enumeration<InetAddress> i = SocketUtils.addressesFromNetworkInterface(iface); i.hasMoreElements();) {
189                 InetAddress addr = i.nextElement();
190                 if (addr.isLoopbackAddress()) {
191                     // Found
192                     loopbackIface = iface;
193                     loopbackAddr = addr;
194                     break loop;
195                 }
196             }
197         }
198 
199         // If failed to find the loopback interface from its INET address, fall back to isLoopback().
200         if (loopbackIface == null) {
201             try {
202                 for (NetworkInterface iface: ifaces) {
203                     if (iface.isLoopback()) {
204                         Enumeration<InetAddress> i = SocketUtils.addressesFromNetworkInterface(iface);
205                         if (i.hasMoreElements()) {
206                             // Found the one with INET address.
207                             loopbackIface = iface;
208                             loopbackAddr = i.nextElement();
209                             break;
210                         }
211                     }
212                 }
213 
214                 if (loopbackIface == null) {
215                     logger.warn("Failed to find the loopback interface");
216                 }
217             } catch (SocketException e) {
218                 logger.warn("Failed to find the loopback interface", e);
219             }
220         }
221 
222         if (loopbackIface != null) {
223             // Found the loopback interface with an INET address.
224             logger.debug(
225                     "Loopback interface: {} ({}, {})",
226                     loopbackIface.getName(), loopbackIface.getDisplayName(), loopbackAddr.getHostAddress());
227         } else {
228             // Could not find the loopback interface, but we can't leave LOCALHOST as null.
229             // Use LOCALHOST6 or LOCALHOST4, preferably the IPv6 one.
230             if (loopbackAddr == null) {
231                 try {
232                     if (NetworkInterface.getByInetAddress(LOCALHOST6) != null) {
233                         logger.debug("Using hard-coded IPv6 localhost address: {}", localhost6);
234                         loopbackAddr = localhost6;
235                     }
236                 } catch (Exception e) {
237                     // Ignore
238                 } finally {
239                     if (loopbackAddr == null) {
240                         logger.debug("Using hard-coded IPv4 localhost address: {}", localhost4);
241                         loopbackAddr = localhost4;
242                     }
243                 }
244             }
245         }
246 
247         LOOPBACK_IF = loopbackIface;
248         LOCALHOST = loopbackAddr;
249 
250         // As a SecurityManager may prevent reading the somaxconn file we wrap this in a privileged block.
251         //
252         // See https://github.com/netty/netty/issues/3680
253         SOMAXCONN = AccessController.doPrivileged(new PrivilegedAction<Integer>() {
254             @Override
255             public Integer run() {
256                 // Determine the default somaxconn (server socket backlog) value of the platform.
257                 // The known defaults:
258                 // - Windows NT Server 4.0+: 200
259                 // - Linux and Mac OS X: 128
260                 int somaxconn = PlatformDependent.isWindows() ? 200 : 128;
261                 File file = new File("/proc/sys/net/core/somaxconn");
262                 BufferedReader in = null;
263                 try {
264                     // file.exists() may throw a SecurityException if a SecurityManager is used, so execute it in the
265                     // try / catch block.
266                     // See https://github.com/netty/netty/issues/4936
267                     if (file.exists()) {
268                         in = new BufferedReader(new FileReader(file));
269                         somaxconn = Integer.parseInt(in.readLine());
270                         if (logger.isDebugEnabled()) {
271                             logger.debug("{}: {}", file, somaxconn);
272                         }
273                     } else {
274                         // Try to get from sysctl
275                         Integer tmp = null;
276                         if (SystemPropertyUtil.getBoolean("io.netty.net.somaxconn.trySysctl", false)) {
277                             tmp = sysctlGetInt("kern.ipc.somaxconn");
278                             if (tmp == null) {
279                                 tmp = sysctlGetInt("kern.ipc.soacceptqueue");
280                                 if (tmp != null) {
281                                     somaxconn = tmp;
282                                 }
283                             } else {
284                                 somaxconn = tmp;
285                             }
286                         }
287 
288                         if (tmp == null) {
289                             logger.debug("Failed to get SOMAXCONN from sysctl and file {}. Default: {}", file,
290                                          somaxconn);
291                         }
292                     }
293                 } catch (Exception e) {
294                     logger.debug("Failed to get SOMAXCONN from sysctl and file {}. Default: {}", file, somaxconn, e);
295                 } finally {
296                     if (in != null) {
297                         try {
298                             in.close();
299                         } catch (Exception e) {
300                             // Ignored.
301                         }
302                     }
303                 }
304                 return somaxconn;
305             }
306         });
307     }
308 
309     /**
310      * This will execute <a href ="https://www.freebsd.org/cgi/man.cgi?sysctl(8)">sysctl</a> with the {@code sysctlKey}
311      * which is expected to return the numeric value for for {@code sysctlKey}.
312      * @param sysctlKey The key which the return value corresponds to.
313      * @return The <a href ="https://www.freebsd.org/cgi/man.cgi?sysctl(8)">sysctl</a> value for {@code sysctlKey}.
314      */
315     private static Integer sysctlGetInt(String sysctlKey) throws IOException {
316         Process process = new ProcessBuilder("sysctl", sysctlKey).start();
317         try {
318             InputStream is = process.getInputStream();
319             InputStreamReader isr = new InputStreamReader(is);
320             BufferedReader br = new BufferedReader(isr);
321             try {
322                 String line = br.readLine();
323                 if (line.startsWith(sysctlKey)) {
324                     for (int i = line.length() - 1; i > sysctlKey.length(); --i) {
325                         if (!Character.isDigit(line.charAt(i))) {
326                             return Integer.valueOf(line.substring(i + 1, line.length()));
327                         }
328                     }
329                 }
330                 return null;
331             } finally {
332                 br.close();
333             }
334         } finally {
335             if (process != null) {
336                 process.destroy();
337             }
338         }
339     }
340 
341     /**
342      * Returns {@code true} if IPv4 should be used even if the system supports both IPv4 and IPv6. Setting this
343      * property to {@code true} will disable IPv6 support. The default value of this property is {@code false}.
344      *
345      * @see <a href="https://docs.oracle.com/javase/8/docs/api/java/net/doc-files/net-properties.html">Java SE
346      *      networking properties</a>
347      */
348     public static boolean isIpV4StackPreferred() {
349         return IPV4_PREFERRED;
350     }
351 
352     /**
353      * Returns {@code true} if an IPv6 address should be preferred when a host has both an IPv4 address and an IPv6
354      * address. The default value of this property is {@code false}.
355      *
356      * @see <a href="https://docs.oracle.com/javase/8/docs/api/java/net/doc-files/net-properties.html">Java SE
357      *      networking properties</a>
358      */
359     public static boolean isIpV6AddressesPreferred() {
360         return IPV6_ADDRESSES_PREFERRED;
361     }
362 
363     /**
364      * Creates an byte[] based on an ipAddressString. No error handling is performed here.
365      */
366     public static byte[] createByteArrayFromIpAddressString(String ipAddressString) {
367 
368         if (isValidIpV4Address(ipAddressString)) {
369             return validIpV4ToBytes(ipAddressString);
370         }
371 
372         if (isValidIpV6Address(ipAddressString)) {
373             if (ipAddressString.charAt(0) == '[') {
374                 ipAddressString = ipAddressString.substring(1, ipAddressString.length() - 1);
375             }
376 
377             int percentPos = ipAddressString.indexOf('%');
378             if (percentPos >= 0) {
379                 ipAddressString = ipAddressString.substring(0, percentPos);
380             }
381 
382             return getIPv6ByName(ipAddressString, true);
383         }
384         return null;
385     }
386 
387     private static int decimalDigit(String str, int pos) {
388         return str.charAt(pos) - '0';
389     }
390 
391     private static byte ipv4WordToByte(String ip, int from, int toExclusive) {
392         int ret = decimalDigit(ip, from);
393         from++;
394         if (from == toExclusive) {
395             return (byte) ret;
396         }
397         ret = ret * 10 + decimalDigit(ip, from);
398         from++;
399         if (from == toExclusive) {
400             return (byte) ret;
401         }
402         return (byte) (ret * 10 + decimalDigit(ip, from));
403     }
404 
405     // visible for tests
406     static byte[] validIpV4ToBytes(String ip) {
407         int i;
408         return new byte[] {
409                 ipv4WordToByte(ip, 0, i = ip.indexOf('.', 1)),
410                 ipv4WordToByte(ip, i + 1, i = ip.indexOf('.', i + 2)),
411                 ipv4WordToByte(ip, i + 1, i = ip.indexOf('.', i + 2)),
412                 ipv4WordToByte(ip, i + 1, ip.length())
413         };
414     }
415 
416     /**
417      * Converts a 32-bit integer into an IPv4 address.
418      */
419     public static String intToIpAddress(int i) {
420         StringBuilder buf = new StringBuilder(15);
421         buf.append(i >> 24 & 0xff);
422         buf.append('.');
423         buf.append(i >> 16 & 0xff);
424         buf.append('.');
425         buf.append(i >> 8 & 0xff);
426         buf.append('.');
427         buf.append(i & 0xff);
428         return buf.toString();
429     }
430 
431     /**
432      * Converts 4-byte or 16-byte data into an IPv4 or IPv6 string respectively.
433      *
434      * @throws IllegalArgumentException
435      *         if {@code length} is not {@code 4} nor {@code 16}
436      */
437     public static String bytesToIpAddress(byte[] bytes) {
438         return bytesToIpAddress(bytes, 0, bytes.length);
439     }
440 
441     /**
442      * Converts 4-byte or 16-byte data into an IPv4 or IPv6 string respectively.
443      *
444      * @throws IllegalArgumentException
445      *         if {@code length} is not {@code 4} nor {@code 16}
446      */
447     public static String bytesToIpAddress(byte[] bytes, int offset, int length) {
448         switch (length) {
449             case 4: {
450                 return new StringBuilder(15)
451                         .append(bytes[offset] & 0xff)
452                         .append('.')
453                         .append(bytes[offset + 1] & 0xff)
454                         .append('.')
455                         .append(bytes[offset + 2] & 0xff)
456                         .append('.')
457                         .append(bytes[offset + 3] & 0xff).toString();
458             }
459             case 16:
460                 return toAddressString(bytes, offset, false);
461             default:
462                 throw new IllegalArgumentException("length: " + length + " (expected: 4 or 16)");
463         }
464     }
465 
466     public static boolean isValidIpV6Address(String ip) {
467         return isValidIpV6Address((CharSequence) ip);
468     }
469 
470     public static boolean isValidIpV6Address(CharSequence ip) {
471         int end = ip.length();
472         if (end < 2) {
473             return false;
474         }
475 
476         // strip "[]"
477         int start;
478         char c = ip.charAt(0);
479         if (c == '[') {
480             end--;
481             if (ip.charAt(end) != ']') {
482                 // must have a close ]
483                 return false;
484             }
485             start = 1;
486             c = ip.charAt(1);
487         } else {
488             start = 0;
489         }
490 
491         int colons;
492         int compressBegin;
493         if (c == ':') {
494             // an IPv6 address can start with "::" or with a number
495             if (ip.charAt(start + 1) != ':') {
496                 return false;
497             }
498             colons = 2;
499             compressBegin = start;
500             start += 2;
501         } else {
502             colons = 0;
503             compressBegin = -1;
504         }
505 
506         int wordLen = 0;
507         loop:
508         for (int i = start; i < end; i++) {
509             c = ip.charAt(i);
510             if (isValidHexChar(c)) {
511                 if (wordLen < 4) {
512                     wordLen++;
513                     continue;
514                 }
515                 return false;
516             }
517 
518             switch (c) {
519             case ':':
520                 if (colons > 7) {
521                     return false;
522                 }
523                 if (ip.charAt(i - 1) == ':') {
524                     if (compressBegin >= 0) {
525                         return false;
526                     }
527                     compressBegin = i - 1;
528                 } else {
529                     wordLen = 0;
530                 }
531                 colons++;
532                 break;
533             case '.':
534                 // case for the last 32-bits represented as IPv4 x:x:x:x:x:x:d.d.d.d
535 
536                 // check a normal case (6 single colons)
537                 if (compressBegin < 0 && colons != 6 ||
538                     // a special case ::1:2:3:4:5:d.d.d.d allows 7 colons with an
539                     // IPv4 ending, otherwise 7 :'s is bad
540                     (colons == 7 && compressBegin >= start || colons > 7)) {
541                     return false;
542                 }
543 
544                 // Verify this address is of the correct structure to contain an IPv4 address.
545                 // It must be IPv4-Mapped or IPv4-Compatible
546                 // (see https://tools.ietf.org/html/rfc4291#section-2.5.5).
547                 int ipv4Start = i - wordLen;
548                 int j = ipv4Start - 2; // index of character before the previous ':'.
549                 if (isValidIPv4MappedChar(ip.charAt(j))) {
550                     if (!isValidIPv4MappedChar(ip.charAt(j - 1)) ||
551                         !isValidIPv4MappedChar(ip.charAt(j - 2)) ||
552                         !isValidIPv4MappedChar(ip.charAt(j - 3))) {
553                         return false;
554                     }
555                     j -= 5;
556                 }
557 
558                 for (; j >= start; --j) {
559                     char tmpChar = ip.charAt(j);
560                     if (tmpChar != '0' && tmpChar != ':') {
561                         return false;
562                     }
563                 }
564 
565                 // 7 - is minimum IPv4 address length
566                 int ipv4End = indexOf(ip, '%', ipv4Start + 7);
567                 if (ipv4End < 0) {
568                     ipv4End = end;
569                 }
570                 return isValidIpV4Address(ip, ipv4Start, ipv4End);
571             case '%':
572                 // strip the interface name/index after the percent sign
573                 end = i;
574                 break loop;
575             default:
576                 return false;
577             }
578         }
579 
580         // normal case without compression
581         if (compressBegin < 0) {
582             return colons == 7 && wordLen > 0;
583         }
584 
585         return compressBegin + 2 == end ||
586                // 8 colons is valid only if compression in start or end
587                wordLen > 0 && (colons < 8 || compressBegin <= start);
588     }
589 
590     private static boolean isValidIpV4Word(CharSequence word, int from, int toExclusive) {
591         int len = toExclusive - from;
592         char c0, c1, c2;
593         if (len < 1 || len > 3 || (c0 = word.charAt(from)) < '0') {
594             return false;
595         }
596         if (len == 3) {
597             return (c1 = word.charAt(from + 1)) >= '0' &&
598                    (c2 = word.charAt(from + 2)) >= '0' &&
599                    (c0 <= '1' && c1 <= '9' && c2 <= '9' ||
600                     c0 == '2' && c1 <= '5' && (c2 <= '5' || c1 < '5' && c2 <= '9'));
601         }
602         return c0 <= '9' && (len == 1 || isValidNumericChar(word.charAt(from + 1)));
603     }
604 
605     private static boolean isValidHexChar(char c) {
606         return c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f';
607     }
608 
609     private static boolean isValidNumericChar(char c) {
610         return c >= '0' && c <= '9';
611     }
612 
613     private static boolean isValidIPv4MappedChar(char c) {
614         return c == 'f' || c == 'F';
615     }
616 
617     private static boolean isValidIPv4MappedSeparators(byte b0, byte b1, boolean mustBeZero) {
618         // We allow IPv4 Mapped (https://tools.ietf.org/html/rfc4291#section-2.5.5.1)
619         // and IPv4 compatible (https://tools.ietf.org/html/rfc4291#section-2.5.5.1).
620         // The IPv4 compatible is deprecated, but it allows parsing of plain IPv4 addressed into IPv6-Mapped addresses.
621         return b0 == b1 && (b0 == 0 || !mustBeZero && b1 == -1);
622     }
623 
624     private static boolean isValidIPv4Mapped(byte[] bytes, int currentIndex, int compressBegin, int compressLength) {
625         final boolean mustBeZero = compressBegin + compressLength >= 14;
626         return currentIndex <= 12 && currentIndex >= 2 && (!mustBeZero || compressBegin < 12) &&
627                 isValidIPv4MappedSeparators(bytes[currentIndex - 1], bytes[currentIndex - 2], mustBeZero) &&
628                 PlatformDependent.isZero(bytes, 0, currentIndex - 3);
629     }
630 
631     /**
632      * Takes a {@link CharSequence} and parses it to see if it is a valid IPV4 address.
633      *
634      * @return true, if the string represents an IPV4 address in dotted
635      *         notation, false otherwise
636      */
637     public static boolean isValidIpV4Address(CharSequence ip) {
638         return isValidIpV4Address(ip, 0, ip.length());
639     }
640 
641     /**
642      * Takes a {@link String} and parses it to see if it is a valid IPV4 address.
643      *
644      * @return true, if the string represents an IPV4 address in dotted
645      *         notation, false otherwise
646      */
647     public static boolean isValidIpV4Address(String ip) {
648         return isValidIpV4Address(ip, 0, ip.length());
649     }
650 
651     private static boolean isValidIpV4Address(CharSequence ip, int from, int toExcluded) {
652         return ip instanceof String ? isValidIpV4Address((String) ip, from, toExcluded) :
653                 ip instanceof AsciiString ? isValidIpV4Address((AsciiString) ip, from, toExcluded) :
654                         isValidIpV4Address0(ip, from, toExcluded);
655     }
656 
657     @SuppressWarnings("DuplicateBooleanBranch")
658     private static boolean isValidIpV4Address(String ip, int from, int toExcluded) {
659         int len = toExcluded - from;
660         int i;
661         return len <= 15 && len >= 7 &&
662                 (i = ip.indexOf('.', from + 1)) > 0 && isValidIpV4Word(ip, from, i) &&
663                 (i =  ip.indexOf('.', from = i + 2)) > 0 && isValidIpV4Word(ip, from - 1, i) &&
664                 (i =  ip.indexOf('.', from = i + 2)) > 0 && isValidIpV4Word(ip, from - 1, i) &&
665                 isValidIpV4Word(ip, i + 1, toExcluded);
666     }
667 
668     @SuppressWarnings("DuplicateBooleanBranch")
669     private static boolean isValidIpV4Address(AsciiString ip, int from, int toExcluded) {
670         int len = toExcluded - from;
671         int i;
672         return len <= 15 && len >= 7 &&
673                 (i = ip.indexOf('.', from + 1)) > 0 && isValidIpV4Word(ip, from, i) &&
674                 (i =  ip.indexOf('.', from = i + 2)) > 0 && isValidIpV4Word(ip, from - 1, i) &&
675                 (i =  ip.indexOf('.', from = i + 2)) > 0 && isValidIpV4Word(ip, from - 1, i) &&
676                 isValidIpV4Word(ip, i + 1, toExcluded);
677     }
678 
679     @SuppressWarnings("DuplicateBooleanBranch")
680     private static boolean isValidIpV4Address0(CharSequence ip, int from, int toExcluded) {
681         int len = toExcluded - from;
682         int i;
683         return len <= 15 && len >= 7 &&
684                 (i = indexOf(ip, '.', from + 1)) > 0 && isValidIpV4Word(ip, from, i) &&
685                 (i =  indexOf(ip, '.', from = i + 2)) > 0 && isValidIpV4Word(ip, from - 1, i) &&
686                 (i =  indexOf(ip, '.', from = i + 2)) > 0 && isValidIpV4Word(ip, from - 1, i) &&
687                 isValidIpV4Word(ip, i + 1, toExcluded);
688     }
689 
690     /**
691      * Returns the {@link Inet6Address} representation of a {@link CharSequence} IP address.
692      * <p>
693      * This method will treat all IPv4 type addresses as "IPv4 mapped" (see {@link #getByName(CharSequence, boolean)})
694      * @param ip {@link CharSequence} IP address to be converted to a {@link Inet6Address}
695      * @return {@link Inet6Address} representation of the {@code ip} or {@code null} if not a valid IP address.
696      */
697     public static Inet6Address getByName(CharSequence ip) {
698         return getByName(ip, true);
699     }
700 
701     /**
702      * Returns the {@link Inet6Address} representation of a {@link CharSequence} IP address.
703      * <p>
704      * The {@code ipv4Mapped} parameter specifies how IPv4 addresses should be treated.
705      * "IPv4 mapped" format as
706      * defined in <a href="http://tools.ietf.org/html/rfc4291#section-2.5.5">rfc 4291 section 2</a> is supported.
707      * @param ip {@link CharSequence} IP address to be converted to a {@link Inet6Address}
708      * @param ipv4Mapped
709      * <ul>
710      * <li>{@code true} To allow IPv4 mapped inputs to be translated into {@link Inet6Address}</li>
711      * <li>{@code false} Consider IPv4 mapped addresses as invalid.</li>
712      * </ul>
713      * @return {@link Inet6Address} representation of the {@code ip} or {@code null} if not a valid IP address.
714      */
715     public static Inet6Address getByName(CharSequence ip, boolean ipv4Mapped) {
716         byte[] bytes = getIPv6ByName(ip, ipv4Mapped);
717         if (bytes == null) {
718             return null;
719         }
720         try {
721             return Inet6Address.getByAddress(null, bytes, -1);
722         } catch (UnknownHostException e) {
723             throw new RuntimeException(e); // Should never happen
724         }
725     }
726 
727     /**
728      * Returns the byte array representation of a {@link CharSequence} IP address.
729      * <p>
730      * The {@code ipv4Mapped} parameter specifies how IPv4 addresses should be treated.
731      * "IPv4 mapped" format as
732      * defined in <a href="http://tools.ietf.org/html/rfc4291#section-2.5.5">rfc 4291 section 2</a> is supported.
733      * @param ip {@link CharSequence} IP address to be converted to a {@link Inet6Address}
734      * @param ipv4Mapped
735      * <ul>
736      * <li>{@code true} To allow IPv4 mapped inputs to be translated into {@link Inet6Address}</li>
737      * <li>{@code false} Consider IPv4 mapped addresses as invalid.</li>
738      * </ul>
739      * @return byte array representation of the {@code ip} or {@code null} if not a valid IP address.
740      */
741     private static byte[] getIPv6ByName(CharSequence ip, boolean ipv4Mapped) {
742         final byte[] bytes = new byte[IPV6_BYTE_COUNT];
743         final int ipLength = ip.length();
744         int compressBegin = 0;
745         int compressLength = 0;
746         int currentIndex = 0;
747         int value = 0;
748         int begin = -1;
749         int i = 0;
750         int ipv6Separators = 0;
751         int ipv4Separators = 0;
752         int tmp;
753         boolean needsShift = false;
754         for (; i < ipLength; ++i) {
755             final char c = ip.charAt(i);
756             switch (c) {
757             case ':':
758                 ++ipv6Separators;
759                 if (i - begin > IPV6_MAX_CHAR_BETWEEN_SEPARATOR ||
760                         ipv4Separators > 0 || ipv6Separators > IPV6_MAX_SEPARATORS ||
761                         currentIndex + 1 >= bytes.length) {
762                     return null;
763                 }
764                 value <<= (IPV6_MAX_CHAR_BETWEEN_SEPARATOR - (i - begin)) << 2;
765 
766                 if (compressLength > 0) {
767                     compressLength -= 2;
768                 }
769 
770                 // The value integer holds at most 4 bytes from right (most significant) to left (least significant).
771                 // The following bit shifting is used to extract and re-order the individual bytes to achieve a
772                 // left (most significant) to right (least significant) ordering.
773                 bytes[currentIndex++] = (byte) (((value & 0xf) << 4) | ((value >> 4) & 0xf));
774                 bytes[currentIndex++] = (byte) ((((value >> 8) & 0xf) << 4) | ((value >> 12) & 0xf));
775                 tmp = i + 1;
776                 if (tmp < ipLength && ip.charAt(tmp) == ':') {
777                     ++tmp;
778                     if (compressBegin != 0 || (tmp < ipLength && ip.charAt(tmp) == ':')) {
779                         return null;
780                     }
781                     ++ipv6Separators;
782                     needsShift = ipv6Separators == 2 && value == 0;
783                     compressBegin = currentIndex;
784                     compressLength = bytes.length - compressBegin - 2;
785                     ++i;
786                 }
787                 value = 0;
788                 begin = -1;
789                 break;
790             case '.':
791                 ++ipv4Separators;
792                 tmp = i - begin; // tmp is the length of the current segment.
793                 if (tmp > IPV4_MAX_CHAR_BETWEEN_SEPARATOR
794                         || begin < 0
795                         || ipv4Separators > IPV4_SEPARATORS
796                         || (ipv6Separators > 0 && (currentIndex + compressLength < 12))
797                         || i + 1 >= ipLength
798                         || currentIndex >= bytes.length
799                         || ipv4Separators == 1 &&
800                             // We also parse pure IPv4 addresses as IPv4-Mapped for ease of use.
801                             ((!ipv4Mapped || currentIndex != 0 && !isValidIPv4Mapped(bytes, currentIndex,
802                                                                                      compressBegin, compressLength)) ||
803                                 (tmp == 3 && (!isValidNumericChar(ip.charAt(i - 1)) ||
804                                               !isValidNumericChar(ip.charAt(i - 2)) ||
805                                               !isValidNumericChar(ip.charAt(i - 3))) ||
806                                  tmp == 2 && (!isValidNumericChar(ip.charAt(i - 1)) ||
807                                               !isValidNumericChar(ip.charAt(i - 2))) ||
808                                  tmp == 1 && !isValidNumericChar(ip.charAt(i - 1))))) {
809                     return null;
810                 }
811                 value <<= (IPV4_MAX_CHAR_BETWEEN_SEPARATOR - tmp) << 2;
812 
813                 // The value integer holds at most 3 bytes from right (most significant) to left (least significant).
814                 // The following bit shifting is to restructure the bytes to be left (most significant) to
815                 // right (least significant) while also accounting for each IPv4 digit is base 10.
816                 begin = (value & 0xf) * 100 + ((value >> 4) & 0xf) * 10 + ((value >> 8) & 0xf);
817                 if (begin < 0 || begin > 255) {
818                     return null;
819                 }
820                 bytes[currentIndex++] = (byte) begin;
821                 value = 0;
822                 begin = -1;
823                 break;
824             default:
825                 if (!isValidHexChar(c) || (ipv4Separators > 0 && !isValidNumericChar(c))) {
826                     return null;
827                 }
828                 if (begin < 0) {
829                     begin = i;
830                 } else if (i - begin > IPV6_MAX_CHAR_BETWEEN_SEPARATOR) {
831                     return null;
832                 }
833                 // The value is treated as a sort of array of numbers because we are dealing with
834                 // at most 4 consecutive bytes we can use bit shifting to accomplish this.
835                 // The most significant byte will be encountered first, and reside in the right most
836                 // position of the following integer
837                 value += StringUtil.decodeHexNibble(c) << ((i - begin) << 2);
838                 break;
839             }
840         }
841 
842         final boolean isCompressed = compressBegin > 0;
843         // Finish up last set of data that was accumulated in the loop (or before the loop)
844         if (ipv4Separators > 0) {
845             if (begin > 0 && i - begin > IPV4_MAX_CHAR_BETWEEN_SEPARATOR ||
846                     ipv4Separators != IPV4_SEPARATORS ||
847                     currentIndex >= bytes.length) {
848                 return null;
849             }
850             if (ipv6Separators == 0) {
851                 compressLength = 12;
852             } else if (ipv6Separators >= IPV6_MIN_SEPARATORS &&
853                            (!isCompressed && (ipv6Separators == 6 && ip.charAt(0) != ':') ||
854                             isCompressed && (ipv6Separators < IPV6_MAX_SEPARATORS &&
855                                              (ip.charAt(0) != ':' || compressBegin <= 2)))) {
856                 compressLength -= 2;
857             } else {
858                 return null;
859             }
860             value <<= (IPV4_MAX_CHAR_BETWEEN_SEPARATOR - (i - begin)) << 2;
861 
862             // The value integer holds at most 3 bytes from right (most significant) to left (least significant).
863             // The following bit shifting is to restructure the bytes to be left (most significant) to
864             // right (least significant) while also accounting for each IPv4 digit is base 10.
865             begin = (value & 0xf) * 100 + ((value >> 4) & 0xf) * 10 + ((value >> 8) & 0xf);
866             if (begin < 0 || begin > 255) {
867                 return null;
868             }
869             bytes[currentIndex++] = (byte) begin;
870         } else {
871             tmp = ipLength - 1;
872             if (begin > 0 && i - begin > IPV6_MAX_CHAR_BETWEEN_SEPARATOR ||
873                     ipv6Separators < IPV6_MIN_SEPARATORS ||
874                     !isCompressed && (ipv6Separators + 1 != IPV6_MAX_SEPARATORS  ||
875                                       ip.charAt(0) == ':' || ip.charAt(tmp) == ':') ||
876                     isCompressed && (ipv6Separators > IPV6_MAX_SEPARATORS ||
877                         (ipv6Separators == IPV6_MAX_SEPARATORS &&
878                           (compressBegin <= 2 && ip.charAt(0) != ':' ||
879                            compressBegin >= 14 && ip.charAt(tmp) != ':'))) ||
880                     currentIndex + 1 >= bytes.length ||
881                     begin < 0 && ip.charAt(tmp - 1) != ':' ||
882                     compressBegin > 2 && ip.charAt(0) == ':') {
883                 return null;
884             }
885             if (begin >= 0 && i - begin <= IPV6_MAX_CHAR_BETWEEN_SEPARATOR) {
886                 value <<= (IPV6_MAX_CHAR_BETWEEN_SEPARATOR - (i - begin)) << 2;
887             }
888             // The value integer holds at most 4 bytes from right (most significant) to left (least significant).
889             // The following bit shifting is used to extract and re-order the individual bytes to achieve a
890             // left (most significant) to right (least significant) ordering.
891             bytes[currentIndex++] = (byte) (((value & 0xf) << 4) | ((value >> 4) & 0xf));
892             bytes[currentIndex++] = (byte) ((((value >> 8) & 0xf) << 4) | ((value >> 12) & 0xf));
893         }
894 
895         i = currentIndex + compressLength;
896         if (needsShift || i >= bytes.length) {
897             // Right shift array
898             if (i >= bytes.length) {
899                 ++compressBegin;
900             }
901             for (i = currentIndex; i < bytes.length; ++i) {
902                 for (begin = bytes.length - 1; begin >= compressBegin; --begin) {
903                     bytes[begin] = bytes[begin - 1];
904                 }
905                 bytes[begin] = 0;
906                 ++compressBegin;
907             }
908         } else {
909             // Selectively move elements
910             for (i = 0; i < compressLength; ++i) {
911                 begin = i + compressBegin;
912                 currentIndex = begin + compressLength;
913                 if (currentIndex < bytes.length) {
914                     bytes[currentIndex] = bytes[begin];
915                     bytes[begin] = 0;
916                 } else {
917                     break;
918                 }
919             }
920         }
921 
922         if (ipv4Separators > 0) {
923             // We only support IPv4-Mapped addresses [1] because IPv4-Compatible addresses are deprecated [2].
924             // [1] https://tools.ietf.org/html/rfc4291#section-2.5.5.2
925             // [2] https://tools.ietf.org/html/rfc4291#section-2.5.5.1
926             bytes[10] = bytes[11] = (byte) 0xff;
927         }
928 
929         return bytes;
930     }
931 
932     /**
933      * Returns the {@link String} representation of an {@link InetSocketAddress}.
934      * <p>
935      * The output does not include Scope ID.
936      * @param addr {@link InetSocketAddress} to be converted to an address string
937      * @return {@code String} containing the text-formatted IP address
938      */
939     public static String toSocketAddressString(InetSocketAddress addr) {
940         String port = String.valueOf(addr.getPort());
941         final StringBuilder sb;
942 
943         if (addr.isUnresolved()) {
944             String hostname = getHostname(addr);
945             sb = newSocketAddressStringBuilder(hostname, port, !isValidIpV6Address(hostname));
946         } else {
947             InetAddress address = addr.getAddress();
948             String hostString = toAddressString(address);
949             sb = newSocketAddressStringBuilder(hostString, port, address instanceof Inet4Address);
950         }
951         return sb.append(':').append(port).toString();
952     }
953 
954     /**
955      * Returns the {@link String} representation of a host port combo.
956      */
957     public static String toSocketAddressString(String host, int port) {
958         String portStr = String.valueOf(port);
959         return newSocketAddressStringBuilder(
960                 host, portStr, !isValidIpV6Address(host)).append(':').append(portStr).toString();
961     }
962 
963     private static StringBuilder newSocketAddressStringBuilder(String host, String port, boolean ipv4) {
964         int hostLen = host.length();
965         if (ipv4) {
966             // Need to include enough space for hostString:port.
967             return new StringBuilder(hostLen + 1 + port.length()).append(host);
968         }
969         // Need to include enough space for [hostString]:port.
970         StringBuilder stringBuilder = new StringBuilder(hostLen + 3 + port.length());
971         if (hostLen > 1 && host.charAt(0) == '[' && host.charAt(hostLen - 1) == ']') {
972             return stringBuilder.append(host);
973         }
974         return stringBuilder.append('[').append(host).append(']');
975     }
976 
977     /**
978      * Returns the {@link String} representation of an {@link InetAddress}.
979      * <ul>
980      * <li>Inet4Address results are identical to {@link InetAddress#getHostAddress()}</li>
981      * <li>Inet6Address results adhere to
982      * <a href="http://tools.ietf.org/html/rfc5952#section-4">rfc 5952 section 4</a></li>
983      * </ul>
984      * <p>
985      * The output does not include Scope ID.
986      * @param ip {@link InetAddress} to be converted to an address string
987      * @return {@code String} containing the text-formatted IP address
988      */
989     public static String toAddressString(InetAddress ip) {
990         return toAddressString(ip, false);
991     }
992 
993     /**
994      * Returns the {@link String} representation of an {@link InetAddress}.
995      * <ul>
996      * <li>Inet4Address results are identical to {@link InetAddress#getHostAddress()}</li>
997      * <li>Inet6Address results adhere to
998      * <a href="http://tools.ietf.org/html/rfc5952#section-4">rfc 5952 section 4</a> if
999      * {@code ipv4Mapped} is false.  If {@code ipv4Mapped} is true then "IPv4 mapped" format
1000      * from <a href="http://tools.ietf.org/html/rfc4291#section-2.5.5">rfc 4291 section 2</a> will be supported.
1001      * The compressed result will always obey the compression rules defined in
1002      * <a href="http://tools.ietf.org/html/rfc5952#section-4">rfc 5952 section 4</a></li>
1003      * </ul>
1004      * <p>
1005      * The output does not include Scope ID.
1006      * @param ip {@link InetAddress} to be converted to an address string
1007      * @param ipv4Mapped
1008      * <ul>
1009      * <li>{@code true} to stray from strict rfc 5952 and support the "IPv4 mapped" format
1010      * defined in <a href="http://tools.ietf.org/html/rfc4291#section-2.5.5">rfc 4291 section 2</a> while still
1011      * following the updated guidelines in
1012      * <a href="http://tools.ietf.org/html/rfc5952#section-4">rfc 5952 section 4</a></li>
1013      * <li>{@code false} to strictly follow rfc 5952</li>
1014      * </ul>
1015      * @return {@code String} containing the text-formatted IP address
1016      */
1017     public static String toAddressString(InetAddress ip, boolean ipv4Mapped) {
1018         if (ip instanceof Inet4Address) {
1019             return ip.getHostAddress();
1020         }
1021         if (!(ip instanceof Inet6Address)) {
1022             throw new IllegalArgumentException("Unhandled type: " + ip);
1023         }
1024 
1025         return toAddressString(ip.getAddress(), 0, ipv4Mapped);
1026     }
1027 
1028     private static String toAddressString(byte[] bytes, int offset, boolean ipv4Mapped) {
1029         final int[] words = new int[IPV6_WORD_COUNT];
1030         int i;
1031         final int end = offset + words.length;
1032         for (i = offset; i < end; ++i) {
1033             words[i] = ((bytes[i << 1] & 0xff) << 8) | (bytes[(i << 1) + 1] & 0xff);
1034         }
1035 
1036         // Find longest run of 0s, tie goes to first found instance
1037         int currentStart = -1;
1038         int currentLength;
1039         int shortestStart = -1;
1040         int shortestLength = 0;
1041         for (i = 0; i < words.length; ++i) {
1042             if (words[i] == 0) {
1043                 if (currentStart < 0) {
1044                     currentStart = i;
1045                 }
1046             } else if (currentStart >= 0) {
1047                 currentLength = i - currentStart;
1048                 if (currentLength > shortestLength) {
1049                     shortestStart = currentStart;
1050                     shortestLength = currentLength;
1051                 }
1052                 currentStart = -1;
1053             }
1054         }
1055         // If the array ends on a streak of zeros, make sure we account for it
1056         if (currentStart >= 0) {
1057             currentLength = i - currentStart;
1058             if (currentLength > shortestLength) {
1059                 shortestStart = currentStart;
1060                 shortestLength = currentLength;
1061             }
1062         }
1063         // Ignore the longest streak if it is only 1 long
1064         if (shortestLength == 1) {
1065             shortestLength = 0;
1066             shortestStart = -1;
1067         }
1068 
1069         // Translate to string taking into account longest consecutive 0s
1070         final int shortestEnd = shortestStart + shortestLength;
1071         final StringBuilder b = new StringBuilder(IPV6_MAX_CHAR_COUNT);
1072         if (shortestEnd < 0) { // Optimization when there is no compressing needed
1073             b.append(Integer.toHexString(words[0]));
1074             for (i = 1; i < words.length; ++i) {
1075                 b.append(':');
1076                 b.append(Integer.toHexString(words[i]));
1077             }
1078         } else { // General case that can handle compressing (and not compressing)
1079             // Loop unroll the first index (so we don't constantly check i==0 cases in loop)
1080             final boolean isIpv4Mapped;
1081             if (inRangeEndExclusive(0, shortestStart, shortestEnd)) {
1082                 b.append("::");
1083                 isIpv4Mapped = ipv4Mapped && (shortestEnd == 5 && words[5] == 0xffff);
1084             } else {
1085                 b.append(Integer.toHexString(words[0]));
1086                 isIpv4Mapped = false;
1087             }
1088             for (i = 1; i < words.length; ++i) {
1089                 if (!inRangeEndExclusive(i, shortestStart, shortestEnd)) {
1090                     if (!inRangeEndExclusive(i - 1, shortestStart, shortestEnd)) {
1091                         // If the last index was not part of the shortened sequence
1092                         if (!isIpv4Mapped || i == 6) {
1093                             b.append(':');
1094                         } else {
1095                             b.append('.');
1096                         }
1097                     }
1098                     if (isIpv4Mapped && i > 5) {
1099                         b.append(words[i] >> 8);
1100                         b.append('.');
1101                         b.append(words[i] & 0xff);
1102                     } else {
1103                         b.append(Integer.toHexString(words[i]));
1104                     }
1105                 } else if (!inRangeEndExclusive(i - 1, shortestStart, shortestEnd)) {
1106                     // If we are in the shortened sequence and the last index was not
1107                     b.append("::");
1108                 }
1109             }
1110         }
1111 
1112         return b.toString();
1113     }
1114 
1115     /**
1116      * Returns {@link InetSocketAddress#getHostString()} if Java >= 7,
1117      * or {@link InetSocketAddress#getHostName()} otherwise.
1118      * @param addr The address
1119      * @return the host string
1120      */
1121     public static String getHostname(InetSocketAddress addr) {
1122         return PlatformDependent.javaVersion() >= 7 ? addr.getHostString() : addr.getHostName();
1123     }
1124 
1125     /**
1126      * Does a range check on {@code value} if is within {@code start} (inclusive) and {@code end} (exclusive).
1127      * @param value The value to checked if is within {@code start} (inclusive) and {@code end} (exclusive)
1128      * @param start The start of the range (inclusive)
1129      * @param end The end of the range (exclusive)
1130      * @return
1131      * <ul>
1132      * <li>{@code true} if {@code value} if is within {@code start} (inclusive) and {@code end} (exclusive)</li>
1133      * <li>{@code false} otherwise</li>
1134      * </ul>
1135      */
1136     private static boolean inRangeEndExclusive(int value, int start, int end) {
1137         return value >= start && value < end;
1138     }
1139 
1140     /**
1141      * A constructor to stop this class being constructed.
1142      */
1143     private NetUtil() {
1144         // Unused
1145     }
1146 }