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