blob: e7c801475c4d720652ec518b3ba89d70b214a490 [file] [log] [blame]
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * 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
7 *
8 * 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.
15 */
16
17package android.net;
18
paulhu895a7412019-03-27 22:26:37 +080019import android.annotation.IntRange;
paulhucbbc3db2019-03-08 16:35:20 +080020import android.annotation.NonNull;
Remi NGUYEN VANd9f75862019-01-23 21:35:52 +090021import android.annotation.SystemApi;
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -070022import android.os.Parcel;
23import android.os.Parcelable;
Lorenzo Colitti174bab22014-06-12 13:41:17 +090024import android.util.Pair;
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -070025
Hugo Benichi8253be92017-08-08 13:06:04 +090026import java.net.Inet4Address;
27import java.net.Inet6Address;
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -070028import java.net.InetAddress;
29import java.net.UnknownHostException;
30import java.util.Arrays;
Chalard Jean9cbc8822018-02-26 11:52:46 +090031import java.util.Comparator;
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -070032
33/**
34 * This class represents an IP prefix, i.e., a contiguous block of IP addresses aligned on a
35 * power of two boundary (also known as an "IP subnet"). A prefix is specified by two pieces of
36 * information:
37 *
38 * <ul>
39 * <li>A starting IP address (IPv4 or IPv6). This is the first IP address of the prefix.
40 * <li>A prefix length. This specifies the length of the prefix by specifing the number of bits
41 * in the IP address, starting from the most significant bit in network byte order, that
42 * are constant for all addresses in the prefix.
43 * </ul>
44 *
45 * For example, the prefix <code>192.0.2.0/24</code> covers the 256 IPv4 addresses from
46 * <code>192.0.2.0</code> to <code>192.0.2.255</code>, inclusive, and the prefix
47 * <code>2001:db8:1:2</code> covers the 2^64 IPv6 addresses from <code>2001:db8:1:2::</code> to
48 * <code>2001:db8:1:2:ffff:ffff:ffff:ffff</code>, inclusive.
49 *
50 * Objects of this class are immutable.
51 */
Robert Greenwalt4998e952014-06-12 12:57:19 -070052public final class IpPrefix implements Parcelable {
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -070053 private final byte[] address; // network byte order
54 private final int prefixLength;
55
Lorenzo Colitti174bab22014-06-12 13:41:17 +090056 private void checkAndMaskAddressAndPrefixLength() {
57 if (address.length != 4 && address.length != 16) {
58 throw new IllegalArgumentException(
59 "IpPrefix has " + address.length + " bytes which is neither 4 nor 16");
60 }
61 NetworkUtils.maskRawAddress(address, prefixLength);
62 }
63
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -070064 /**
65 * Constructs a new {@code IpPrefix} from a byte array containing an IPv4 or IPv6 address in
Lorenzo Colitti174bab22014-06-12 13:41:17 +090066 * network byte order and a prefix length. Silently truncates the address to the prefix length,
67 * so for example {@code 192.0.2.1/24} is silently converted to {@code 192.0.2.0/24}.
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -070068 *
69 * @param address the IP address. Must be non-null and exactly 4 or 16 bytes long.
70 * @param prefixLength the prefix length. Must be &gt;= 0 and &lt;= (32 or 128) (IPv4 or IPv6).
71 *
72 * @hide
73 */
paulhu895a7412019-03-27 22:26:37 +080074 public IpPrefix(@NonNull byte[] address, @IntRange(from = 0, to = 128) int prefixLength) {
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -070075 this.address = address.clone();
76 this.prefixLength = prefixLength;
Lorenzo Colitti174bab22014-06-12 13:41:17 +090077 checkAndMaskAddressAndPrefixLength();
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -070078 }
79
80 /**
Lorenzo Colitti174bab22014-06-12 13:41:17 +090081 * Constructs a new {@code IpPrefix} from an IPv4 or IPv6 address and a prefix length. Silently
82 * truncates the address to the prefix length, so for example {@code 192.0.2.1/24} is silently
83 * converted to {@code 192.0.2.0/24}.
84 *
85 * @param address the IP address. Must be non-null.
86 * @param prefixLength the prefix length. Must be &gt;= 0 and &lt;= (32 or 128) (IPv4 or IPv6).
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -070087 * @hide
88 */
Remi NGUYEN VANd9f75862019-01-23 21:35:52 +090089 @SystemApi
paulhu895a7412019-03-27 22:26:37 +080090 public IpPrefix(@NonNull InetAddress address, @IntRange(from = 0, to = 128) int prefixLength) {
Lorenzo Colitti174bab22014-06-12 13:41:17 +090091 // We don't reuse the (byte[], int) constructor because it calls clone() on the byte array,
92 // which is unnecessary because getAddress() already returns a clone.
93 this.address = address.getAddress();
94 this.prefixLength = prefixLength;
95 checkAndMaskAddressAndPrefixLength();
96 }
97
98 /**
99 * Constructs a new IpPrefix from a string such as "192.0.2.1/24" or "2001:db8::1/64".
100 * Silently truncates the address to the prefix length, so for example {@code 192.0.2.1/24}
101 * is silently converted to {@code 192.0.2.0/24}.
102 *
103 * @param prefix the prefix to parse
104 *
105 * @hide
106 */
Remi NGUYEN VANc7fe99f2019-01-29 12:08:43 +0900107 @SystemApi
paulhucbbc3db2019-03-08 16:35:20 +0800108 public IpPrefix(@NonNull String prefix) {
Lorenzo Colitti174bab22014-06-12 13:41:17 +0900109 // We don't reuse the (InetAddress, int) constructor because "error: call to this must be
110 // first statement in constructor". We could factor out setting the member variables to an
111 // init() method, but if we did, then we'd have to make the members non-final, or "error:
112 // cannot assign a value to final variable address". So we just duplicate the code here.
113 Pair<InetAddress, Integer> ipAndMask = NetworkUtils.parseIpAndMask(prefix);
114 this.address = ipAndMask.first.getAddress();
115 this.prefixLength = ipAndMask.second;
116 checkAndMaskAddressAndPrefixLength();
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -0700117 }
118
119 /**
120 * Compares this {@code IpPrefix} object against the specified object in {@code obj}. Two
121 * objects are equal if they have the same startAddress and prefixLength.
122 *
123 * @param obj the object to be tested for equality.
124 * @return {@code true} if both objects are equal, {@code false} otherwise.
125 */
126 @Override
127 public boolean equals(Object obj) {
128 if (!(obj instanceof IpPrefix)) {
129 return false;
130 }
131 IpPrefix that = (IpPrefix) obj;
132 return Arrays.equals(this.address, that.address) && this.prefixLength == that.prefixLength;
133 }
134
135 /**
136 * Gets the hashcode of the represented IP prefix.
137 *
138 * @return the appropriate hashcode value.
139 */
140 @Override
141 public int hashCode() {
142 return Arrays.hashCode(address) + 11 * prefixLength;
143 }
144
145 /**
146 * Returns a copy of the first IP address in the prefix. Modifying the returned object does not
147 * change this object's contents.
148 *
149 * @return the address in the form of a byte array.
150 */
paulhu895a7412019-03-27 22:26:37 +0800151 public @NonNull InetAddress getAddress() {
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -0700152 try {
153 return InetAddress.getByAddress(address);
154 } catch (UnknownHostException e) {
155 // Cannot happen. InetAddress.getByAddress can only throw an exception if the byte
156 // array is the wrong length, but we check that in the constructor.
paulhu895a7412019-03-27 22:26:37 +0800157 throw new IllegalArgumentException("Address is invalid");
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -0700158 }
159 }
160
161 /**
162 * Returns a copy of the IP address bytes in network order (the highest order byte is the zeroth
163 * element). Modifying the returned array does not change this object's contents.
164 *
165 * @return the address in the form of a byte array.
166 */
paulhu895a7412019-03-27 22:26:37 +0800167 public @NonNull byte[] getRawAddress() {
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -0700168 return address.clone();
169 }
170
171 /**
Lorenzo Colitti174bab22014-06-12 13:41:17 +0900172 * Returns the prefix length of this {@code IpPrefix}.
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -0700173 *
174 * @return the prefix length.
175 */
paulhu895a7412019-03-27 22:26:37 +0800176 @IntRange(from = 0, to = 128)
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -0700177 public int getPrefixLength() {
178 return prefixLength;
179 }
180
181 /**
Erik Klineb98afb02015-04-13 15:33:34 +0900182 * Determines whether the prefix contains the specified address.
183 *
184 * @param address An {@link InetAddress} to test.
paulhu895a7412019-03-27 22:26:37 +0800185 * @return {@code true} if the prefix covers the given address. {@code false} otherwise.
Erik Klineb98afb02015-04-13 15:33:34 +0900186 */
paulhu895a7412019-03-27 22:26:37 +0800187 public boolean contains(@NonNull InetAddress address) {
188 byte[] addrBytes = address.getAddress();
Erik Klineb98afb02015-04-13 15:33:34 +0900189 if (addrBytes == null || addrBytes.length != this.address.length) {
190 return false;
191 }
192 NetworkUtils.maskRawAddress(addrBytes, prefixLength);
193 return Arrays.equals(this.address, addrBytes);
194 }
195
196 /**
Chalard Jean9cbc8822018-02-26 11:52:46 +0900197 * Returns whether the specified prefix is entirely contained in this prefix.
198 *
199 * Note this is mathematical inclusion, so a prefix is always contained within itself.
200 * @param otherPrefix the prefix to test
201 * @hide
202 */
paulhu895a7412019-03-27 22:26:37 +0800203 public boolean containsPrefix(@NonNull IpPrefix otherPrefix) {
Chalard Jean9cbc8822018-02-26 11:52:46 +0900204 if (otherPrefix.getPrefixLength() < prefixLength) return false;
205 final byte[] otherAddress = otherPrefix.getRawAddress();
206 NetworkUtils.maskRawAddress(otherAddress, prefixLength);
207 return Arrays.equals(otherAddress, address);
208 }
209
210 /**
Hugo Benichi8253be92017-08-08 13:06:04 +0900211 * @hide
212 */
213 public boolean isIPv6() {
214 return getAddress() instanceof Inet6Address;
215 }
216
217 /**
218 * @hide
219 */
220 public boolean isIPv4() {
221 return getAddress() instanceof Inet4Address;
222 }
223
224 /**
Lorenzo Colitti174bab22014-06-12 13:41:17 +0900225 * Returns a string representation of this {@code IpPrefix}.
226 *
Lorenzo Colitti21290342014-09-19 01:49:05 +0900227 * @return a string such as {@code "192.0.2.0/24"} or {@code "2001:db8:1:2::/64"}.
Lorenzo Colitti174bab22014-06-12 13:41:17 +0900228 */
229 public String toString() {
230 try {
231 return InetAddress.getByAddress(address).getHostAddress() + "/" + prefixLength;
232 } catch(UnknownHostException e) {
233 // Cosmic rays?
234 throw new IllegalStateException("IpPrefix with invalid address! Shouldn't happen.", e);
235 }
236 }
237
238 /**
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -0700239 * Implement the Parcelable interface.
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -0700240 */
241 public int describeContents() {
242 return 0;
243 }
244
245 /**
246 * Implement the Parcelable interface.
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -0700247 */
248 public void writeToParcel(Parcel dest, int flags) {
249 dest.writeByteArray(address);
250 dest.writeInt(prefixLength);
251 }
252
253 /**
Chalard Jean9cbc8822018-02-26 11:52:46 +0900254 * Returns a comparator ordering IpPrefixes by length, shorter to longer.
255 * Contents of the address will break ties.
256 * @hide
257 */
258 public static Comparator<IpPrefix> lengthComparator() {
259 return new Comparator<IpPrefix>() {
260 @Override
261 public int compare(IpPrefix prefix1, IpPrefix prefix2) {
262 if (prefix1.isIPv4()) {
263 if (prefix2.isIPv6()) return -1;
264 } else {
265 if (prefix2.isIPv4()) return 1;
266 }
267 final int p1len = prefix1.getPrefixLength();
268 final int p2len = prefix2.getPrefixLength();
269 if (p1len < p2len) return -1;
270 if (p2len < p1len) return 1;
271 final byte[] a1 = prefix1.address;
272 final byte[] a2 = prefix2.address;
273 final int len = a1.length < a2.length ? a1.length : a2.length;
274 for (int i = 0; i < len; ++i) {
275 if (a1[i] < a2[i]) return -1;
276 if (a1[i] > a2[i]) return 1;
277 }
278 if (a2.length < len) return 1;
279 if (a1.length < len) return -1;
280 return 0;
281 }
282 };
283 }
284
285 /**
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -0700286 * Implement the Parcelable interface.
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -0700287 */
Jeff Sharkeyf8525282019-02-28 12:06:45 -0700288 public static final @android.annotation.NonNull Creator<IpPrefix> CREATOR =
Sreeram Ramachandran887d7b12014-06-03 18:41:43 -0700289 new Creator<IpPrefix>() {
290 public IpPrefix createFromParcel(Parcel in) {
291 byte[] address = in.createByteArray();
292 int prefixLength = in.readInt();
293 return new IpPrefix(address, prefixLength);
294 }
295
296 public IpPrefix[] newArray(int size) {
297 return new IpPrefix[size];
298 }
299 };
300}