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