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