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.MoreObjects;
023import com.google.common.base.Splitter;
024import com.google.common.collect.Iterables;
025import com.google.common.hash.Hashing;
026import com.google.common.io.ByteStreams;
027import com.google.common.primitives.Ints;
028import java.math.BigInteger;
029import java.net.Inet4Address;
030import java.net.Inet6Address;
031import java.net.InetAddress;
032import java.net.UnknownHostException;
033import java.nio.ByteBuffer;
034import java.util.Arrays;
035import java.util.List;
036import java.util.Locale;
037import org.checkerframework.checker.nullness.compatqual.NullableDecl;
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@Beta
101@GwtIncompatible
102public final class InetAddresses {
103  private static final int IPV4_PART_COUNT = 4;
104  private static final int IPV6_PART_COUNT = 8;
105  private static final Splitter IPV4_SPLITTER = Splitter.on('.').limit(IPV4_PART_COUNT);
106  private static final Splitter IPV6_SPLITTER = Splitter.on(':').limit(IPV6_PART_COUNT + 2);
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      return textToNumericFormatV4(ipString);
201    }
202    return null;
203  }
204
205  @NullableDecl
206  private static byte[] textToNumericFormatV4(String ipString) {
207    byte[] bytes = new byte[IPV4_PART_COUNT];
208    int i = 0;
209    try {
210      for (String octet : IPV4_SPLITTER.split(ipString)) {
211        bytes[i++] = parseOctet(octet);
212      }
213    } catch (NumberFormatException ex) {
214      return null;
215    }
216
217    return i == IPV4_PART_COUNT ? bytes : null;
218  }
219
220  @NullableDecl
221  private static byte[] textToNumericFormatV6(String ipString) {
222    // An address can have [2..8] colons, and N colons make N+1 parts.
223    List<String> parts = IPV6_SPLITTER.splitToList(ipString);
224    if (parts.size() < 3 || parts.size() > IPV6_PART_COUNT + 1) {
225      return null;
226    }
227
228    // Disregarding the endpoints, find "::" with nothing in between.
229    // This indicates that a run of zeroes has been skipped.
230    int skipIndex = -1;
231    for (int i = 1; i < parts.size() - 1; i++) {
232      if (parts.get(i).length() == 0) {
233        if (skipIndex >= 0) {
234          return null; // Can't have more than one ::
235        }
236        skipIndex = i;
237      }
238    }
239
240    int partsHi; // Number of parts to copy from above/before the "::"
241    int partsLo; // Number of parts to copy from below/after the "::"
242    if (skipIndex >= 0) {
243      // If we found a "::", then check if it also covers the endpoints.
244      partsHi = skipIndex;
245      partsLo = parts.size() - skipIndex - 1;
246      if (parts.get(0).length() == 0 && --partsHi != 0) {
247        return null; // ^: requires ^::
248      }
249      if (Iterables.getLast(parts).length() == 0 && --partsLo != 0) {
250        return null; // :$ requires ::$
251      }
252    } else {
253      // Otherwise, allocate the entire address to partsHi. The endpoints
254      // could still be empty, but parseHextet() will check for that.
255      partsHi = parts.size();
256      partsLo = 0;
257    }
258
259    // If we found a ::, then we must have skipped at least one part.
260    // Otherwise, we must have exactly the right number of parts.
261    int partsSkipped = IPV6_PART_COUNT - (partsHi + partsLo);
262    if (!(skipIndex >= 0 ? partsSkipped >= 1 : partsSkipped == 0)) {
263      return null;
264    }
265
266    // Now parse the hextets into a byte array.
267    ByteBuffer rawBytes = ByteBuffer.allocate(2 * IPV6_PART_COUNT);
268    try {
269      for (int i = 0; i < partsHi; i++) {
270        rawBytes.putShort(parseHextet(parts.get(i)));
271      }
272      for (int i = 0; i < partsSkipped; i++) {
273        rawBytes.putShort((short) 0);
274      }
275      for (int i = partsLo; i > 0; i--) {
276        rawBytes.putShort(parseHextet(parts.get(parts.size() - i)));
277      }
278    } catch (NumberFormatException ex) {
279      return null;
280    }
281    return rawBytes.array();
282  }
283
284  @NullableDecl
285  private static String convertDottedQuadToHex(String ipString) {
286    int lastColon = ipString.lastIndexOf(':');
287    String initialPart = ipString.substring(0, lastColon + 1);
288    String dottedQuad = ipString.substring(lastColon + 1);
289    byte[] quad = textToNumericFormatV4(dottedQuad);
290    if (quad == null) {
291      return null;
292    }
293    String penultimate = Integer.toHexString(((quad[0] & 0xff) << 8) | (quad[1] & 0xff));
294    String ultimate = Integer.toHexString(((quad[2] & 0xff) << 8) | (quad[3] & 0xff));
295    return initialPart + penultimate + ":" + ultimate;
296  }
297
298  private static byte parseOctet(String ipPart) {
299    // Note: we already verified that this string contains only hex digits.
300    int octet = Integer.parseInt(ipPart);
301    // Disallow leading zeroes, because no clear standard exists on
302    // whether these should be interpreted as decimal or octal.
303    if (octet > 255 || (ipPart.startsWith("0") && ipPart.length() > 1)) {
304      throw new NumberFormatException();
305    }
306    return (byte) octet;
307  }
308
309  private static short parseHextet(String ipPart) {
310    // Note: we already verified that this string contains only hex digits.
311    int hextet = Integer.parseInt(ipPart, 16);
312    if (hextet > 0xffff) {
313      throw new NumberFormatException();
314    }
315    return (short) hextet;
316  }
317
318  /**
319   * Convert a byte array into an InetAddress.
320   *
321   * <p>{@link InetAddress#getByAddress} is documented as throwing a checked exception "if IP
322   * address is of illegal length." We replace it with an unchecked exception, for use by callers
323   * who already know that addr is an array of length 4 or 16.
324   *
325   * @param addr the raw 4-byte or 16-byte IP address in big-endian order
326   * @return an InetAddress object created from the raw IP address
327   */
328  private static InetAddress bytesToInetAddress(byte[] addr) {
329    try {
330      return InetAddress.getByAddress(addr);
331    } catch (UnknownHostException e) {
332      throw new AssertionError(e);
333    }
334  }
335
336  /**
337   * Returns the string representation of an {@link InetAddress}.
338   *
339   * <p>For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6
340   * addresses, the output follows <a href="http://tools.ietf.org/html/rfc5952">RFC 5952</a> section
341   * 4. The main difference is that this method uses "::" for zero compression, while Java's version
342   * uses the uncompressed form.
343   *
344   * <p>This method uses hexadecimal for all IPv6 addresses, including IPv4-mapped IPv6 addresses
345   * such as "::c000:201". The output does not include a Scope ID.
346   *
347   * @param ip {@link InetAddress} to be converted to an address string
348   * @return {@code String} containing the text-formatted IP address
349   * @since 10.0
350   */
351  public static String toAddrString(InetAddress ip) {
352    checkNotNull(ip);
353    if (ip instanceof Inet4Address) {
354      // For IPv4, Java's formatting is good enough.
355      return ip.getHostAddress();
356    }
357    checkArgument(ip instanceof Inet6Address);
358    byte[] bytes = ip.getAddress();
359    int[] hextets = new int[IPV6_PART_COUNT];
360    for (int i = 0; i < hextets.length; i++) {
361      hextets[i] = Ints.fromBytes((byte) 0, (byte) 0, bytes[2 * i], bytes[2 * i + 1]);
362    }
363    compressLongestRunOfZeroes(hextets);
364    return hextetsToIPv6String(hextets);
365  }
366
367  /**
368   * Identify and mark the longest run of zeroes in an IPv6 address.
369   *
370   * <p>Only runs of two or more hextets are considered. In case of a tie, the leftmost run wins. If
371   * a qualifying run is found, its hextets are replaced by the sentinel value -1.
372   *
373   * @param hextets {@code int[]} mutable array of eight 16-bit hextets
374   */
375  private static void compressLongestRunOfZeroes(int[] hextets) {
376    int bestRunStart = -1;
377    int bestRunLength = -1;
378    int runStart = -1;
379    for (int i = 0; i < hextets.length + 1; i++) {
380      if (i < hextets.length && hextets[i] == 0) {
381        if (runStart < 0) {
382          runStart = i;
383        }
384      } else if (runStart >= 0) {
385        int runLength = i - runStart;
386        if (runLength > bestRunLength) {
387          bestRunStart = runStart;
388          bestRunLength = runLength;
389        }
390        runStart = -1;
391      }
392    }
393    if (bestRunLength >= 2) {
394      Arrays.fill(hextets, bestRunStart, bestRunStart + bestRunLength, -1);
395    }
396  }
397
398  /**
399   * Convert a list of hextets into a human-readable IPv6 address.
400   *
401   * <p>In order for "::" compression to work, the input should contain negative sentinel values in
402   * place of the elided zeroes.
403   *
404   * @param hextets {@code int[]} array of eight 16-bit hextets, or -1s
405   */
406  private static String hextetsToIPv6String(int[] hextets) {
407    // While scanning the array, handle these state transitions:
408    //   start->num => "num"     start->gap => "::"
409    //   num->num   => ":num"    num->gap   => "::"
410    //   gap->num   => "num"     gap->gap   => ""
411    StringBuilder buf = new StringBuilder(39);
412    boolean lastWasNumber = false;
413    for (int i = 0; i < hextets.length; i++) {
414      boolean thisIsNumber = hextets[i] >= 0;
415      if (thisIsNumber) {
416        if (lastWasNumber) {
417          buf.append(':');
418        }
419        buf.append(Integer.toHexString(hextets[i]));
420      } else {
421        if (i == 0 || lastWasNumber) {
422          buf.append("::");
423        }
424      }
425      lastWasNumber = thisIsNumber;
426    }
427    return buf.toString();
428  }
429
430  /**
431   * Returns the string representation of an {@link InetAddress} suitable for inclusion in a URI.
432   *
433   * <p>For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6
434   * addresses it compresses zeroes and surrounds the text with square brackets; for example {@code
435   * "[2001:db8::1]"}.
436   *
437   * <p>Per section 3.2.2 of <a target="_parent"
438   * href="http://tools.ietf.org/html/rfc3986#section-3.2.2">RFC 3986</a>, a URI containing an IPv6
439   * string literal is of the form {@code "http://[2001:db8::1]:8888/index.html"}.
440   *
441   * <p>Use of either {@link InetAddresses#toAddrString}, {@link InetAddress#getHostAddress()}, or
442   * this method is recommended over {@link InetAddress#toString()} when an IP address string
443   * literal is desired. This is because {@link InetAddress#toString()} prints the hostname and the
444   * IP address string joined by a "/".
445   *
446   * @param ip {@link InetAddress} to be converted to URI string literal
447   * @return {@code String} containing URI-safe string literal
448   */
449  public static String toUriString(InetAddress ip) {
450    if (ip instanceof Inet6Address) {
451      return "[" + toAddrString(ip) + "]";
452    }
453    return toAddrString(ip);
454  }
455
456  /**
457   * Returns an InetAddress representing the literal IPv4 or IPv6 host portion of a URL, encoded in
458   * the format specified by RFC 3986 section 3.2.2.
459   *
460   * <p>This function is similar to {@link InetAddresses#forString(String)}, however, it requires
461   * that IPv6 addresses are surrounded by square brackets.
462   *
463   * <p>This function is the inverse of {@link InetAddresses#toUriString(java.net.InetAddress)}.
464   *
465   * @param hostAddr A RFC 3986 section 3.2.2 encoded IPv4 or IPv6 address
466   * @return an InetAddress representing the address in {@code hostAddr}
467   * @throws IllegalArgumentException if {@code hostAddr} is not a valid IPv4 address, or IPv6
468   *     address surrounded by square brackets
469   */
470  public static InetAddress forUriString(String hostAddr) {
471    InetAddress addr = forUriStringNoThrow(hostAddr);
472    if (addr == null) {
473      throw formatIllegalArgumentException("Not a valid URI IP literal: '%s'", hostAddr);
474    }
475
476    return addr;
477  }
478
479  @NullableDecl
480  private static InetAddress forUriStringNoThrow(String hostAddr) {
481    checkNotNull(hostAddr);
482
483    // Decide if this should be an IPv6 or IPv4 address.
484    String ipString;
485    int expectBytes;
486    if (hostAddr.startsWith("[") && hostAddr.endsWith("]")) {
487      ipString = hostAddr.substring(1, hostAddr.length() - 1);
488      expectBytes = 16;
489    } else {
490      ipString = hostAddr;
491      expectBytes = 4;
492    }
493
494    // Parse the address, and make sure the length/version is correct.
495    byte[] addr = ipStringToBytes(ipString);
496    if (addr == null || addr.length != expectBytes) {
497      return null;
498    }
499
500    return bytesToInetAddress(addr);
501  }
502
503  /**
504   * Returns {@code true} if the supplied string is a valid URI IP string literal, {@code false}
505   * otherwise.
506   *
507   * @param ipString {@code String} to evaluated as an IP URI host string literal
508   * @return {@code true} if the argument is a valid IP URI host
509   */
510  public static boolean isUriInetAddress(String ipString) {
511    return forUriStringNoThrow(ipString) != null;
512  }
513
514  /**
515   * Evaluates whether the argument is an IPv6 "compat" address.
516   *
517   * <p>An "IPv4 compatible", or "compat", address is one with 96 leading bits of zero, with the
518   * remaining 32 bits interpreted as an IPv4 address. These are conventionally represented in
519   * string literals as {@code "::192.168.0.1"}, though {@code "::c0a8:1"} is also considered an
520   * IPv4 compatible address (and equivalent to {@code "::192.168.0.1"}).
521   *
522   * <p>For more on IPv4 compatible addresses see section 2.5.5.1 of <a target="_parent"
523   * href="http://tools.ietf.org/html/rfc4291#section-2.5.5.1">RFC 4291</a>.
524   *
525   * <p>NOTE: This method is different from {@link Inet6Address#isIPv4CompatibleAddress} in that it
526   * more correctly classifies {@code "::"} and {@code "::1"} as proper IPv6 addresses (which they
527   * are), NOT IPv4 compatible addresses (which they are generally NOT considered to be).
528   *
529   * @param ip {@link Inet6Address} to be examined for embedded IPv4 compatible address format
530   * @return {@code true} if the argument is a valid "compat" address
531   */
532  public static boolean isCompatIPv4Address(Inet6Address ip) {
533    if (!ip.isIPv4CompatibleAddress()) {
534      return false;
535    }
536
537    byte[] bytes = ip.getAddress();
538    if ((bytes[12] == 0)
539        && (bytes[13] == 0)
540        && (bytes[14] == 0)
541        && ((bytes[15] == 0) || (bytes[15] == 1))) {
542      return false;
543    }
544
545    return true;
546  }
547
548  /**
549   * Returns the IPv4 address embedded in an IPv4 compatible address.
550   *
551   * @param ip {@link Inet6Address} to be examined for an embedded IPv4 address
552   * @return {@link Inet4Address} of the embedded IPv4 address
553   * @throws IllegalArgumentException if the argument is not a valid IPv4 compatible address
554   */
555  public static Inet4Address getCompatIPv4Address(Inet6Address ip) {
556    checkArgument(
557        isCompatIPv4Address(ip), "Address '%s' is not IPv4-compatible.", toAddrString(ip));
558
559    return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16));
560  }
561
562  /**
563   * Evaluates whether the argument is a 6to4 address.
564   *
565   * <p>6to4 addresses begin with the {@code "2002::/16"} prefix. The next 32 bits are the IPv4
566   * address of the host to which IPv6-in-IPv4 tunneled packets should be routed.
567   *
568   * <p>For more on 6to4 addresses see section 2 of <a target="_parent"
569   * href="http://tools.ietf.org/html/rfc3056#section-2">RFC 3056</a>.
570   *
571   * @param ip {@link Inet6Address} to be examined for 6to4 address format
572   * @return {@code true} if the argument is a 6to4 address
573   */
574  public static boolean is6to4Address(Inet6Address ip) {
575    byte[] bytes = ip.getAddress();
576    return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x02);
577  }
578
579  /**
580   * Returns the IPv4 address embedded in a 6to4 address.
581   *
582   * @param ip {@link Inet6Address} to be examined for embedded IPv4 in 6to4 address
583   * @return {@link Inet4Address} of embedded IPv4 in 6to4 address
584   * @throws IllegalArgumentException if the argument is not a valid IPv6 6to4 address
585   */
586  public static Inet4Address get6to4IPv4Address(Inet6Address ip) {
587    checkArgument(is6to4Address(ip), "Address '%s' is not a 6to4 address.", toAddrString(ip));
588
589    return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 2, 6));
590  }
591
592  /**
593   * A simple immutable data class to encapsulate the information to be found in a Teredo address.
594   *
595   * <p>All of the fields in this class are encoded in various portions of the IPv6 address as part
596   * of the protocol. More protocols details can be found at: <a target="_parent"
597   * href="http://en.wikipedia.org/wiki/Teredo_tunneling">http://en.wikipedia.
598   * org/wiki/Teredo_tunneling</a>.
599   *
600   * <p>The RFC can be found here: <a target="_parent" href="http://tools.ietf.org/html/rfc4380">RFC
601   * 4380</a>.
602   *
603   * @since 5.0
604   */
605  @Beta
606  public static final class TeredoInfo {
607    private final Inet4Address server;
608    private final Inet4Address client;
609    private final int port;
610    private final int flags;
611
612    /**
613     * Constructs a TeredoInfo instance.
614     *
615     * <p>Both server and client can be {@code null}, in which case the value {@code "0.0.0.0"} will
616     * be assumed.
617     *
618     * @throws IllegalArgumentException if either of the {@code port} or the {@code flags} arguments
619     *     are out of range of an unsigned short
620     */
621    // TODO: why is this public?
622    public TeredoInfo(
623        @NullableDecl Inet4Address server, @NullableDecl Inet4Address client, int port, int flags) {
624      checkArgument(
625          (port >= 0) && (port <= 0xffff), "port '%s' is out of range (0 <= port <= 0xffff)", port);
626      checkArgument(
627          (flags >= 0) && (flags <= 0xffff),
628          "flags '%s' is out of range (0 <= flags <= 0xffff)",
629          flags);
630
631      this.server = MoreObjects.firstNonNull(server, ANY4);
632      this.client = MoreObjects.firstNonNull(client, ANY4);
633      this.port = port;
634      this.flags = flags;
635    }
636
637    public Inet4Address getServer() {
638      return server;
639    }
640
641    public Inet4Address getClient() {
642      return client;
643    }
644
645    public int getPort() {
646      return port;
647    }
648
649    public int getFlags() {
650      return flags;
651    }
652  }
653
654  /**
655   * Evaluates whether the argument is a Teredo address.
656   *
657   * <p>Teredo addresses begin with the {@code "2001::/32"} prefix.
658   *
659   * @param ip {@link Inet6Address} to be examined for Teredo address format
660   * @return {@code true} if the argument is a Teredo address
661   */
662  public static boolean isTeredoAddress(Inet6Address ip) {
663    byte[] bytes = ip.getAddress();
664    return (bytes[0] == (byte) 0x20)
665        && (bytes[1] == (byte) 0x01)
666        && (bytes[2] == 0)
667        && (bytes[3] == 0);
668  }
669
670  /**
671   * Returns the Teredo information embedded in a Teredo address.
672   *
673   * @param ip {@link Inet6Address} to be examined for embedded Teredo information
674   * @return extracted {@code TeredoInfo}
675   * @throws IllegalArgumentException if the argument is not a valid IPv6 Teredo address
676   */
677  public static TeredoInfo getTeredoInfo(Inet6Address ip) {
678    checkArgument(isTeredoAddress(ip), "Address '%s' is not a Teredo address.", toAddrString(ip));
679
680    byte[] bytes = ip.getAddress();
681    Inet4Address server = getInet4Address(Arrays.copyOfRange(bytes, 4, 8));
682
683    int flags = ByteStreams.newDataInput(bytes, 8).readShort() & 0xffff;
684
685    // Teredo obfuscates the mapped client port, per section 4 of the RFC.
686    int port = ~ByteStreams.newDataInput(bytes, 10).readShort() & 0xffff;
687
688    byte[] clientBytes = Arrays.copyOfRange(bytes, 12, 16);
689    for (int i = 0; i < clientBytes.length; i++) {
690      // Teredo obfuscates the mapped client IP, per section 4 of the RFC.
691      clientBytes[i] = (byte) ~clientBytes[i];
692    }
693    Inet4Address client = getInet4Address(clientBytes);
694
695    return new TeredoInfo(server, client, port, flags);
696  }
697
698  /**
699   * Evaluates whether the argument is an ISATAP address.
700   *
701   * <p>From RFC 5214: "ISATAP interface identifiers are constructed in Modified EUI-64 format [...]
702   * by concatenating the 24-bit IANA OUI (00-00-5E), the 8-bit hexadecimal value 0xFE, and a 32-bit
703   * IPv4 address in network byte order [...]"
704   *
705   * <p>For more on ISATAP addresses see section 6.1 of <a target="_parent"
706   * href="http://tools.ietf.org/html/rfc5214#section-6.1">RFC 5214</a>.
707   *
708   * @param ip {@link Inet6Address} to be examined for ISATAP address format
709   * @return {@code true} if the argument is an ISATAP address
710   */
711  public static boolean isIsatapAddress(Inet6Address ip) {
712
713    // If it's a Teredo address with the right port (41217, or 0xa101)
714    // which would be encoded as 0x5efe then it can't be an ISATAP address.
715    if (isTeredoAddress(ip)) {
716      return false;
717    }
718
719    byte[] bytes = ip.getAddress();
720
721    if ((bytes[8] | (byte) 0x03) != (byte) 0x03) {
722
723      // Verify that high byte of the 64 bit identifier is zero, modulo
724      // the U/L and G bits, with which we are not concerned.
725      return false;
726    }
727
728    return (bytes[9] == (byte) 0x00) && (bytes[10] == (byte) 0x5e) && (bytes[11] == (byte) 0xfe);
729  }
730
731  /**
732   * Returns the IPv4 address embedded in an ISATAP address.
733   *
734   * @param ip {@link Inet6Address} to be examined for embedded IPv4 in ISATAP address
735   * @return {@link Inet4Address} of embedded IPv4 in an ISATAP address
736   * @throws IllegalArgumentException if the argument is not a valid IPv6 ISATAP address
737   */
738  public static Inet4Address getIsatapIPv4Address(Inet6Address ip) {
739    checkArgument(isIsatapAddress(ip), "Address '%s' is not an ISATAP address.", toAddrString(ip));
740
741    return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16));
742  }
743
744  /**
745   * Examines the Inet6Address to determine if it is an IPv6 address of one of the specified address
746   * types that contain an embedded IPv4 address.
747   *
748   * <p>NOTE: ISATAP addresses are explicitly excluded from this method due to their trivial
749   * spoofability. With other transition addresses spoofing involves (at least) infection of one's
750   * BGP routing table.
751   *
752   * @param ip {@link Inet6Address} to be examined for embedded IPv4 client address
753   * @return {@code true} if there is an embedded IPv4 client address
754   * @since 7.0
755   */
756  public static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip) {
757    return isCompatIPv4Address(ip) || is6to4Address(ip) || isTeredoAddress(ip);
758  }
759
760  /**
761   * Examines the Inet6Address to extract the embedded IPv4 client address if the InetAddress is an
762   * IPv6 address of one of the specified address types that contain an embedded IPv4 address.
763   *
764   * <p>NOTE: ISATAP addresses are explicitly excluded from this method due to their trivial
765   * spoofability. With other transition addresses spoofing involves (at least) infection of one's
766   * BGP routing table.
767   *
768   * @param ip {@link Inet6Address} to be examined for embedded IPv4 client address
769   * @return {@link Inet4Address} of embedded IPv4 client address
770   * @throws IllegalArgumentException if the argument does not have a valid embedded IPv4 address
771   */
772  public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) {
773    if (isCompatIPv4Address(ip)) {
774      return getCompatIPv4Address(ip);
775    }
776
777    if (is6to4Address(ip)) {
778      return get6to4IPv4Address(ip);
779    }
780
781    if (isTeredoAddress(ip)) {
782      return getTeredoInfo(ip).getClient();
783    }
784
785    throw formatIllegalArgumentException("'%s' has no embedded IPv4 address.", toAddrString(ip));
786  }
787
788  /**
789   * Evaluates whether the argument is an "IPv4 mapped" IPv6 address.
790   *
791   * <p>An "IPv4 mapped" address is anything in the range ::ffff:0:0/96 (sometimes written as
792   * ::ffff:0.0.0.0/96), with the last 32 bits interpreted as an IPv4 address.
793   *
794   * <p>For more on IPv4 mapped addresses see section 2.5.5.2 of <a target="_parent"
795   * href="http://tools.ietf.org/html/rfc4291#section-2.5.5.2">RFC 4291</a>.
796   *
797   * <p>Note: This method takes a {@code String} argument because {@link InetAddress} automatically
798   * collapses mapped addresses to IPv4. (It is actually possible to avoid this using one of the
799   * obscure {@link Inet6Address} methods, but it would be unwise to depend on such a
800   * poorly-documented feature.)
801   *
802   * @param ipString {@code String} to be examined for embedded IPv4-mapped IPv6 address format
803   * @return {@code true} if the argument is a valid "mapped" address
804   * @since 10.0
805   */
806  public static boolean isMappedIPv4Address(String ipString) {
807    byte[] bytes = ipStringToBytes(ipString);
808    if (bytes != null && bytes.length == 16) {
809      for (int i = 0; i < 10; i++) {
810        if (bytes[i] != 0) {
811          return false;
812        }
813      }
814      for (int i = 10; i < 12; i++) {
815        if (bytes[i] != (byte) 0xff) {
816          return false;
817        }
818      }
819      return true;
820    }
821    return false;
822  }
823
824  /**
825   * Coerces an IPv6 address into an IPv4 address.
826   *
827   * <p>HACK: As long as applications continue to use IPv4 addresses for indexing into tables,
828   * accounting, et cetera, it may be necessary to <b>coerce</b> IPv6 addresses into IPv4 addresses.
829   * This function does so by hashing 64 bits of the IPv6 address into {@code 224.0.0.0/3} (64 bits
830   * into 29 bits):
831   *
832   * <ul>
833   *   <li>If the IPv6 address contains an embedded IPv4 address, the function hashes that.
834   *   <li>Otherwise, it hashes the upper 64 bits of the IPv6 address.
835   * </ul>
836   *
837   * <p>A "coerced" IPv4 address is equivalent to itself.
838   *
839   * <p>NOTE: This function is failsafe for security purposes: ALL IPv6 addresses (except localhost
840   * (::1)) are hashed to avoid the security risk associated with extracting an embedded IPv4
841   * address that might permit elevated privileges.
842   *
843   * @param ip {@link InetAddress} to "coerce"
844   * @return {@link Inet4Address} represented "coerced" address
845   * @since 7.0
846   */
847  public static Inet4Address getCoercedIPv4Address(InetAddress ip) {
848    if (ip instanceof Inet4Address) {
849      return (Inet4Address) ip;
850    }
851
852    // Special cases:
853    byte[] bytes = ip.getAddress();
854    boolean leadingBytesOfZero = true;
855    for (int i = 0; i < 15; ++i) {
856      if (bytes[i] != 0) {
857        leadingBytesOfZero = false;
858        break;
859      }
860    }
861    if (leadingBytesOfZero && (bytes[15] == 1)) {
862      return LOOPBACK4; // ::1
863    } else if (leadingBytesOfZero && (bytes[15] == 0)) {
864      return ANY4; // ::0
865    }
866
867    Inet6Address ip6 = (Inet6Address) ip;
868    long addressAsLong = 0;
869    if (hasEmbeddedIPv4ClientAddress(ip6)) {
870      addressAsLong = getEmbeddedIPv4ClientAddress(ip6).hashCode();
871    } else {
872      // Just extract the high 64 bits (assuming the rest is user-modifiable).
873      addressAsLong = ByteBuffer.wrap(ip6.getAddress(), 0, 8).getLong();
874    }
875
876    // Many strategies for hashing are possible. This might suffice for now.
877    int coercedHash = Hashing.murmur3_32().hashLong(addressAsLong).asInt();
878
879    // Squash into 224/4 Multicast and 240/4 Reserved space (i.e. 224/3).
880    coercedHash |= 0xe0000000;
881
882    // Fixup to avoid some "illegal" values. Currently the only potential
883    // illegal value is 255.255.255.255.
884    if (coercedHash == 0xffffffff) {
885      coercedHash = 0xfffffffe;
886    }
887
888    return getInet4Address(Ints.toByteArray(coercedHash));
889  }
890
891  /**
892   * Returns an integer representing an IPv4 address regardless of whether the supplied argument is
893   * an IPv4 address or not.
894   *
895   * <p>IPv6 addresses are <b>coerced</b> to IPv4 addresses before being converted to integers.
896   *
897   * <p>As long as there are applications that assume that all IP addresses are IPv4 addresses and
898   * can therefore be converted safely to integers (for whatever purpose) this function can be used
899   * to handle IPv6 addresses as well until the application is suitably fixed.
900   *
901   * <p>NOTE: an IPv6 address coerced to an IPv4 address can only be used for such purposes as
902   * rudimentary identification or indexing into a collection of real {@link InetAddress}es. They
903   * cannot be used as real addresses for the purposes of network communication.
904   *
905   * @param ip {@link InetAddress} to convert
906   * @return {@code int}, "coerced" if ip is not an IPv4 address
907   * @since 7.0
908   */
909  public static int coerceToInteger(InetAddress ip) {
910    return ByteStreams.newDataInput(getCoercedIPv4Address(ip).getAddress()).readInt();
911  }
912
913  /**
914   * Returns a BigInteger representing the address.
915   *
916   * <p>Unlike {@code coerceToInteger}, IPv6 addresses are not coerced to IPv4 addresses.
917   *
918   * @param address {@link InetAddress} to convert
919   * @return {@code BigInteger} representation of the address
920   * @since 28.2
921   */
922  public static BigInteger toBigInteger(InetAddress address) {
923    return new BigInteger(1, address.getAddress());
924  }
925
926  /**
927   * Returns an Inet4Address having the integer value specified by the argument.
928   *
929   * @param address {@code int}, the 32bit integer address to be converted
930   * @return {@link Inet4Address} equivalent of the argument
931   */
932  public static Inet4Address fromInteger(int address) {
933    return getInet4Address(Ints.toByteArray(address));
934  }
935
936  /**
937   * Returns the {@code Inet4Address} corresponding to a given {@code BigInteger}.
938   *
939   * @param address BigInteger representing the IPv4 address
940   * @return Inet4Address representation of the given BigInteger
941   * @throws IllegalArgumentException if the BigInteger is not between 0 and 2^32-1
942   * @since 28.2
943   */
944  public static Inet4Address fromIPv4BigInteger(BigInteger address) {
945    return (Inet4Address) fromBigInteger(address, false);
946  }
947  /**
948   * Returns the {@code Inet6Address} corresponding to a given {@code BigInteger}.
949   *
950   * @param address BigInteger representing the IPv6 address
951   * @return Inet6Address representation of the given BigInteger
952   * @throws IllegalArgumentException if the BigInteger is not between 0 and 2^128-1
953   * @since 28.2
954   */
955  public static Inet6Address fromIPv6BigInteger(BigInteger address) {
956    return (Inet6Address) fromBigInteger(address, true);
957  }
958
959  /**
960   * Converts a BigInteger to either an IPv4 or IPv6 address. If the IP is IPv4, it must be
961   * constrainted to 32 bits, otherwise it is constrained to 128 bits.
962   *
963   * @param address the address represented as a big integer
964   * @param isIpv6 whether the created address should be IPv4 or IPv6
965   * @return the BigInteger converted to an address
966   * @throws IllegalArgumentException if the BigInteger is not between 0 and maximum value for IPv4
967   *     or IPv6 respectively
968   */
969  private static InetAddress fromBigInteger(BigInteger address, boolean isIpv6) {
970    checkArgument(address.signum() >= 0, "BigInteger must be greater than or equal to 0");
971
972    int numBytes = isIpv6 ? 16 : 4;
973
974    byte[] addressBytes = address.toByteArray();
975    byte[] targetCopyArray = new byte[numBytes];
976
977    int srcPos = Math.max(0, addressBytes.length - numBytes);
978    int copyLength = addressBytes.length - srcPos;
979    int destPos = numBytes - copyLength;
980
981    // Check the extra bytes in the BigInteger are all zero.
982    for (int i = 0; i < srcPos; i++) {
983      if (addressBytes[i] != 0x00) {
984        throw formatIllegalArgumentException(
985            "BigInteger cannot be converted to InetAddress because it has more than %d"
986                + " bytes: %s",
987            numBytes, address);
988      }
989    }
990
991    // Copy the bytes into the least significant positions.
992    System.arraycopy(addressBytes, srcPos, targetCopyArray, destPos, copyLength);
993
994    try {
995      return InetAddress.getByAddress(targetCopyArray);
996    } catch (UnknownHostException impossible) {
997      throw new AssertionError(impossible);
998    }
999  }
1000
1001  /**
1002   * Returns an address from a <b>little-endian ordered</b> byte array (the opposite of what {@link
1003   * InetAddress#getByAddress} expects).
1004   *
1005   * <p>IPv4 address byte array must be 4 bytes long and IPv6 byte array must be 16 bytes long.
1006   *
1007   * @param addr the raw IP address in little-endian byte order
1008   * @return an InetAddress object created from the raw IP address
1009   * @throws UnknownHostException if IP address is of illegal length
1010   */
1011  public static InetAddress fromLittleEndianByteArray(byte[] addr) throws UnknownHostException {
1012    byte[] reversed = new byte[addr.length];
1013    for (int i = 0; i < addr.length; i++) {
1014      reversed[i] = addr[addr.length - i - 1];
1015    }
1016    return InetAddress.getByAddress(reversed);
1017  }
1018
1019  /**
1020   * Returns a new InetAddress that is one less than the passed in address. This method works for
1021   * both IPv4 and IPv6 addresses.
1022   *
1023   * @param address the InetAddress to decrement
1024   * @return a new InetAddress that is one less than the passed in address
1025   * @throws IllegalArgumentException if InetAddress is at the beginning of its range
1026   * @since 18.0
1027   */
1028  public static InetAddress decrement(InetAddress address) {
1029    byte[] addr = address.getAddress();
1030    int i = addr.length - 1;
1031    while (i >= 0 && addr[i] == (byte) 0x00) {
1032      addr[i] = (byte) 0xff;
1033      i--;
1034    }
1035
1036    checkArgument(i >= 0, "Decrementing %s would wrap.", address);
1037
1038    addr[i]--;
1039    return bytesToInetAddress(addr);
1040  }
1041
1042  /**
1043   * Returns a new InetAddress that is one more than the passed in address. This method works for
1044   * both IPv4 and IPv6 addresses.
1045   *
1046   * @param address the InetAddress to increment
1047   * @return a new InetAddress that is one more than the passed in address
1048   * @throws IllegalArgumentException if InetAddress is at the end of its range
1049   * @since 10.0
1050   */
1051  public static InetAddress increment(InetAddress address) {
1052    byte[] addr = address.getAddress();
1053    int i = addr.length - 1;
1054    while (i >= 0 && addr[i] == (byte) 0xff) {
1055      addr[i] = 0;
1056      i--;
1057    }
1058
1059    checkArgument(i >= 0, "Incrementing %s would wrap.", address);
1060
1061    addr[i]++;
1062    return bytesToInetAddress(addr);
1063  }
1064
1065  /**
1066   * Returns true if the InetAddress is either 255.255.255.255 for IPv4 or
1067   * ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6.
1068   *
1069   * @return true if the InetAddress is either 255.255.255.255 for IPv4 or
1070   *     ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6
1071   * @since 10.0
1072   */
1073  public static boolean isMaximum(InetAddress address) {
1074    byte[] addr = address.getAddress();
1075    for (int i = 0; i < addr.length; i++) {
1076      if (addr[i] != (byte) 0xff) {
1077        return false;
1078      }
1079    }
1080    return true;
1081  }
1082
1083  private static IllegalArgumentException formatIllegalArgumentException(
1084      String format, Object... args) {
1085    return new IllegalArgumentException(String.format(Locale.ROOT, format, args));
1086  }
1087}