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