blob: 8a8aca26e25236bc28dca338a2413c5addd48906 [file] [log] [blame]
Thomas Vachuska24c849c2014-10-27 09:53:05 -07001/*
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07002 * Copyright 2014 Open Networking Laboratory
Thomas Vachuska24c849c2014-10-27 09:53:05 -07003 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07004 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
Thomas Vachuska24c849c2014-10-27 09:53:05 -07007 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07008 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
Thomas Vachuska24c849c2014-10-27 09:53:05 -070015 */
Jonathan Hartdec62d42014-09-22 15:59:04 -070016package org.onlab.packet;
17
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -070018import java.net.InetAddress;
19import java.net.Inet4Address;
20import java.net.Inet6Address;
21import java.net.UnknownHostException;
Pavlin Radoslavov52307e62014-10-29 15:07:37 -070022import java.nio.ByteBuffer;
Jonathan Hartdec62d42014-09-22 15:59:04 -070023import java.util.Arrays;
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -070024import java.util.Objects;
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -070025
26import com.google.common.net.InetAddresses;
27import com.google.common.primitives.UnsignedBytes;
28
29import static com.google.common.base.Preconditions.checkState;
Jonathan Hartdec62d42014-09-22 15:59:04 -070030
31/**
Pavlin Radoslavov855ea2d2014-10-30 15:32:39 -070032 * A class representing an IP address.
Pavlin Radoslavovf182f012014-11-04 15:03:18 -080033 * This class is immutable.
Jonathan Hartdec62d42014-09-22 15:59:04 -070034 */
Pavlin Radoslavovf182f012014-11-04 15:03:18 -080035public class IpAddress implements Comparable<IpAddress> {
Pavlin Radoslavov52307e62014-10-29 15:07:37 -070036 // IP Versions
Jonathan Hartdec62d42014-09-22 15:59:04 -070037 public enum Version { INET, INET6 };
38
Pavlin Radoslavov52307e62014-10-29 15:07:37 -070039 // lengths of address, in bytes
40 public static final int INET_BYTE_LENGTH = 4;
41 public static final int INET_BIT_LENGTH = INET_BYTE_LENGTH * Byte.SIZE;
42 public static final int INET6_BYTE_LENGTH = 16;
43 public static final int INET6_BIT_LENGTH = INET6_BYTE_LENGTH * Byte.SIZE;
Jonathan Hartdec62d42014-09-22 15:59:04 -070044
Pavlin Radoslavov52307e62014-10-29 15:07:37 -070045 private final Version version;
46 private final byte[] octets;
Jonathan Hartdec62d42014-09-22 15:59:04 -070047
48 /**
Pavlin Radoslavov52307e62014-10-29 15:07:37 -070049 * Constructor for given IP address version and address octets.
50 *
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -070051 * @param version the IP address version
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -070052 * @param value the IP address value stored in network byte order
Pavlin Radoslavov52307e62014-10-29 15:07:37 -070053 * (i.e., the most significant byte first)
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -070054 * @throws IllegalArgumentException if the arguments are invalid
Jonathan Hartdec62d42014-09-22 15:59:04 -070055 */
Pavlin Radoslavovf182f012014-11-04 15:03:18 -080056 protected IpAddress(Version version, byte[] value) {
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -070057 checkArguments(version, value, 0);
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -070058 this.version = version;
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -070059 switch (version) {
60 case INET:
61 this.octets = Arrays.copyOf(value, INET_BYTE_LENGTH);
62 break;
63 case INET6:
64 this.octets = Arrays.copyOf(value, INET6_BYTE_LENGTH);
65 break;
66 default:
67 // Should not be reached
68 this.octets = null;
69 break;
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -070070 }
Jonathan Hartdec62d42014-09-22 15:59:04 -070071 }
72
73 /**
74 * Returns the IP version of this address.
75 *
76 * @return the version
77 */
78 public Version version() {
79 return this.version;
80 }
81
82 /**
Pavlin Radoslavov34c81642014-11-04 16:21:38 -080083 * Gets the {@link Ip4Address} view of the IP address.
84 *
85 * @return the {@link Ip4Address} view of the IP address if it is IPv4,
86 * otherwise null
87 */
88 public Ip4Address getIp4Address() {
89 if (version() != Ip4Address.VERSION) {
90 return null;
91 }
92
93 // Return this object itself if it is already instance of Ip4Address
94 if (this instanceof Ip4Address) {
95 return (Ip4Address) this;
96 }
97 return Ip4Address.valueOf(octets);
98 }
99
100 /**
101 * Gets the {@link Ip6Address} view of the IP address.
102 *
103 * @return the {@link Ip6Address} view of the IP address if it is IPv6,
104 * otherwise null
105 */
106 public Ip6Address getIp6Address() {
107 if (version() != Ip6Address.VERSION) {
108 return null;
109 }
110
111 // Return this object itself if it is already instance of Ip6Address
112 if (this instanceof Ip6Address) {
113 return (Ip6Address) this;
114 }
115 return Ip6Address.valueOf(octets);
116 }
117
118 /**
Jonathan Hartdec62d42014-09-22 15:59:04 -0700119 * Returns the IP address as a byte array.
120 *
121 * @return a byte array
122 */
123 public byte[] toOctets() {
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700124 return Arrays.copyOf(octets, octets.length);
Jonathan Hartdec62d42014-09-22 15:59:04 -0700125 }
126
127 /**
Pavlin Radoslavovf182f012014-11-04 15:03:18 -0800128 * Returns the integer value of this IP address.
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700129 * TODO: This method should be moved to Ip4Address.
Jonathan Hartdec62d42014-09-22 15:59:04 -0700130 *
131 * @return the IP address's value as an integer
132 */
133 public int toInt() {
Pavlin Radoslavov52307e62014-10-29 15:07:37 -0700134 ByteBuffer bb = ByteBuffer.wrap(octets);
135 return bb.getInt();
Jonathan Hartdec62d42014-09-22 15:59:04 -0700136 }
137
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700138 /**
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700139 * Computes the IP address byte length for a given IP version.
140 *
141 * @param version the IP version
142 * @return the IP address byte length for the IP version
143 * @throws IllegalArgumentException if the IP version is invalid
144 */
145 public static int byteLength(Version version) {
146 switch (version) {
147 case INET:
148 return INET_BYTE_LENGTH;
149 case INET6:
150 return INET6_BYTE_LENGTH;
151 default:
152 String msg = "Invalid IP version " + version;
153 throw new IllegalArgumentException(msg);
154 }
155 }
156
157 /**
158 * Converts an integer into an IPv4 address.
159 *
160 * @param value an integer representing an IPv4 address value
161 * @return an IP address
162 */
163 public static IpAddress valueOf(int value) {
164 byte[] bytes =
165 ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array();
166 return new IpAddress(Version.INET, bytes);
167 }
168
169 /**
170 * Converts a byte array into an IP address.
171 *
172 * @param version the IP address version
173 * @param value the IP address value stored in network byte order
174 * (i.e., the most significant byte first)
175 * @return an IP address
176 * @throws IllegalArgumentException if the arguments are invalid
177 */
178 public static IpAddress valueOf(Version version, byte[] value) {
179 return new IpAddress(version, value);
180 }
181
182 /**
183 * Converts a byte array and a given offset from the beginning of the
184 * array into an IP address.
185 * <p>
186 * The IP address is stored in network byte order (i.e., the most
187 * significant byte first).
188 * </p>
189 * @param version the IP address version
190 * @param value the value to use
191 * @param offset the offset in bytes from the beginning of the byte array
192 * @return an IP address
193 * @throws IllegalArgumentException if the arguments are invalid
194 */
195 public static IpAddress valueOf(Version version, byte[] value,
196 int offset) {
197 checkArguments(version, value, offset);
198 byte[] bc = Arrays.copyOfRange(value, offset, value.length);
199 return IpAddress.valueOf(version, bc);
200 }
201
202 /**
Pavlin Radoslavovaf5ff792014-10-31 20:51:47 -0700203 * Converts an InetAddress into an IP address.
204 *
205 * @param inetAddress the InetAddress value to use
206 * @return an IP address
207 * @throws IllegalArgumentException if the argument is invalid
208 */
209 public static IpAddress valueOf(InetAddress inetAddress) {
210 byte[] bytes = inetAddress.getAddress();
211 if (inetAddress instanceof Inet4Address) {
212 return new IpAddress(Version.INET, bytes);
213 }
214 if (inetAddress instanceof Inet6Address) {
215 return new IpAddress(Version.INET6, bytes);
216 }
217 // Use the number of bytes as a hint
218 if (bytes.length == INET_BYTE_LENGTH) {
219 return new IpAddress(Version.INET, bytes);
220 }
221 if (bytes.length == INET6_BYTE_LENGTH) {
222 return new IpAddress(Version.INET6, bytes);
223 }
224 final String msg = "Unrecognized IP version address string: " +
225 inetAddress.toString();
226 throw new IllegalArgumentException(msg);
227 }
228
229 /**
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700230 * Converts an IPv4 or IPv6 string literal (e.g., "10.2.3.4" or
231 * "1111:2222::8888") into an IP address.
232 *
233 * @param value an IP address value in string form
234 * @return an IP address
235 * @throws IllegalArgumentException if the argument is invalid
236 */
237 public static IpAddress valueOf(String value) {
Pavlin Radoslavovaf5ff792014-10-31 20:51:47 -0700238 InetAddress inetAddress = null;
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700239 try {
Pavlin Radoslavovaf5ff792014-10-31 20:51:47 -0700240 inetAddress = InetAddresses.forString(value);
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700241 } catch (IllegalArgumentException e) {
242 final String msg = "Invalid IP address string: " + value;
243 throw new IllegalArgumentException(msg);
244 }
Pavlin Radoslavovaf5ff792014-10-31 20:51:47 -0700245 return valueOf(inetAddress);
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700246 }
247
248 /**
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700249 * Creates an IP network mask prefix.
250 *
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700251 * @param version the IP address version
Pavlin Radoslavov855ea2d2014-10-30 15:32:39 -0700252 * @param prefixLength the length of the mask prefix. Must be in the
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700253 * interval [0, 32] for IPv4, or [0, 128] for IPv6
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700254 * @return a new IP address that contains a mask prefix of the
255 * specified length
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700256 * @throws IllegalArgumentException if the arguments are invalid
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700257 */
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700258 public static IpAddress makeMaskPrefix(Version version, int prefixLength) {
Pavlin Radoslavovf182f012014-11-04 15:03:18 -0800259 byte[] mask = makeMaskPrefixArray(version, prefixLength);
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700260 return new IpAddress(version, mask);
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700261 }
262
263 /**
264 * Creates an IP address by masking it with a network mask of given
265 * mask length.
266 *
Pavlin Radoslavovf182f012014-11-04 15:03:18 -0800267 * @param address the address to mask
Pavlin Radoslavov855ea2d2014-10-30 15:32:39 -0700268 * @param prefixLength the length of the mask prefix. Must be in the
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700269 * interval [0, 32] for IPv4, or [0, 128] for IPv6
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700270 * @return a new IP address that is masked with a mask prefix of the
271 * specified length
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700272 * @throws IllegalArgumentException if the prefix length is invalid
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700273 */
Pavlin Radoslavovf182f012014-11-04 15:03:18 -0800274 public static IpAddress makeMaskedAddress(final IpAddress address,
Pavlin Radoslavov855ea2d2014-10-30 15:32:39 -0700275 int prefixLength) {
Pavlin Radoslavovf182f012014-11-04 15:03:18 -0800276 // TODO: The code below should go away and replaced with generics
277 if (address instanceof Ip4Address) {
278 Ip4Address ip4a = (Ip4Address) address;
279 return Ip4Address.makeMaskedAddress(ip4a, prefixLength);
280 } else if (address instanceof Ip6Address) {
281 Ip6Address ip6a = (Ip6Address) address;
282 return Ip6Address.makeMaskedAddress(ip6a, prefixLength);
283 } else {
284 byte[] net = makeMaskedAddressArray(address, prefixLength);
285 return IpAddress.valueOf(address.version(), net);
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700286 }
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700287 }
288
Jonathan Hartdec62d42014-09-22 15:59:04 -0700289 @Override
Jonathan Hartab63aac2014-10-16 08:52:55 -0700290 public int compareTo(IpAddress o) {
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700291 // Compare first the version
292 if (this.version != o.version) {
293 return this.version.compareTo(o.version);
294 }
295
296 // Compare the bytes, one-by-one
297 for (int i = 0; i < this.octets.length; i++) {
298 if (this.octets[i] != o.octets[i]) {
299 return UnsignedBytes.compare(this.octets[i], o.octets[i]);
300 }
301 }
302 return 0; // Equal
Jonathan Hartab63aac2014-10-16 08:52:55 -0700303 }
304
305 @Override
Jonathan Hartdec62d42014-09-22 15:59:04 -0700306 public int hashCode() {
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700307 return Objects.hash(version, Arrays.hashCode(octets));
Jonathan Hartdec62d42014-09-22 15:59:04 -0700308 }
309
310 @Override
311 public boolean equals(Object obj) {
Pavlin Radoslavov855ea2d2014-10-30 15:32:39 -0700312 if (this == obj) {
Jonathan Hartdec62d42014-09-22 15:59:04 -0700313 return true;
314 }
Pavlin Radoslavov50b70672014-11-05 11:22:25 -0800315 if ((obj == null) || (!(obj instanceof IpAddress))) {
Jonathan Hartdec62d42014-09-22 15:59:04 -0700316 return false;
317 }
318 IpAddress other = (IpAddress) obj;
Pavlin Radoslavov49e159a2014-10-29 16:22:13 -0700319 return (version == other.version) &&
320 Arrays.equals(octets, other.octets);
Jonathan Hartdec62d42014-09-22 15:59:04 -0700321 }
322
323 @Override
324 /*
325 * (non-Javadoc)
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700326 * The string representation of the IP address: "x.x.x.x" for IPv4
327 * addresses, or ':' separated string for IPv6 addresses.
Jonathan Hartdec62d42014-09-22 15:59:04 -0700328 *
329 * @see java.lang.Object#toString()
330 */
331 public String toString() {
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700332 InetAddress inetAddr = null;
333 try {
334 inetAddr = InetAddress.getByAddress(octets);
335 } catch (UnknownHostException e) {
336 // Should never happen
337 checkState(false, "Internal error: Ip6Address.toString()");
338 return "[Invalid IP Address]";
Jonathan Hartdec62d42014-09-22 15:59:04 -0700339 }
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700340 return InetAddresses.toAddrString(inetAddr);
341 }
342
343 /**
344 * Gets the IP address name for the IP address version.
345 *
346 * @param version the IP address version
347 * @return the IP address name for the IP address version
348 */
349 private static String addressName(Version version) {
350 switch (version) {
351 case INET:
352 return "IPv4";
353 case INET6:
354 return "IPv6";
355 default:
356 break;
357 }
358 return "UnknownIP(" + version + ")";
359 }
360
361 /**
362 * Checks whether the arguments are valid.
363 *
364 * @param version the IP address version
365 * @param value the IP address value stored in a byte array
366 * @param offset the offset in bytes from the beginning of the byte
367 * array with the address
368 * @throws IllegalArgumentException if any of the arguments is invalid
369 */
Pavlin Radoslavovf182f012014-11-04 15:03:18 -0800370 static void checkArguments(Version version, byte[] value, int offset) {
Pavlin Radoslavovd0e32d72014-10-31 18:11:43 -0700371 // Check the offset and byte array length
372 int addrByteLength = byteLength(version);
373 if ((offset < 0) || (offset + addrByteLength > value.length)) {
374 String msg;
375 if (value.length < addrByteLength) {
376 msg = "Invalid " + addressName(version) +
377 " address array: array length: " + value.length +
378 ". Must be at least " + addrByteLength;
379 } else {
380 msg = "Invalid " + addressName(version) +
381 " address array: array offset: " + offset +
382 ". Must be in the interval [0, " +
383 (value.length - addrByteLength) + "]";
384 }
385 throw new IllegalArgumentException(msg);
386 }
Jonathan Hartdec62d42014-09-22 15:59:04 -0700387 }
Pavlin Radoslavovf182f012014-11-04 15:03:18 -0800388
389 /**
390 * Creates a byte array for IP network mask prefix.
391 *
392 * @param version the IP address version
393 * @param prefixLength the length of the mask prefix. Must be in the
394 * interval [0, 32] for IPv4, or [0, 128] for IPv6
395 * @return a byte array that contains a mask prefix of the
396 * specified length
397 * @throws IllegalArgumentException if the arguments are invalid
398 */
399 static byte[] makeMaskPrefixArray(Version version, int prefixLength) {
400 int addrByteLength = byteLength(version);
401 int addrBitLength = addrByteLength * Byte.SIZE;
402
403 // Verify the prefix length
404 if ((prefixLength < 0) || (prefixLength > addrBitLength)) {
405 final String msg = "Invalid IP prefix length: " + prefixLength +
406 ". Must be in the interval [0, " + addrBitLength + "].";
407 throw new IllegalArgumentException(msg);
408 }
409
410 // Number of bytes and extra bits that should be all 1s
411 int maskBytes = prefixLength / Byte.SIZE;
412 int maskBits = prefixLength % Byte.SIZE;
413 byte[] mask = new byte[addrByteLength];
414
415 // Set the bytes and extra bits to 1s
416 for (int i = 0; i < maskBytes; i++) {
417 mask[i] = (byte) 0xff; // Set mask bytes to 1s
418 }
419 for (int i = maskBytes; i < addrByteLength; i++) {
420 mask[i] = 0; // Set remaining bytes to 0s
421 }
422 if (maskBits > 0) {
423 mask[maskBytes] = (byte) (0xff << (Byte.SIZE - maskBits));
424 }
425 return mask;
426 }
427
428 /**
429 * Creates a byte array that represents an IP address masked with
430 * a network mask of given mask length.
431 *
432 * @param addr the address to mask
433 * @param prefixLength the length of the mask prefix. Must be in the
434 * interval [0, 32] for IPv4, or [0, 128] for IPv6
435 * @return a byte array that represents the IP address masked with
436 * a mask prefix of the specified length
437 * @throws IllegalArgumentException if the prefix length is invalid
438 */
439 static byte[] makeMaskedAddressArray(final IpAddress addr,
440 int prefixLength) {
441 byte[] mask = IpAddress.makeMaskPrefixArray(addr.version(),
442 prefixLength);
443 byte[] net = new byte[mask.length];
444
445 // Mask each byte
446 for (int i = 0; i < net.length; i++) {
447 net[i] = (byte) (addr.octets[i] & mask[i]);
448 }
449 return net;
450 }
Jonathan Hartdec62d42014-09-22 15:59:04 -0700451}