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