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
017 package com.google.common.net;
018
019 import com.google.common.annotations.Beta;
020 import com.google.common.base.Objects;
021 import com.google.common.base.Preconditions;
022 import com.google.common.hash.Hashing;
023 import com.google.common.io.ByteStreams;
024 import com.google.common.primitives.Ints;
025
026 import java.net.Inet4Address;
027 import java.net.Inet6Address;
028 import java.net.InetAddress;
029 import java.net.UnknownHostException;
030 import java.nio.ByteBuffer;
031 import java.util.Arrays;
032
033 import javax.annotation.Nullable;
034
035 /**
036 * Static utility methods pertaining to {@link InetAddress} instances.
037 *
038 * <p><b>Important note:</b> Unlike {@code InetAddress.getByName()}, the
039 * methods of this class never cause DNS services to be accessed. For
040 * this reason, you should prefer these methods as much as possible over
041 * their JDK equivalents whenever you are expecting to handle only
042 * IP address string literals -- there is no blocking DNS penalty for a
043 * malformed string.
044 *
045 * <p>When dealing with {@link Inet4Address} and {@link Inet6Address}
046 * objects as byte arrays (vis. {@code InetAddress.getAddress()}) they
047 * are 4 and 16 bytes in length, respectively, and represent the address
048 * in network byte order.
049 *
050 * <p>Examples of IP addresses and their byte representations:
051 * <ul>
052 * <li>The IPv4 loopback address, {@code "127.0.0.1"}.<br/>
053 * {@code 7f 00 00 01}
054 *
055 * <li>The IPv6 loopback address, {@code "::1"}.<br/>
056 * {@code 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01}
057 *
058 * <li>From the IPv6 reserved documentation prefix ({@code 2001:db8::/32}),
059 * {@code "2001:db8::1"}.<br/>
060 * {@code 20 01 0d b8 00 00 00 00 00 00 00 00 00 00 00 01}
061 *
062 * <li>An IPv6 "IPv4 compatible" (or "compat") address,
063 * {@code "::192.168.0.1"}.<br/>
064 * {@code 00 00 00 00 00 00 00 00 00 00 00 00 c0 a8 00 01}
065 *
066 * <li>An IPv6 "IPv4 mapped" address, {@code "::ffff:192.168.0.1"}.<br/>
067 * {@code 00 00 00 00 00 00 00 00 00 00 ff ff c0 a8 00 01}
068 * </ul>
069 *
070 * <p>A few notes about IPv6 "IPv4 mapped" addresses and their observed
071 * use in Java.
072 * <br><br>
073 * "IPv4 mapped" addresses were originally a representation of IPv4
074 * addresses for use on an IPv6 socket that could receive both IPv4
075 * and IPv6 connections (by disabling the {@code IPV6_V6ONLY} socket
076 * option on an IPv6 socket). Yes, it's confusing. Nevertheless,
077 * these "mapped" addresses were never supposed to be seen on the
078 * wire. That assumption was dropped, some say mistakenly, in later
079 * RFCs with the apparent aim of making IPv4-to-IPv6 transition simpler.
080 *
081 * <p>Technically one <i>can</i> create a 128bit IPv6 address with the wire
082 * format of a "mapped" address, as shown above, and transmit it in an
083 * IPv6 packet header. However, Java's InetAddress creation methods
084 * appear to adhere doggedly to the original intent of the "mapped"
085 * address: all "mapped" addresses return {@link Inet4Address} objects.
086 *
087 * <p>For added safety, it is common for IPv6 network operators to filter
088 * all packets where either the source or destination address appears to
089 * be a "compat" or "mapped" address. Filtering suggestions usually
090 * recommend discarding any packets with source or destination addresses
091 * in the invalid range {@code ::/3}, which includes both of these bizarre
092 * address formats. For more information on "bogons", including lists
093 * of IPv6 bogon space, see:
094 *
095 * <ul>
096 * <li><a target="_parent"
097 * href="http://en.wikipedia.org/wiki/Bogon_filtering"
098 * >http://en.wikipedia.org/wiki/Bogon_filtering</a>
099 * <li><a target="_parent"
100 * href="http://www.cymru.com/Bogons/ipv6.txt"
101 * >http://www.cymru.com/Bogons/ipv6.txt</a>
102 * <li><a target="_parent"
103 * href="http://www.cymru.com/Bogons/v6bogon.html"
104 * >http://www.cymru.com/Bogons/v6bogon.html</a>
105 * <li><a target="_parent"
106 * href="http://www.space.net/~gert/RIPE/ipv6-filters.html"
107 * >http://www.space.net/~gert/RIPE/ipv6-filters.html</a>
108 * </ul>
109 *
110 * @author Erik Kline
111 * @since 5.0
112 */
113 @Beta
114 public final class InetAddresses {
115 private static final int IPV4_PART_COUNT = 4;
116 private static final int IPV6_PART_COUNT = 8;
117 private static final Inet4Address LOOPBACK4 = (Inet4Address) forString("127.0.0.1");
118 private static final Inet4Address ANY4 = (Inet4Address) forString("0.0.0.0");
119
120 private InetAddresses() {}
121
122 /**
123 * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address.
124 *
125 * @param bytes byte array representing an IPv4 address (should be of length 4)
126 * @return {@link Inet4Address} corresponding to the supplied byte array
127 * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created
128 */
129 private static Inet4Address getInet4Address(byte[] bytes) {
130 Preconditions.checkArgument(bytes.length == 4,
131 "Byte array has invalid length for an IPv4 address: %s != 4.",
132 bytes.length);
133
134 // Given a 4-byte array, this cast should always succeed.
135 return (Inet4Address) bytesToInetAddress(bytes);
136 }
137
138 /**
139 * Returns the {@link InetAddress} having the given string representation.
140 *
141 * <p>This deliberately avoids all nameservice lookups (e.g. no DNS).
142 *
143 * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g.
144 * {@code "192.168.0.1"} or {@code "2001:db8::1"}
145 * @return {@link InetAddress} representing the argument
146 * @throws IllegalArgumentException if the argument is not a valid IP string literal
147 */
148 public static InetAddress forString(String ipString) {
149 byte[] addr = ipStringToBytes(ipString);
150
151 // The argument was malformed, i.e. not an IP string literal.
152 if (addr == null) {
153 throw new IllegalArgumentException(
154 String.format("'%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 if 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 new IllegalArgumentException(
502 String.format("Not a valid URI IP literal: '%s'", hostAddr));
503 }
504
505 return bytesToInetAddress(addr);
506 }
507
508 /**
509 * Returns {@code true} if the supplied string is a valid URI IP string
510 * literal, {@code false} otherwise.
511 *
512 * @param ipString {@code String} to evaluated as an IP URI host string literal
513 * @return {@code true} if the argument is a valid IP URI host
514 */
515 public static boolean isUriInetAddress(String ipString) {
516 try {
517 forUriString(ipString);
518 return true;
519 } catch (IllegalArgumentException e) {
520 return false;
521 }
522 }
523
524 /**
525 * Evaluates whether the argument is an IPv6 "compat" address.
526 *
527 * <p>An "IPv4 compatible", or "compat", address is one with 96 leading
528 * bits of zero, with the remaining 32 bits interpreted as an
529 * IPv4 address. These are conventionally represented in string
530 * literals as {@code "::192.168.0.1"}, though {@code "::c0a8:1"} is
531 * also considered an IPv4 compatible address (and equivalent to
532 * {@code "::192.168.0.1"}).
533 *
534 * <p>For more on IPv4 compatible addresses see section 2.5.5.1 of
535 * <a target="_parent"
536 * href="http://tools.ietf.org/html/rfc4291#section-2.5.5.1"
537 * >http://tools.ietf.org/html/rfc4291</a>
538 *
539 * <p>NOTE: This method is different from
540 * {@link Inet6Address#isIPv4CompatibleAddress} in that it more
541 * correctly classifies {@code "::"} and {@code "::1"} as
542 * proper IPv6 addresses (which they are), NOT IPv4 compatible
543 * addresses (which they are generally NOT considered to be).
544 *
545 * @param ip {@link Inet6Address} to be examined for embedded IPv4 compatible address format
546 * @return {@code true} if the argument is a valid "compat" address
547 */
548 public static boolean isCompatIPv4Address(Inet6Address ip) {
549 if (!ip.isIPv4CompatibleAddress()) {
550 return false;
551 }
552
553 byte[] bytes = ip.getAddress();
554 if ((bytes[12] == 0) && (bytes[13] == 0) && (bytes[14] == 0)
555 && ((bytes[15] == 0) || (bytes[15] == 1))) {
556 return false;
557 }
558
559 return true;
560 }
561
562 /**
563 * Java 5 substitute for Arrays.copyOfRange.
564 */
565 private static byte[] copyOfRange(byte[] array, int fromIndex, int toIndex) {
566 byte[] result = new byte[toIndex - fromIndex];
567 System.arraycopy(array, fromIndex, result, 0, toIndex - fromIndex);
568 return result;
569 }
570
571 /**
572 * Returns the IPv4 address embedded in an IPv4 compatible address.
573 *
574 * @param ip {@link Inet6Address} to be examined for an embedded IPv4 address
575 * @return {@link Inet4Address} of the embedded IPv4 address
576 * @throws IllegalArgumentException if the argument is not a valid IPv4 compatible address
577 */
578 public static Inet4Address getCompatIPv4Address(Inet6Address ip) {
579 Preconditions.checkArgument(isCompatIPv4Address(ip),
580 "Address '%s' is not IPv4-compatible.", toAddrString(ip));
581
582 return getInet4Address(copyOfRange(ip.getAddress(), 12, 16));
583 }
584
585 /**
586 * Evaluates whether the argument is a 6to4 address.
587 *
588 * <p>6to4 addresses begin with the {@code "2002::/16"} prefix.
589 * The next 32 bits are the IPv4 address of the host to which
590 * IPv6-in-IPv4 tunneled packets should be routed.
591 *
592 * <p>For more on 6to4 addresses see section 2 of
593 * <a target="_parent" href="http://tools.ietf.org/html/rfc3056#section-2"
594 * >http://tools.ietf.org/html/rfc3056</a>
595 *
596 * @param ip {@link Inet6Address} to be examined for 6to4 address format
597 * @return {@code true} if the argument is a 6to4 address
598 */
599 public static boolean is6to4Address(Inet6Address ip) {
600 byte[] bytes = ip.getAddress();
601 return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x02);
602 }
603
604 /**
605 * Returns the IPv4 address embedded in a 6to4 address.
606 *
607 * @param ip {@link Inet6Address} to be examined for embedded IPv4 in 6to4 address
608 * @return {@link Inet4Address} of embedded IPv4 in 6to4 address
609 * @throws IllegalArgumentException if the argument is not a valid IPv6 6to4 address
610 */
611 public static Inet4Address get6to4IPv4Address(Inet6Address ip) {
612 Preconditions.checkArgument(is6to4Address(ip),
613 "Address '%s' is not a 6to4 address.", toAddrString(ip));
614
615 return getInet4Address(copyOfRange(ip.getAddress(), 2, 6));
616 }
617
618 /**
619 * A simple immutable data class to encapsulate the information to be found in a
620 * Teredo address.
621 *
622 * <p>All of the fields in this class are encoded in various portions
623 * of the IPv6 address as part of the protocol. More protocols details
624 * can be found at:
625 * <a target="_parent" href="http://en.wikipedia.org/wiki/Teredo_tunneling"
626 * >http://en.wikipedia.org/wiki/Teredo_tunneling</a>.
627 *
628 * <p>The RFC can be found here:
629 * <a target="_parent" href="http://tools.ietf.org/html/rfc4380"
630 * >http://tools.ietf.org/html/rfc4380</a>.
631 *
632 * @since 5.0
633 */
634 @Beta
635 public static final class TeredoInfo {
636 private final Inet4Address server;
637 private final Inet4Address client;
638 private final int port;
639 private final int flags;
640
641 /**
642 * Constructs a TeredoInfo instance.
643 *
644 * <p>Both server and client can be {@code null}, in which case the
645 * value {@code "0.0.0.0"} will be assumed.
646 *
647 * @throws IllegalArgumentException if either of the {@code port} or the {@code flags}
648 * arguments are out of range of an unsigned short
649 */
650 // TODO: why is this public?
651 public TeredoInfo(
652 @Nullable Inet4Address server, @Nullable Inet4Address client, int port, int flags) {
653 Preconditions.checkArgument((port >= 0) && (port <= 0xffff),
654 "port '%s' is out of range (0 <= port <= 0xffff)", port);
655 Preconditions.checkArgument((flags >= 0) && (flags <= 0xffff),
656 "flags '%s' is out of range (0 <= flags <= 0xffff)", flags);
657
658 this.server = Objects.firstNonNull(server, ANY4);
659 this.client = Objects.firstNonNull(client, ANY4);
660 this.port = port;
661 this.flags = flags;
662 }
663
664 public Inet4Address getServer() {
665 return server;
666 }
667
668 public Inet4Address getClient() {
669 return client;
670 }
671
672 public int getPort() {
673 return port;
674 }
675
676 public int getFlags() {
677 return flags;
678 }
679 }
680
681 /**
682 * Evaluates whether the argument is a Teredo address.
683 *
684 * <p>Teredo addresses begin with the {@code "2001::/32"} prefix.
685 *
686 * @param ip {@link Inet6Address} to be examined for Teredo address format
687 * @return {@code true} if the argument is a Teredo address
688 */
689 public static boolean isTeredoAddress(Inet6Address ip) {
690 byte[] bytes = ip.getAddress();
691 return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x01)
692 && (bytes[2] == 0) && (bytes[3] == 0);
693 }
694
695 /**
696 * Returns the Teredo information embedded in a Teredo address.
697 *
698 * @param ip {@link Inet6Address} to be examined for embedded Teredo information
699 * @return extracted {@code TeredoInfo}
700 * @throws IllegalArgumentException if the argument is not a valid IPv6 Teredo address
701 */
702 public static TeredoInfo getTeredoInfo(Inet6Address ip) {
703 Preconditions.checkArgument(isTeredoAddress(ip),
704 "Address '%s' is not a Teredo address.", toAddrString(ip));
705
706 byte[] bytes = ip.getAddress();
707 Inet4Address server = getInet4Address(copyOfRange(bytes, 4, 8));
708
709 int flags = ByteStreams.newDataInput(bytes, 8).readShort() & 0xffff;
710
711 // Teredo obfuscates the mapped client port, per section 4 of the RFC.
712 int port = ~ByteStreams.newDataInput(bytes, 10).readShort() & 0xffff;
713
714 byte[] clientBytes = copyOfRange(bytes, 12, 16);
715 for (int i = 0; i < clientBytes.length; i++) {
716 // Teredo obfuscates the mapped client IP, per section 4 of the RFC.
717 clientBytes[i] = (byte) ~clientBytes[i];
718 }
719 Inet4Address client = getInet4Address(clientBytes);
720
721 return new TeredoInfo(server, client, port, flags);
722 }
723
724 /**
725 * Evaluates whether the argument is an ISATAP address.
726 *
727 * <p>From RFC 5214: "ISATAP interface identifiers are constructed in
728 * Modified EUI-64 format [...] by concatenating the 24-bit IANA OUI
729 * (00-00-5E), the 8-bit hexadecimal value 0xFE, and a 32-bit IPv4
730 * address in network byte order [...]"
731 *
732 * <p>For more on ISATAP addresses see section 6.1 of
733 * <a target="_parent" href="http://tools.ietf.org/html/rfc5214#section-6.1"
734 * >http://tools.ietf.org/html/rfc5214</a>
735 *
736 * @param ip {@link Inet6Address} to be examined for ISATAP address format
737 * @return {@code true} if the argument is an ISATAP address
738 */
739 public static boolean isIsatapAddress(Inet6Address ip) {
740
741 // If it's a Teredo address with the right port (41217, or 0xa101)
742 // which would be encoded as 0x5efe then it can't be an ISATAP address.
743 if (isTeredoAddress(ip)) {
744 return false;
745 }
746
747 byte[] bytes = ip.getAddress();
748
749 if ((bytes[8] | (byte) 0x03) != (byte) 0x03) {
750
751 // Verify that high byte of the 64 bit identifier is zero, modulo
752 // the U/L and G bits, with which we are not concerned.
753 return false;
754 }
755
756 return (bytes[9] == (byte) 0x00) && (bytes[10] == (byte) 0x5e)
757 && (bytes[11] == (byte) 0xfe);
758 }
759
760 /**
761 * Returns the IPv4 address embedded in an ISATAP address.
762 *
763 * @param ip {@link Inet6Address} to be examined for embedded IPv4 in ISATAP address
764 * @return {@link Inet4Address} of embedded IPv4 in an ISATAP address
765 * @throws IllegalArgumentException if the argument is not a valid IPv6 ISATAP address
766 */
767 public static Inet4Address getIsatapIPv4Address(Inet6Address ip) {
768 Preconditions.checkArgument(isIsatapAddress(ip),
769 "Address '%s' is not an ISATAP address.", toAddrString(ip));
770
771 return getInet4Address(copyOfRange(ip.getAddress(), 12, 16));
772 }
773
774 /**
775 * Examines the Inet6Address to determine if it is an IPv6 address of one
776 * of the specified address types that contain an embedded IPv4 address.
777 *
778 * <p>NOTE: ISATAP addresses are explicitly excluded from this method
779 * due to their trivial spoofability. With other transition addresses
780 * spoofing involves (at least) infection of one's BGP routing table.
781 *
782 * @param ip {@link Inet6Address} to be examined for embedded IPv4 client address
783 * @return {@code true} if there is an embedded IPv4 client address
784 * @since 7.0
785 */
786 public static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip) {
787 return isCompatIPv4Address(ip) || is6to4Address(ip) || isTeredoAddress(ip);
788 }
789
790 /**
791 * Examines the Inet6Address to extract the embedded IPv4 client address
792 * if the InetAddress is an IPv6 address of one of the specified address
793 * types that contain an embedded IPv4 address.
794 *
795 * <p>NOTE: ISATAP addresses are explicitly excluded from this method
796 * due to their trivial spoofability. With other transition addresses
797 * spoofing involves (at least) infection of one's BGP routing table.
798 *
799 * @param ip {@link Inet6Address} to be examined for embedded IPv4 client address
800 * @return {@link Inet4Address} of embedded IPv4 client address
801 * @throws IllegalArgumentException if the argument does not have a valid embedded IPv4 address
802 */
803 public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) {
804 if (isCompatIPv4Address(ip)) {
805 return getCompatIPv4Address(ip);
806 }
807
808 if (is6to4Address(ip)) {
809 return get6to4IPv4Address(ip);
810 }
811
812 if (isTeredoAddress(ip)) {
813 return getTeredoInfo(ip).getClient();
814 }
815
816 throw new IllegalArgumentException(
817 String.format("'%s' has no embedded IPv4 address.", toAddrString(ip)));
818 }
819
820 /**
821 * Evaluates whether the argument is an "IPv4 mapped" IPv6 address.
822 *
823 * <p>An "IPv4 mapped" address is anything in the range ::ffff:0:0/96
824 * (sometimes written as ::ffff:0.0.0.0/96), with the last 32 bits
825 * interpreted as an IPv4 address.
826 *
827 * <p>For more on IPv4 mapped addresses see section 2.5.5.2 of
828 * <a target="_parent"
829 * href="http://tools.ietf.org/html/rfc4291#section-2.5.5.2"
830 * >http://tools.ietf.org/html/rfc4291</a>
831 *
832 * <p>Note: This method takes a {@code String} argument because
833 * {@link InetAddress} automatically collapses mapped addresses to IPv4.
834 * (It is actually possible to avoid this using one of the obscure
835 * {@link Inet6Address} methods, but it would be unwise to depend on such
836 * a poorly-documented feature.)
837 *
838 * @param ipString {@code String} to be examined for embedded IPv4-mapped IPv6 address format
839 * @return {@code true} if the argument is a valid "mapped" address
840 * @since 10.0
841 */
842 public static boolean isMappedIPv4Address(String ipString) {
843 byte[] bytes = ipStringToBytes(ipString);
844 if (bytes != null && bytes.length == 16) {
845 for (int i = 0; i < 10; i++) {
846 if (bytes[i] != 0) {
847 return false;
848 }
849 }
850 for (int i = 10; i < 12; i++) {
851 if (bytes[i] != (byte) 0xff) {
852 return false;
853 }
854 }
855 return true;
856 }
857 return false;
858 }
859
860 /**
861 * Coerces an IPv6 address into an IPv4 address.
862 *
863 * <p>HACK: As long as applications continue to use IPv4 addresses for
864 * indexing into tables, accounting, et cetera, it may be necessary to
865 * <b>coerce</b> IPv6 addresses into IPv4 addresses. This function does
866 * so by hashing the upper 64 bits into {@code 224.0.0.0/3}
867 * (64 bits into 29 bits).
868 *
869 * <p>A "coerced" IPv4 address is equivalent to itself.
870 *
871 * <p>NOTE: This function is failsafe for security purposes: ALL IPv6
872 * addresses (except localhost (::1)) are hashed to avoid the security
873 * risk associated with extracting an embedded IPv4 address that might
874 * permit elevated privileges.
875 *
876 * @param ip {@link InetAddress} to "coerce"
877 * @return {@link Inet4Address} represented "coerced" address
878 * @since 7.0
879 */
880 public static Inet4Address getCoercedIPv4Address(InetAddress ip) {
881 if (ip instanceof Inet4Address) {
882 return (Inet4Address) ip;
883 }
884
885 // Special cases:
886 byte[] bytes = ip.getAddress();
887 boolean leadingBytesOfZero = true;
888 for (int i = 0; i < 15; ++i) {
889 if (bytes[i] != 0) {
890 leadingBytesOfZero = false;
891 break;
892 }
893 }
894 if (leadingBytesOfZero && (bytes[15] == 1)) {
895 return LOOPBACK4; // ::1
896 } else if (leadingBytesOfZero && (bytes[15] == 0)) {
897 return ANY4; // ::0
898 }
899
900 Inet6Address ip6 = (Inet6Address) ip;
901 long addressAsLong = 0;
902 if (hasEmbeddedIPv4ClientAddress(ip6)) {
903 addressAsLong = getEmbeddedIPv4ClientAddress(ip6).hashCode();
904 } else {
905
906 // Just extract the high 64 bits (assuming the rest is user-modifiable).
907 addressAsLong = ByteBuffer.wrap(ip6.getAddress(), 0, 8).getLong();
908 }
909
910 // Many strategies for hashing are possible. This might suffice for now.
911 int coercedHash = Hashing.murmur3_32().hashLong(addressAsLong).asInt();
912
913 // Squash into 224/4 Multicast and 240/4 Reserved space (i.e. 224/3).
914 coercedHash |= 0xe0000000;
915
916 // Fixup to avoid some "illegal" values. Currently the only potential
917 // illegal value is 255.255.255.255.
918 if (coercedHash == 0xffffffff) {
919 coercedHash = 0xfffffffe;
920 }
921
922 return getInet4Address(Ints.toByteArray(coercedHash));
923 }
924
925 /**
926 * Returns an integer representing an IPv4 address regardless of
927 * whether the supplied argument is an IPv4 address or not.
928 *
929 * <p>IPv6 addresses are <b>coerced</b> to IPv4 addresses before being
930 * converted to integers.
931 *
932 * <p>As long as there are applications that assume that all IP addresses
933 * are IPv4 addresses and can therefore be converted safely to integers
934 * (for whatever purpose) this function can be used to handle IPv6
935 * addresses as well until the application is suitably fixed.
936 *
937 * <p>NOTE: an IPv6 address coerced to an IPv4 address can only be used
938 * for such purposes as rudimentary identification or indexing into a
939 * collection of real {@link InetAddress}es. They cannot be used as
940 * real addresses for the purposes of network communication.
941 *
942 * @param ip {@link InetAddress} to convert
943 * @return {@code int}, "coerced" if ip is not an IPv4 address
944 * @since 7.0
945 */
946 public static int coerceToInteger(InetAddress ip) {
947 return ByteStreams.newDataInput(getCoercedIPv4Address(ip).getAddress()).readInt();
948 }
949
950 /**
951 * Returns an Inet4Address having the integer value specified by
952 * the argument.
953 *
954 * @param address {@code int}, the 32bit integer address to be converted
955 * @return {@link Inet4Address} equivalent of the argument
956 */
957 public static Inet4Address fromInteger(int address) {
958 return getInet4Address(Ints.toByteArray(address));
959 }
960
961 /**
962 * Returns an address from a <b>little-endian ordered</b> byte array
963 * (the opposite of what {@link InetAddress#getByAddress} expects).
964 *
965 * <p>IPv4 address byte array must be 4 bytes long and IPv6 byte array
966 * must be 16 bytes long.
967 *
968 * @param addr the raw IP address in little-endian byte order
969 * @return an InetAddress object created from the raw IP address
970 * @throws UnknownHostException if IP address is of illegal length
971 */
972 public static InetAddress fromLittleEndianByteArray(byte[] addr) throws UnknownHostException {
973 byte[] reversed = new byte[addr.length];
974 for (int i = 0; i < addr.length; i++) {
975 reversed[i] = addr[addr.length - i - 1];
976 }
977 return InetAddress.getByAddress(reversed);
978 }
979
980 /**
981 * Returns a new InetAddress that is one more than the passed in address.
982 * This method works for both IPv4 and IPv6 addresses.
983 *
984 * @param address the InetAddress to increment
985 * @return a new InetAddress that is one more than the passed in address
986 * @throws IllegalArgumentException if InetAddress is at the end of its range
987 * @since 10.0
988 */
989 public static InetAddress increment(InetAddress address) {
990 byte[] addr = address.getAddress();
991 int i = addr.length - 1;
992 while (i >= 0 && addr[i] == (byte) 0xff) {
993 addr[i] = 0;
994 i--;
995 }
996
997 Preconditions.checkArgument(i >= 0, "Incrementing %s would wrap.", address);
998
999 addr[i]++;
1000 return bytesToInetAddress(addr);
1001 }
1002
1003 /**
1004 * Returns true if the InetAddress is either 255.255.255.255 for IPv4 or
1005 * ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6.
1006 *
1007 * @return true if the InetAddress is either 255.255.255.255 for IPv4 or
1008 * ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6
1009 * @since 10.0
1010 */
1011 public static boolean isMaximum(InetAddress address) {
1012 byte[] addr = address.getAddress();
1013 for (int i = 0; i < addr.length; i++) {
1014 if (addr[i] != (byte) 0xff) {
1015 return false;
1016 }
1017 }
1018 return true;
1019 }
1020 }