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