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