001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.net;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static java.lang.Math.max;
020import static java.util.Objects.requireNonNull;
021
022import com.google.common.annotations.GwtIncompatible;
023import com.google.common.annotations.J2ktIncompatible;
024import com.google.common.base.CharMatcher;
025import com.google.common.base.MoreObjects;
026import com.google.common.hash.Hashing;
027import com.google.common.io.ByteStreams;
028import com.google.common.primitives.Ints;
029import com.google.errorprone.annotations.CanIgnoreReturnValue;
030import java.math.BigInteger;
031import java.net.Inet4Address;
032import java.net.Inet6Address;
033import java.net.InetAddress;
034import java.net.NetworkInterface;
035import java.net.SocketException;
036import java.net.UnknownHostException;
037import java.nio.ByteBuffer;
038import java.util.Arrays;
039import java.util.Locale;
040import javax.annotation.CheckForNull;
041import org.checkerframework.checker.nullness.qual.Nullable;
042
043/**
044 * Static utility methods pertaining to {@link InetAddress} instances.
045 *
046 * <p><b>Important note:</b> Unlike {@code InetAddress.getByName()}, the methods of this class never
047 * cause DNS services to be accessed. For this reason, you should prefer these methods as much as
048 * possible over their JDK equivalents whenever you are expecting to handle only IP address string
049 * literals -- there is no blocking DNS penalty for a malformed string.
050 *
051 * <p>When dealing with {@link Inet4Address} and {@link Inet6Address} objects as byte arrays (vis.
052 * {@code InetAddress.getAddress()}) they are 4 and 16 bytes in length, respectively, and represent
053 * the address in network byte order.
054 *
055 * <p>Examples of IP addresses and their byte representations:
056 *
057 * <dl>
058 *   <dt>The IPv4 loopback address, {@code "127.0.0.1"}.
059 *   <dd>{@code 7f 00 00 01}
060 *   <dt>The IPv6 loopback address, {@code "::1"}.
061 *   <dd>{@code 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01}
062 *   <dt>From the IPv6 reserved documentation prefix ({@code 2001:db8::/32}), {@code "2001:db8::1"}.
063 *   <dd>{@code 20 01 0d b8 00 00 00 00 00 00 00 00 00 00 00 01}
064 *   <dt>An IPv6 "IPv4 compatible" (or "compat") address, {@code "::192.168.0.1"}.
065 *   <dd>{@code 00 00 00 00 00 00 00 00 00 00 00 00 c0 a8 00 01}
066 *   <dt>An IPv6 "IPv4 mapped" address, {@code "::ffff:192.168.0.1"}.
067 *   <dd>{@code 00 00 00 00 00 00 00 00 00 00 ff ff c0 a8 00 01}
068 * </dl>
069 *
070 * <p>A few notes about IPv6 "IPv4 mapped" addresses and their observed use in Java.
071 *
072 * <p>"IPv4 mapped" addresses were originally a representation of IPv4 addresses for use on an IPv6
073 * socket that could receive both IPv4 and IPv6 connections (by disabling the {@code IPV6_V6ONLY}
074 * socket option on an IPv6 socket). Yes, it's confusing. Nevertheless, these "mapped" addresses
075 * were never supposed to be seen on the wire. That assumption was dropped, some say mistakenly, in
076 * later RFCs with the apparent aim of making IPv4-to-IPv6 transition simpler.
077 *
078 * <p>Technically one <i>can</i> create a 128bit IPv6 address with the wire format of a "mapped"
079 * address, as shown above, and transmit it in an IPv6 packet header. However, Java's InetAddress
080 * creation methods appear to adhere doggedly to the original intent of the "mapped" address: all
081 * "mapped" addresses return {@link Inet4Address} objects.
082 *
083 * <p>For added safety, it is common for IPv6 network operators to filter all packets where either
084 * the source or destination address appears to be a "compat" or "mapped" address. Filtering
085 * suggestions usually recommend discarding any packets with source or destination addresses in the
086 * invalid range {@code ::/3}, which includes both of these bizarre address formats. For more
087 * information on "bogons", including lists of IPv6 bogon space, see:
088 *
089 * <ul>
090 *   <li><a target="_parent"
091 *       href="http://en.wikipedia.org/wiki/Bogon_filtering">http://en.wikipedia.
092 *       org/wiki/Bogon_filtering</a>
093 *   <li><a target="_parent"
094 *       href="http://www.cymru.com/Bogons/ipv6.txt">http://www.cymru.com/Bogons/ ipv6.txt</a>
095 *   <li><a target="_parent" href="http://www.cymru.com/Bogons/v6bogon.html">http://www.cymru.com/
096 *       Bogons/v6bogon.html</a>
097 *   <li><a target="_parent" href="http://www.space.net/~gert/RIPE/ipv6-filters.html">http://www.
098 *       space.net/~gert/RIPE/ipv6-filters.html</a>
099 * </ul>
100 *
101 * @author Erik Kline
102 * @since 5.0
103 */
104@J2ktIncompatible
105@GwtIncompatible
106@ElementTypesAreNonnullByDefault
107public final class InetAddresses {
108  private static final int IPV4_PART_COUNT = 4;
109  private static final int IPV6_PART_COUNT = 8;
110  private static final char IPV4_DELIMITER = '.';
111  private static final char IPV6_DELIMITER = ':';
112  private static final CharMatcher IPV4_DELIMITER_MATCHER = CharMatcher.is(IPV4_DELIMITER);
113  private static final CharMatcher IPV6_DELIMITER_MATCHER = CharMatcher.is(IPV6_DELIMITER);
114  private static final Inet4Address LOOPBACK4 = (Inet4Address) forString("127.0.0.1");
115  private static final Inet4Address ANY4 = (Inet4Address) forString("0.0.0.0");
116
117  private InetAddresses() {}
118
119  /**
120   * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address.
121   *
122   * @param bytes byte array representing an IPv4 address (should be of length 4)
123   * @return {@link Inet4Address} corresponding to the supplied byte array
124   * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created
125   */
126  private static Inet4Address getInet4Address(byte[] bytes) {
127    checkArgument(
128        bytes.length == 4,
129        "Byte array has invalid length for an IPv4 address: %s != 4.",
130        bytes.length);
131
132    // Given a 4-byte array, this cast should always succeed.
133    return (Inet4Address) bytesToInetAddress(bytes, null);
134  }
135
136  /**
137   * Returns the {@link InetAddress} having the given string representation.
138   *
139   * <p>This deliberately avoids all nameservice lookups (e.g. no DNS).
140   *
141   * <p>This method accepts non-ASCII digits, for example {@code "192.168.0.1"} (those are fullwidth
142   * characters). That is consistent with {@link InetAddress}, but not with various RFCs. If you
143   * want to accept ASCII digits only, you can use something like {@code
144   * CharMatcher.ascii().matchesAllOf(ipString)}.
145   *
146   * <p>The scope ID is validated against the interfaces on the machine, which requires permissions
147   * under Android.
148   *
149   * <p><b>Android users on API >= 29:</b> Prefer {@code InetAddresses.parseNumericAddress}.
150   *
151   * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. {@code
152   *     "192.168.0.1"} or {@code "2001:db8::1"} or with a scope ID, e.g. {@code "2001:db8::1%eth0"}
153   * @return {@link InetAddress} representing the argument
154   * @throws IllegalArgumentException if the argument is not a valid IP string literal or if the
155   *     address has a scope ID that fails validation against the interfaces on the machine (as
156   *     required by Java's {@link InetAddress})
157   */
158  @CanIgnoreReturnValue // TODO(b/219820829): consider removing
159  public static InetAddress forString(String ipString) {
160    Scope scope = new Scope();
161    byte[] addr = ipStringToBytes(ipString, scope);
162
163    // The argument was malformed, i.e. not an IP string literal.
164    if (addr == null) {
165      throw formatIllegalArgumentException("'%s' is not an IP string literal.", ipString);
166    }
167
168    return bytesToInetAddress(addr, scope.scope);
169  }
170
171  /**
172   * Returns {@code true} if the supplied string is a valid IP string literal, {@code false}
173   * otherwise.
174   *
175   * <p>This method accepts non-ASCII digits, for example {@code "192.168.0.1"} (those are fullwidth
176   * characters). That is consistent with {@link InetAddress}, but not with various RFCs. If you
177   * want to accept ASCII digits only, you can use something like {@code
178   * CharMatcher.ascii().matchesAllOf(ipString)}.
179   *
180   * <p>Note that if this method returns {@code true}, a call to {@link #forString(String)} can
181   * still throw if the address has a scope ID that fails validation against the interfaces on the
182   * machine.
183   *
184   * @param ipString {@code String} to evaluated as an IP string literal
185   * @return {@code true} if the argument is a valid IP string literal
186   */
187  public static boolean isInetAddress(String ipString) {
188    return ipStringToBytes(ipString, null) != null;
189  }
190
191  private static final class Scope {
192    private String scope;
193  }
194
195  /** Returns {@code null} if unable to parse into a {@code byte[]}. */
196  @CheckForNull
197  private static byte[] ipStringToBytes(String ipStringParam, @Nullable Scope scope) {
198    String ipString = ipStringParam;
199    // Make a first pass to categorize the characters in this string.
200    boolean hasColon = false;
201    boolean hasDot = false;
202    int percentIndex = -1;
203    for (int i = 0; i < ipString.length(); i++) {
204      char c = ipString.charAt(i);
205      if (c == '.') {
206        hasDot = true;
207      } else if (c == ':') {
208        if (hasDot) {
209          return null; // Colons must not appear after dots.
210        }
211        hasColon = true;
212      } else if (c == '%') {
213        percentIndex = i;
214        break;
215      } else if (Character.digit(c, 16) == -1) {
216        return null; // Everything else must be a decimal or hex digit.
217      }
218    }
219
220    // Now decide which address family to parse.
221    if (hasColon) {
222      if (hasDot) {
223        ipString = convertDottedQuadToHex(ipString);
224        if (ipString == null) {
225          return null;
226        }
227      }
228      if (percentIndex != -1) {
229        if (scope != null) {
230          scope.scope = ipString.substring(percentIndex + 1);
231        }
232        ipString = ipString.substring(0, percentIndex);
233      }
234      return textToNumericFormatV6(ipString);
235    } else if (hasDot) {
236      if (percentIndex != -1) {
237        return null; // Scope IDs are not supported for IPV4
238      }
239      return textToNumericFormatV4(ipString);
240    }
241    return null;
242  }
243
244  @CheckForNull
245  private static byte[] textToNumericFormatV4(String ipString) {
246    if (IPV4_DELIMITER_MATCHER.countIn(ipString) + 1 != IPV4_PART_COUNT) {
247      return null; // Wrong number of parts
248    }
249
250    byte[] bytes = new byte[IPV4_PART_COUNT];
251    int start = 0;
252    // Iterate through the parts of the ip string.
253    // Invariant: start is always the beginning of an octet.
254    for (int i = 0; i < IPV4_PART_COUNT; i++) {
255      int end = ipString.indexOf(IPV4_DELIMITER, start);
256      if (end == -1) {
257        end = ipString.length();
258      }
259      try {
260        bytes[i] = parseOctet(ipString, start, end);
261      } catch (NumberFormatException ex) {
262        return null;
263      }
264      start = end + 1;
265    }
266
267    return bytes;
268  }
269
270  @CheckForNull
271  private static byte[] textToNumericFormatV6(String ipString) {
272    // An address can have [2..8] colons.
273    int delimiterCount = IPV6_DELIMITER_MATCHER.countIn(ipString);
274    if (delimiterCount < 2 || delimiterCount > IPV6_PART_COUNT) {
275      return null;
276    }
277    int partsSkipped = IPV6_PART_COUNT - (delimiterCount + 1); // estimate; may be modified later
278    boolean hasSkip = false;
279    // Scan for the appearance of ::, to mark a skip-format IPV6 string and adjust the partsSkipped
280    // estimate.
281    for (int i = 0; i < ipString.length() - 1; i++) {
282      if (ipString.charAt(i) == IPV6_DELIMITER && ipString.charAt(i + 1) == IPV6_DELIMITER) {
283        if (hasSkip) {
284          return null; // Can't have more than one ::
285        }
286        hasSkip = true;
287        partsSkipped++; // :: means we skipped an extra part in between the two delimiters.
288        if (i == 0) {
289          partsSkipped++; // Begins with ::, so we skipped the part preceding the first :
290        }
291        if (i == ipString.length() - 2) {
292          partsSkipped++; // Ends with ::, so we skipped the part after the last :
293        }
294      }
295    }
296    if (ipString.charAt(0) == IPV6_DELIMITER && ipString.charAt(1) != IPV6_DELIMITER) {
297      return null; // ^: requires ^::
298    }
299    if (ipString.charAt(ipString.length() - 1) == IPV6_DELIMITER
300        && ipString.charAt(ipString.length() - 2) != IPV6_DELIMITER) {
301      return null; // :$ requires ::$
302    }
303    if (hasSkip && partsSkipped <= 0) {
304      return null; // :: must expand to at least one '0'
305    }
306    if (!hasSkip && delimiterCount + 1 != IPV6_PART_COUNT) {
307      return null; // Incorrect number of parts
308    }
309
310    ByteBuffer rawBytes = ByteBuffer.allocate(2 * IPV6_PART_COUNT);
311    try {
312      // Iterate through the parts of the ip string.
313      // Invariant: start is always the beginning of a hextet, or the second ':' of the skip
314      // sequence "::"
315      int start = 0;
316      if (ipString.charAt(0) == IPV6_DELIMITER) {
317        start = 1;
318      }
319      while (start < ipString.length()) {
320        int end = ipString.indexOf(IPV6_DELIMITER, start);
321        if (end == -1) {
322          end = ipString.length();
323        }
324        if (ipString.charAt(start) == IPV6_DELIMITER) {
325          // expand zeroes
326          for (int i = 0; i < partsSkipped; i++) {
327            rawBytes.putShort((short) 0);
328          }
329
330        } else {
331          rawBytes.putShort(parseHextet(ipString, start, end));
332        }
333        start = end + 1;
334      }
335    } catch (NumberFormatException ex) {
336      return null;
337    }
338    return rawBytes.array();
339  }
340
341  @CheckForNull
342  private static String convertDottedQuadToHex(String ipString) {
343    int lastColon = ipString.lastIndexOf(':');
344    String initialPart = ipString.substring(0, lastColon + 1);
345    String dottedQuad = ipString.substring(lastColon + 1);
346    byte[] quad = textToNumericFormatV4(dottedQuad);
347    if (quad == null) {
348      return null;
349    }
350    String penultimate = Integer.toHexString(((quad[0] & 0xff) << 8) | (quad[1] & 0xff));
351    String ultimate = Integer.toHexString(((quad[2] & 0xff) << 8) | (quad[3] & 0xff));
352    return initialPart + penultimate + ":" + ultimate;
353  }
354
355  private static byte parseOctet(String ipString, int start, int end) {
356    // Note: we already verified that this string contains only hex digits, but the string may still
357    // contain non-decimal characters.
358    int length = end - start;
359    if (length <= 0 || length > 3) {
360      throw new NumberFormatException();
361    }
362    // Disallow leading zeroes, because no clear standard exists on
363    // whether these should be interpreted as decimal or octal.
364    if (length > 1 && ipString.charAt(start) == '0') {
365      throw new NumberFormatException();
366    }
367    int octet = 0;
368    for (int i = start; i < end; i++) {
369      octet *= 10;
370      int digit = Character.digit(ipString.charAt(i), 10);
371      if (digit < 0) {
372        throw new NumberFormatException();
373      }
374      octet += digit;
375    }
376    if (octet > 255) {
377      throw new NumberFormatException();
378    }
379    return (byte) octet;
380  }
381
382  /** Returns a -1 if unable to parse */
383  private static int tryParseDecimal(String string, int start, int end) {
384    int decimal = 0;
385    final int max = Integer.MAX_VALUE / 10; // for int overflow detection
386    for (int i = start; i < end; i++) {
387      if (decimal > max) {
388        return -1;
389      }
390      decimal *= 10;
391      int digit = Character.digit(string.charAt(i), 10);
392      if (digit < 0) {
393        return -1;
394      }
395      decimal += digit;
396    }
397    return decimal;
398  }
399
400  // Parse a hextet out of the ipString from start (inclusive) to end (exclusive)
401  private static short parseHextet(String ipString, int start, int end) {
402    // Note: we already verified that this string contains only hex digits.
403    int length = end - start;
404    if (length <= 0 || length > 4) {
405      throw new NumberFormatException();
406    }
407    int hextet = 0;
408    for (int i = start; i < end; i++) {
409      hextet = hextet << 4;
410      hextet |= Character.digit(ipString.charAt(i), 16);
411    }
412    return (short) hextet;
413  }
414
415  /**
416   * Convert a byte array into an InetAddress.
417   *
418   * <p>{@link InetAddress#getByAddress} is documented as throwing a checked exception "if IP
419   * address is of illegal length." We replace it with an unchecked exception, for use by callers
420   * who already know that addr is an array of length 4 or 16.
421   *
422   * @param addr the raw 4-byte or 16-byte IP address in big-endian order
423   * @return an InetAddress object created from the raw IP address
424   */
425  private static InetAddress bytesToInetAddress(byte[] addr, @Nullable String scope) {
426    try {
427      InetAddress address = InetAddress.getByAddress(addr);
428      if (scope == null) {
429        return address;
430      }
431      checkArgument(
432          address instanceof Inet6Address, "Unexpected state, scope should only appear for ipv6");
433      Inet6Address v6Address = (Inet6Address) address;
434      int interfaceIndex = tryParseDecimal(scope, 0, scope.length());
435      if (interfaceIndex != -1) {
436        return Inet6Address.getByAddress(
437            v6Address.getHostAddress(), v6Address.getAddress(), interfaceIndex);
438      }
439      try {
440        NetworkInterface asInterface = NetworkInterface.getByName(scope);
441        if (asInterface == null) {
442          throw formatIllegalArgumentException("No such interface: '%s'", scope);
443        }
444        return Inet6Address.getByAddress(
445            v6Address.getHostAddress(), v6Address.getAddress(), asInterface);
446      } catch (SocketException | UnknownHostException e) {
447        throw new IllegalArgumentException("No such interface: " + scope, e);
448      }
449    } catch (UnknownHostException e) {
450      throw new AssertionError(e);
451    }
452  }
453
454  /**
455   * Returns the string representation of an {@link InetAddress}.
456   *
457   * <p>For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6
458   * addresses, the output follows <a href="http://tools.ietf.org/html/rfc5952">RFC 5952</a> section
459   * 4. The main difference is that this method uses "::" for zero compression, while Java's version
460   * uses the uncompressed form (except on Android, where the zero compression is also done). The
461   * other difference is that this method outputs any scope ID in the format that it was provided at
462   * creation time, while Android may always output it as an interface name, even if it was supplied
463   * as a numeric ID.
464   *
465   * <p>This method uses hexadecimal for all IPv6 addresses, including IPv4-mapped IPv6 addresses
466   * such as "::c000:201".
467   *
468   * @param ip {@link InetAddress} to be converted to an address string
469   * @return {@code String} containing the text-formatted IP address
470   * @since 10.0
471   */
472  public static String toAddrString(InetAddress ip) {
473    checkNotNull(ip);
474    if (ip instanceof Inet4Address) {
475      // For IPv4, Java's formatting is good enough.
476      // requireNonNull accommodates Android's @RecentlyNullable annotation on getHostAddress
477      return requireNonNull(ip.getHostAddress());
478    }
479    byte[] bytes = ip.getAddress();
480    int[] hextets = new int[IPV6_PART_COUNT];
481    for (int i = 0; i < hextets.length; i++) {
482      hextets[i] = Ints.fromBytes((byte) 0, (byte) 0, bytes[2 * i], bytes[2 * i + 1]);
483    }
484    compressLongestRunOfZeroes(hextets);
485
486    return hextetsToIPv6String(hextets) + scopeWithDelimiter((Inet6Address) ip);
487  }
488
489  private static String scopeWithDelimiter(Inet6Address ip) {
490    // getHostAddress on android sometimes maps the scope ID to an invalid interface name; if the
491    // mapped interface isn't present, fallback to use the scope ID (which has no validation against
492    // present interfaces)
493    NetworkInterface scopedInterface = ip.getScopedInterface();
494    if (scopedInterface != null) {
495      return "%" + scopedInterface.getName();
496    }
497    int scope = ip.getScopeId();
498    if (scope != 0) {
499      return "%" + scope;
500    }
501    return "";
502  }
503
504  /**
505   * Identify and mark the longest run of zeroes in an IPv6 address.
506   *
507   * <p>Only runs of two or more hextets are considered. In case of a tie, the leftmost run wins. If
508   * a qualifying run is found, its hextets are replaced by the sentinel value -1.
509   *
510   * @param hextets {@code int[]} mutable array of eight 16-bit hextets
511   */
512  private static void compressLongestRunOfZeroes(int[] hextets) {
513    int bestRunStart = -1;
514    int bestRunLength = -1;
515    int runStart = -1;
516    for (int i = 0; i < hextets.length + 1; i++) {
517      if (i < hextets.length && hextets[i] == 0) {
518        if (runStart < 0) {
519          runStart = i;
520        }
521      } else if (runStart >= 0) {
522        int runLength = i - runStart;
523        if (runLength > bestRunLength) {
524          bestRunStart = runStart;
525          bestRunLength = runLength;
526        }
527        runStart = -1;
528      }
529    }
530    if (bestRunLength >= 2) {
531      Arrays.fill(hextets, bestRunStart, bestRunStart + bestRunLength, -1);
532    }
533  }
534
535  /**
536   * Convert a list of hextets into a human-readable IPv6 address.
537   *
538   * <p>In order for "::" compression to work, the input should contain negative sentinel values in
539   * place of the elided zeroes.
540   *
541   * @param hextets {@code int[]} array of eight 16-bit hextets, or -1s
542   */
543  private static String hextetsToIPv6String(int[] hextets) {
544    // While scanning the array, handle these state transitions:
545    //   start->num => "num"     start->gap => "::"
546    //   num->num   => ":num"    num->gap   => "::"
547    //   gap->num   => "num"     gap->gap   => ""
548    StringBuilder buf = new StringBuilder(39);
549    boolean lastWasNumber = false;
550    for (int i = 0; i < hextets.length; i++) {
551      boolean thisIsNumber = hextets[i] >= 0;
552      if (thisIsNumber) {
553        if (lastWasNumber) {
554          buf.append(':');
555        }
556        buf.append(Integer.toHexString(hextets[i]));
557      } else {
558        if (i == 0 || lastWasNumber) {
559          buf.append("::");
560        }
561      }
562      lastWasNumber = thisIsNumber;
563    }
564    return buf.toString();
565  }
566
567  /**
568   * Returns the string representation of an {@link InetAddress} suitable for inclusion in a URI.
569   *
570   * <p>For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6
571   * addresses it compresses zeroes and surrounds the text with square brackets; for example {@code
572   * "[2001:db8::1]"}.
573   *
574   * <p>Per section 3.2.2 of <a target="_parent"
575   * href="http://tools.ietf.org/html/rfc3986#section-3.2.2">RFC 3986</a>, a URI containing an IPv6
576   * string literal is of the form {@code "http://[2001:db8::1]:8888/index.html"}.
577   *
578   * <p>Use of either {@link InetAddresses#toAddrString}, {@link InetAddress#getHostAddress()}, or
579   * this method is recommended over {@link InetAddress#toString()} when an IP address string
580   * literal is desired. This is because {@link InetAddress#toString()} prints the hostname and the
581   * IP address string joined by a "/".
582   *
583   * @param ip {@link InetAddress} to be converted to URI string literal
584   * @return {@code String} containing URI-safe string literal
585   */
586  public static String toUriString(InetAddress ip) {
587    if (ip instanceof Inet6Address) {
588      return "[" + toAddrString(ip) + "]";
589    }
590    return toAddrString(ip);
591  }
592
593  /**
594   * Returns an InetAddress representing the literal IPv4 or IPv6 host portion of a URL, encoded in
595   * the format specified by RFC 3986 section 3.2.2.
596   *
597   * <p>This method is similar to {@link InetAddresses#forString(String)}, however, it requires that
598   * IPv6 addresses are surrounded by square brackets.
599   *
600   * <p>This method is the inverse of {@link InetAddresses#toUriString(java.net.InetAddress)}.
601   *
602   * <p>This method accepts non-ASCII digits, for example {@code "192.168.0.1"} (those are fullwidth
603   * characters). That is consistent with {@link InetAddress}, but not with various RFCs. If you
604   * want to accept ASCII digits only, you can use something like {@code
605   * CharMatcher.ascii().matchesAllOf(ipString)}.
606   *
607   * @param hostAddr an RFC 3986 section 3.2.2 encoded IPv4 or IPv6 address
608   * @return an InetAddress representing the address in {@code hostAddr}
609   * @throws IllegalArgumentException if {@code hostAddr} is not a valid IPv4 address, or IPv6
610   *     address surrounded by square brackets, or if the address has a scope ID that fails
611   *     validation against the interfaces on the machine (as required by Java's {@link
612   *     InetAddress})
613   */
614  public static InetAddress forUriString(String hostAddr) {
615    InetAddress addr = forUriStringOrNull(hostAddr, /* parseScope= */ true);
616    if (addr == null) {
617      throw formatIllegalArgumentException("Not a valid URI IP literal: '%s'", hostAddr);
618    }
619
620    return addr;
621  }
622
623  @CheckForNull
624  private static InetAddress forUriStringOrNull(String hostAddr, boolean parseScope) {
625    checkNotNull(hostAddr);
626
627    // Decide if this should be an IPv6 or IPv4 address.
628    String ipString;
629    int expectBytes;
630    if (hostAddr.startsWith("[") && hostAddr.endsWith("]")) {
631      ipString = hostAddr.substring(1, hostAddr.length() - 1);
632      expectBytes = 16;
633    } else {
634      ipString = hostAddr;
635      expectBytes = 4;
636    }
637
638    // Parse the address, and make sure the length/version is correct.
639    Scope scope = parseScope ? new Scope() : null;
640    byte[] addr = ipStringToBytes(ipString, scope);
641    if (addr == null || addr.length != expectBytes) {
642      return null;
643    }
644
645    return bytesToInetAddress(addr, (scope != null) ? scope.scope : null);
646  }
647
648  /**
649   * Returns {@code true} if the supplied string is a valid URI IP string literal, {@code false}
650   * otherwise.
651   *
652   * <p>This method accepts non-ASCII digits, for example {@code "192.168.0.1"} (those are fullwidth
653   * characters). That is consistent with {@link InetAddress}, but not with various RFCs. If you
654   * want to accept ASCII digits only, you can use something like {@code
655   * CharMatcher.ascii().matchesAllOf(ipString)}.
656   *
657   * <p>Note that if this method returns {@code true}, a call to {@link #forUriString(String)} can
658   * still throw if the address has a scope ID that fails validation against the interfaces on the
659   * machine.
660   *
661   * @param ipString {@code String} to evaluated as an IP URI host string literal
662   * @return {@code true} if the argument is a valid IP URI host
663   */
664  public static boolean isUriInetAddress(String ipString) {
665    return forUriStringOrNull(ipString, /* parseScope= */ false) != null;
666  }
667
668  /**
669   * Evaluates whether the argument is an IPv6 "compat" address.
670   *
671   * <p>An "IPv4 compatible", or "compat", address is one with 96 leading bits of zero, with the
672   * remaining 32 bits interpreted as an IPv4 address. These are conventionally represented in
673   * string literals as {@code "::192.168.0.1"}, though {@code "::c0a8:1"} is also considered an
674   * IPv4 compatible address (and equivalent to {@code "::192.168.0.1"}).
675   *
676   * <p>For more on IPv4 compatible addresses see section 2.5.5.1 of <a target="_parent"
677   * href="http://tools.ietf.org/html/rfc4291#section-2.5.5.1">RFC 4291</a>.
678   *
679   * <p>NOTE: This method is different from {@link Inet6Address#isIPv4CompatibleAddress} in that it
680   * more correctly classifies {@code "::"} and {@code "::1"} as proper IPv6 addresses (which they
681   * are), NOT IPv4 compatible addresses (which they are generally NOT considered to be).
682   *
683   * @param ip {@link Inet6Address} to be examined for embedded IPv4 compatible address format
684   * @return {@code true} if the argument is a valid "compat" address
685   */
686  public static boolean isCompatIPv4Address(Inet6Address ip) {
687    if (!ip.isIPv4CompatibleAddress()) {
688      return false;
689    }
690
691    byte[] bytes = ip.getAddress();
692    if ((bytes[12] == 0)
693        && (bytes[13] == 0)
694        && (bytes[14] == 0)
695        && ((bytes[15] == 0) || (bytes[15] == 1))) {
696      return false;
697    }
698
699    return true;
700  }
701
702  /**
703   * Returns the IPv4 address embedded in an IPv4 compatible address.
704   *
705   * @param ip {@link Inet6Address} to be examined for an embedded IPv4 address
706   * @return {@link Inet4Address} of the embedded IPv4 address
707   * @throws IllegalArgumentException if the argument is not a valid IPv4 compatible address
708   */
709  public static Inet4Address getCompatIPv4Address(Inet6Address ip) {
710    checkArgument(
711        isCompatIPv4Address(ip), "Address '%s' is not IPv4-compatible.", toAddrString(ip));
712
713    return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16));
714  }
715
716  /**
717   * Evaluates whether the argument is a 6to4 address.
718   *
719   * <p>6to4 addresses begin with the {@code "2002::/16"} prefix. The next 32 bits are the IPv4
720   * address of the host to which IPv6-in-IPv4 tunneled packets should be routed.
721   *
722   * <p>For more on 6to4 addresses see section 2 of <a target="_parent"
723   * href="http://tools.ietf.org/html/rfc3056#section-2">RFC 3056</a>.
724   *
725   * @param ip {@link Inet6Address} to be examined for 6to4 address format
726   * @return {@code true} if the argument is a 6to4 address
727   */
728  public static boolean is6to4Address(Inet6Address ip) {
729    byte[] bytes = ip.getAddress();
730    return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x02);
731  }
732
733  /**
734   * Returns the IPv4 address embedded in a 6to4 address.
735   *
736   * @param ip {@link Inet6Address} to be examined for embedded IPv4 in 6to4 address
737   * @return {@link Inet4Address} of embedded IPv4 in 6to4 address
738   * @throws IllegalArgumentException if the argument is not a valid IPv6 6to4 address
739   */
740  public static Inet4Address get6to4IPv4Address(Inet6Address ip) {
741    checkArgument(is6to4Address(ip), "Address '%s' is not a 6to4 address.", toAddrString(ip));
742
743    return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 2, 6));
744  }
745
746  /**
747   * A simple immutable data class to encapsulate the information to be found in a Teredo address.
748   *
749   * <p>All of the fields in this class are encoded in various portions of the IPv6 address as part
750   * of the protocol. More protocols details can be found at: <a target="_parent"
751   * href="http://en.wikipedia.org/wiki/Teredo_tunneling">http://en.wikipedia.
752   * org/wiki/Teredo_tunneling</a>.
753   *
754   * <p>The RFC can be found here: <a target="_parent" href="http://tools.ietf.org/html/rfc4380">RFC
755   * 4380</a>.
756   *
757   * @since 5.0
758   */
759  public static final class TeredoInfo {
760    private final Inet4Address server;
761    private final Inet4Address client;
762    private final int port;
763    private final int flags;
764
765    /**
766     * Constructs a TeredoInfo instance.
767     *
768     * <p>Both server and client can be {@code null}, in which case the value {@code "0.0.0.0"} will
769     * be assumed.
770     *
771     * @throws IllegalArgumentException if either of the {@code port} or the {@code flags} arguments
772     *     are out of range of an unsigned short
773     */
774    // TODO: why is this public?
775    public TeredoInfo(
776        @CheckForNull Inet4Address server, @CheckForNull Inet4Address client, int port, int flags) {
777      checkArgument(
778          (port >= 0) && (port <= 0xffff), "port '%s' is out of range (0 <= port <= 0xffff)", port);
779      checkArgument(
780          (flags >= 0) && (flags <= 0xffff),
781          "flags '%s' is out of range (0 <= flags <= 0xffff)",
782          flags);
783
784      this.server = MoreObjects.firstNonNull(server, ANY4);
785      this.client = MoreObjects.firstNonNull(client, ANY4);
786      this.port = port;
787      this.flags = flags;
788    }
789
790    public Inet4Address getServer() {
791      return server;
792    }
793
794    public Inet4Address getClient() {
795      return client;
796    }
797
798    public int getPort() {
799      return port;
800    }
801
802    public int getFlags() {
803      return flags;
804    }
805  }
806
807  /**
808   * Evaluates whether the argument is a Teredo address.
809   *
810   * <p>Teredo addresses begin with the {@code "2001::/32"} prefix.
811   *
812   * @param ip {@link Inet6Address} to be examined for Teredo address format
813   * @return {@code true} if the argument is a Teredo address
814   */
815  public static boolean isTeredoAddress(Inet6Address ip) {
816    byte[] bytes = ip.getAddress();
817    return (bytes[0] == (byte) 0x20)
818        && (bytes[1] == (byte) 0x01)
819        && (bytes[2] == 0)
820        && (bytes[3] == 0);
821  }
822
823  /**
824   * Returns the Teredo information embedded in a Teredo address.
825   *
826   * @param ip {@link Inet6Address} to be examined for embedded Teredo information
827   * @return extracted {@code TeredoInfo}
828   * @throws IllegalArgumentException if the argument is not a valid IPv6 Teredo address
829   */
830  public static TeredoInfo getTeredoInfo(Inet6Address ip) {
831    checkArgument(isTeredoAddress(ip), "Address '%s' is not a Teredo address.", toAddrString(ip));
832
833    byte[] bytes = ip.getAddress();
834    Inet4Address server = getInet4Address(Arrays.copyOfRange(bytes, 4, 8));
835
836    int flags = ByteStreams.newDataInput(bytes, 8).readShort() & 0xffff;
837
838    // Teredo obfuscates the mapped client port, per section 4 of the RFC.
839    int port = ~ByteStreams.newDataInput(bytes, 10).readShort() & 0xffff;
840
841    byte[] clientBytes = Arrays.copyOfRange(bytes, 12, 16);
842    for (int i = 0; i < clientBytes.length; i++) {
843      // Teredo obfuscates the mapped client IP, per section 4 of the RFC.
844      clientBytes[i] = (byte) ~clientBytes[i];
845    }
846    Inet4Address client = getInet4Address(clientBytes);
847
848    return new TeredoInfo(server, client, port, flags);
849  }
850
851  /**
852   * Evaluates whether the argument is an ISATAP address.
853   *
854   * <p>From RFC 5214: "ISATAP interface identifiers are constructed in Modified EUI-64 format [...]
855   * by concatenating the 24-bit IANA OUI (00-00-5E), the 8-bit hexadecimal value 0xFE, and a 32-bit
856   * IPv4 address in network byte order [...]"
857   *
858   * <p>For more on ISATAP addresses see section 6.1 of <a target="_parent"
859   * href="http://tools.ietf.org/html/rfc5214#section-6.1">RFC 5214</a>.
860   *
861   * @param ip {@link Inet6Address} to be examined for ISATAP address format
862   * @return {@code true} if the argument is an ISATAP address
863   */
864  public static boolean isIsatapAddress(Inet6Address ip) {
865
866    // If it's a Teredo address with the right port (41217, or 0xa101)
867    // which would be encoded as 0x5efe then it can't be an ISATAP address.
868    if (isTeredoAddress(ip)) {
869      return false;
870    }
871
872    byte[] bytes = ip.getAddress();
873
874    if ((bytes[8] | (byte) 0x03) != (byte) 0x03) {
875
876      // Verify that high byte of the 64 bit identifier is zero, modulo
877      // the U/L and G bits, with which we are not concerned.
878      return false;
879    }
880
881    return (bytes[9] == (byte) 0x00) && (bytes[10] == (byte) 0x5e) && (bytes[11] == (byte) 0xfe);
882  }
883
884  /**
885   * Returns the IPv4 address embedded in an ISATAP address.
886   *
887   * @param ip {@link Inet6Address} to be examined for embedded IPv4 in ISATAP address
888   * @return {@link Inet4Address} of embedded IPv4 in an ISATAP address
889   * @throws IllegalArgumentException if the argument is not a valid IPv6 ISATAP address
890   */
891  public static Inet4Address getIsatapIPv4Address(Inet6Address ip) {
892    checkArgument(isIsatapAddress(ip), "Address '%s' is not an ISATAP address.", toAddrString(ip));
893
894    return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16));
895  }
896
897  /**
898   * Examines the Inet6Address to determine if it is an IPv6 address of one of the specified address
899   * types that contain an embedded IPv4 address.
900   *
901   * <p>NOTE: ISATAP addresses are explicitly excluded from this method due to their trivial
902   * spoofability. With other transition addresses spoofing involves (at least) infection of one's
903   * BGP routing table.
904   *
905   * @param ip {@link Inet6Address} to be examined for embedded IPv4 client address
906   * @return {@code true} if there is an embedded IPv4 client address
907   * @since 7.0
908   */
909  public static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip) {
910    return isCompatIPv4Address(ip) || is6to4Address(ip) || isTeredoAddress(ip);
911  }
912
913  /**
914   * Examines the Inet6Address to extract the embedded IPv4 client address if the InetAddress is an
915   * IPv6 address of one of the specified address types that contain an embedded IPv4 address.
916   *
917   * <p>NOTE: ISATAP addresses are explicitly excluded from this method due to their trivial
918   * spoofability. With other transition addresses spoofing involves (at least) infection of one's
919   * BGP routing table.
920   *
921   * @param ip {@link Inet6Address} to be examined for embedded IPv4 client address
922   * @return {@link Inet4Address} of embedded IPv4 client address
923   * @throws IllegalArgumentException if the argument does not have a valid embedded IPv4 address
924   */
925  public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) {
926    if (isCompatIPv4Address(ip)) {
927      return getCompatIPv4Address(ip);
928    }
929
930    if (is6to4Address(ip)) {
931      return get6to4IPv4Address(ip);
932    }
933
934    if (isTeredoAddress(ip)) {
935      return getTeredoInfo(ip).getClient();
936    }
937
938    throw formatIllegalArgumentException("'%s' has no embedded IPv4 address.", toAddrString(ip));
939  }
940
941  /**
942   * Evaluates whether the argument is an "IPv4 mapped" IPv6 address.
943   *
944   * <p>An "IPv4 mapped" address is anything in the range ::ffff:0:0/96 (sometimes written as
945   * ::ffff:0.0.0.0/96), with the last 32 bits interpreted as an IPv4 address.
946   *
947   * <p>For more on IPv4 mapped addresses see section 2.5.5.2 of <a target="_parent"
948   * href="http://tools.ietf.org/html/rfc4291#section-2.5.5.2">RFC 4291</a>.
949   *
950   * <p>Note: This method takes a {@code String} argument because {@link InetAddress} automatically
951   * collapses mapped addresses to IPv4. (It is actually possible to avoid this using one of the
952   * obscure {@link Inet6Address} methods, but it would be unwise to depend on such a
953   * poorly-documented feature.)
954   *
955   * <p>This method accepts non-ASCII digits. That is consistent with {@link InetAddress}, but not
956   * with various RFCs. If you want to accept ASCII digits only, you can use something like {@code
957   * CharMatcher.ascii().matchesAllOf(ipString)}.
958   *
959   * @param ipString {@code String} to be examined for embedded IPv4-mapped IPv6 address format
960   * @return {@code true} if the argument is a valid "mapped" address
961   * @since 10.0
962   */
963  public static boolean isMappedIPv4Address(String ipString) {
964    byte[] bytes = ipStringToBytes(ipString, null);
965    if (bytes != null && bytes.length == 16) {
966      for (int i = 0; i < 10; i++) {
967        if (bytes[i] != 0) {
968          return false;
969        }
970      }
971      for (int i = 10; i < 12; i++) {
972        if (bytes[i] != (byte) 0xff) {
973          return false;
974        }
975      }
976      return true;
977    }
978    return false;
979  }
980
981  /**
982   * Coerces an IPv6 address into an IPv4 address.
983   *
984   * <p>HACK: As long as applications continue to use IPv4 addresses for indexing into tables,
985   * accounting, et cetera, it may be necessary to <b>coerce</b> IPv6 addresses into IPv4 addresses.
986   * This method does so by hashing 64 bits of the IPv6 address into {@code 224.0.0.0/3} (64 bits
987   * into 29 bits):
988   *
989   * <ul>
990   *   <li>If the IPv6 address contains an embedded IPv4 address, the function hashes that.
991   *   <li>Otherwise, it hashes the upper 64 bits of the IPv6 address.
992   * </ul>
993   *
994   * <p>A "coerced" IPv4 address is equivalent to itself.
995   *
996   * <p>NOTE: This method is failsafe for security purposes: ALL IPv6 addresses (except localhost
997   * (::1)) are hashed to avoid the security risk associated with extracting an embedded IPv4
998   * address that might permit elevated privileges.
999   *
1000   * @param ip {@link InetAddress} to "coerce"
1001   * @return {@link Inet4Address} represented "coerced" address
1002   * @since 7.0
1003   */
1004  public static Inet4Address getCoercedIPv4Address(InetAddress ip) {
1005    if (ip instanceof Inet4Address) {
1006      return (Inet4Address) ip;
1007    }
1008
1009    // Special cases:
1010    byte[] bytes = ip.getAddress();
1011    boolean leadingBytesOfZero = true;
1012    for (int i = 0; i < 15; ++i) {
1013      if (bytes[i] != 0) {
1014        leadingBytesOfZero = false;
1015        break;
1016      }
1017    }
1018    if (leadingBytesOfZero && (bytes[15] == 1)) {
1019      return LOOPBACK4; // ::1
1020    } else if (leadingBytesOfZero && (bytes[15] == 0)) {
1021      return ANY4; // ::0
1022    }
1023
1024    Inet6Address ip6 = (Inet6Address) ip;
1025    long addressAsLong = 0;
1026    if (hasEmbeddedIPv4ClientAddress(ip6)) {
1027      addressAsLong = getEmbeddedIPv4ClientAddress(ip6).hashCode();
1028    } else {
1029      // Just extract the high 64 bits (assuming the rest is user-modifiable).
1030      addressAsLong = ByteBuffer.wrap(ip6.getAddress(), 0, 8).getLong();
1031    }
1032
1033    // Many strategies for hashing are possible. This might suffice for now.
1034    int coercedHash = Hashing.murmur3_32_fixed().hashLong(addressAsLong).asInt();
1035
1036    // Squash into 224/4 Multicast and 240/4 Reserved space (i.e. 224/3).
1037    coercedHash |= 0xe0000000;
1038
1039    // Fixup to avoid some "illegal" values. Currently the only potential
1040    // illegal value is 255.255.255.255.
1041    if (coercedHash == 0xffffffff) {
1042      coercedHash = 0xfffffffe;
1043    }
1044
1045    return getInet4Address(Ints.toByteArray(coercedHash));
1046  }
1047
1048  /**
1049   * Returns an integer representing an IPv4 address regardless of whether the supplied argument is
1050   * an IPv4 address or not.
1051   *
1052   * <p>IPv6 addresses are <b>coerced</b> to IPv4 addresses before being converted to integers.
1053   *
1054   * <p>As long as there are applications that assume that all IP addresses are IPv4 addresses and
1055   * can therefore be converted safely to integers (for whatever purpose) this function can be used
1056   * to handle IPv6 addresses as well until the application is suitably fixed.
1057   *
1058   * <p>NOTE: an IPv6 address coerced to an IPv4 address can only be used for such purposes as
1059   * rudimentary identification or indexing into a collection of real {@link InetAddress}es. They
1060   * cannot be used as real addresses for the purposes of network communication.
1061   *
1062   * @param ip {@link InetAddress} to convert
1063   * @return {@code int}, "coerced" if ip is not an IPv4 address
1064   * @since 7.0
1065   */
1066  public static int coerceToInteger(InetAddress ip) {
1067    return ByteStreams.newDataInput(getCoercedIPv4Address(ip).getAddress()).readInt();
1068  }
1069
1070  /**
1071   * Returns a BigInteger representing the address.
1072   *
1073   * <p>Unlike {@code coerceToInteger}, IPv6 addresses are not coerced to IPv4 addresses.
1074   *
1075   * @param address {@link InetAddress} to convert
1076   * @return {@code BigInteger} representation of the address
1077   * @since 28.2
1078   */
1079  public static BigInteger toBigInteger(InetAddress address) {
1080    return new BigInteger(1, address.getAddress());
1081  }
1082
1083  /**
1084   * Returns an Inet4Address having the integer value specified by the argument.
1085   *
1086   * @param address {@code int}, the 32bit integer address to be converted
1087   * @return {@link Inet4Address} equivalent of the argument
1088   */
1089  public static Inet4Address fromInteger(int address) {
1090    return getInet4Address(Ints.toByteArray(address));
1091  }
1092
1093  /**
1094   * Returns the {@code Inet4Address} corresponding to a given {@code BigInteger}.
1095   *
1096   * @param address BigInteger representing the IPv4 address
1097   * @return Inet4Address representation of the given BigInteger
1098   * @throws IllegalArgumentException if the BigInteger is not between 0 and 2^32-1
1099   * @since 28.2
1100   */
1101  public static Inet4Address fromIPv4BigInteger(BigInteger address) {
1102    return (Inet4Address) fromBigInteger(address, false);
1103  }
1104  /**
1105   * Returns the {@code Inet6Address} corresponding to a given {@code BigInteger}.
1106   *
1107   * @param address BigInteger representing the IPv6 address
1108   * @return Inet6Address representation of the given BigInteger
1109   * @throws IllegalArgumentException if the BigInteger is not between 0 and 2^128-1
1110   * @since 28.2
1111   */
1112  public static Inet6Address fromIPv6BigInteger(BigInteger address) {
1113    return (Inet6Address) fromBigInteger(address, true);
1114  }
1115
1116  /**
1117   * Converts a BigInteger to either an IPv4 or IPv6 address. If the IP is IPv4, it must be
1118   * constrained to 32 bits, otherwise it is constrained to 128 bits.
1119   *
1120   * @param address the address represented as a big integer
1121   * @param isIpv6 whether the created address should be IPv4 or IPv6
1122   * @return the BigInteger converted to an address
1123   * @throws IllegalArgumentException if the BigInteger is not between 0 and maximum value for IPv4
1124   *     or IPv6 respectively
1125   */
1126  private static InetAddress fromBigInteger(BigInteger address, boolean isIpv6) {
1127    checkArgument(address.signum() >= 0, "BigInteger must be greater than or equal to 0");
1128
1129    int numBytes = isIpv6 ? 16 : 4;
1130
1131    byte[] addressBytes = address.toByteArray();
1132    byte[] targetCopyArray = new byte[numBytes];
1133
1134    int srcPos = max(0, addressBytes.length - numBytes);
1135    int copyLength = addressBytes.length - srcPos;
1136    int destPos = numBytes - copyLength;
1137
1138    // Check the extra bytes in the BigInteger are all zero.
1139    for (int i = 0; i < srcPos; i++) {
1140      if (addressBytes[i] != 0x00) {
1141        throw formatIllegalArgumentException(
1142            "BigInteger cannot be converted to InetAddress because it has more than %d"
1143                + " bytes: %s",
1144            numBytes, address);
1145      }
1146    }
1147
1148    // Copy the bytes into the least significant positions.
1149    System.arraycopy(addressBytes, srcPos, targetCopyArray, destPos, copyLength);
1150
1151    try {
1152      return InetAddress.getByAddress(targetCopyArray);
1153    } catch (UnknownHostException impossible) {
1154      throw new AssertionError(impossible);
1155    }
1156  }
1157
1158  /**
1159   * Returns an address from a <b>little-endian ordered</b> byte array (the opposite of what {@link
1160   * InetAddress#getByAddress} expects).
1161   *
1162   * <p>IPv4 address byte array must be 4 bytes long and IPv6 byte array must be 16 bytes long.
1163   *
1164   * @param addr the raw IP address in little-endian byte order
1165   * @return an InetAddress object created from the raw IP address
1166   * @throws UnknownHostException if IP address is of illegal length
1167   */
1168  public static InetAddress fromLittleEndianByteArray(byte[] addr) throws UnknownHostException {
1169    byte[] reversed = new byte[addr.length];
1170    for (int i = 0; i < addr.length; i++) {
1171      reversed[i] = addr[addr.length - i - 1];
1172    }
1173    return InetAddress.getByAddress(reversed);
1174  }
1175
1176  /**
1177   * Returns a new InetAddress that is one less than the passed in address. This method works for
1178   * both IPv4 and IPv6 addresses.
1179   *
1180   * @param address the InetAddress to decrement
1181   * @return a new InetAddress that is one less than the passed in address
1182   * @throws IllegalArgumentException if InetAddress is at the beginning of its range
1183   * @since 18.0
1184   */
1185  public static InetAddress decrement(InetAddress address) {
1186    byte[] addr = address.getAddress();
1187    int i = addr.length - 1;
1188    while (i >= 0 && addr[i] == (byte) 0x00) {
1189      addr[i] = (byte) 0xff;
1190      i--;
1191    }
1192
1193    checkArgument(i >= 0, "Decrementing %s would wrap.", address);
1194
1195    addr[i]--;
1196    return bytesToInetAddress(addr, null);
1197  }
1198
1199  /**
1200   * Returns a new InetAddress that is one more than the passed in address. This method works for
1201   * both IPv4 and IPv6 addresses.
1202   *
1203   * @param address the InetAddress to increment
1204   * @return a new InetAddress that is one more than the passed in address
1205   * @throws IllegalArgumentException if InetAddress is at the end of its range
1206   * @since 10.0
1207   */
1208  public static InetAddress increment(InetAddress address) {
1209    byte[] addr = address.getAddress();
1210    int i = addr.length - 1;
1211    while (i >= 0 && addr[i] == (byte) 0xff) {
1212      addr[i] = 0;
1213      i--;
1214    }
1215
1216    checkArgument(i >= 0, "Incrementing %s would wrap.", address);
1217
1218    addr[i]++;
1219    return bytesToInetAddress(addr, null);
1220  }
1221
1222  /**
1223   * Returns true if the InetAddress is either 255.255.255.255 for IPv4 or
1224   * ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6.
1225   *
1226   * @return true if the InetAddress is either 255.255.255.255 for IPv4 or
1227   *     ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6
1228   * @since 10.0
1229   */
1230  public static boolean isMaximum(InetAddress address) {
1231    byte[] addr = address.getAddress();
1232    for (byte b : addr) {
1233      if (b != (byte) 0xff) {
1234        return false;
1235      }
1236    }
1237    return true;
1238  }
1239
1240  private static IllegalArgumentException formatIllegalArgumentException(
1241      String format, Object... args) {
1242    return new IllegalArgumentException(String.format(Locale.ROOT, format, args));
1243  }
1244}