blob: e970065e8f95544e4532c95dc8af965f96460ceb [file] [log] [blame]
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001/*
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
19import android.annotation.IntRange;
20import android.annotation.NonNull;
21import android.annotation.SystemApi;
22import android.os.Parcel;
23import android.os.Parcelable;
24import android.util.Pair;
25
Chiachang Wanga858d3b2021-02-03 18:40:42 +080026import com.android.net.module.util.NetUtils;
27
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090028import java.net.Inet4Address;
29import java.net.Inet6Address;
30import java.net.InetAddress;
31import java.net.UnknownHostException;
32import java.util.Arrays;
33import java.util.Comparator;
34
35/**
36 * This class represents an IP prefix, i.e., a contiguous block of IP addresses aligned on a
37 * power of two boundary (also known as an "IP subnet"). A prefix is specified by two pieces of
38 * information:
39 *
40 * <ul>
41 * <li>A starting IP address (IPv4 or IPv6). This is the first IP address of the prefix.
42 * <li>A prefix length. This specifies the length of the prefix by specifing the number of bits
43 * in the IP address, starting from the most significant bit in network byte order, that
44 * are constant for all addresses in the prefix.
45 * </ul>
46 *
47 * For example, the prefix <code>192.0.2.0/24</code> covers the 256 IPv4 addresses from
48 * <code>192.0.2.0</code> to <code>192.0.2.255</code>, inclusive, and the prefix
49 * <code>2001:db8:1:2</code> covers the 2^64 IPv6 addresses from <code>2001:db8:1:2::</code> to
50 * <code>2001:db8:1:2:ffff:ffff:ffff:ffff</code>, inclusive.
51 *
52 * Objects of this class are immutable.
53 */
54public final class IpPrefix implements Parcelable {
55 private final byte[] address; // network byte order
56 private final int prefixLength;
57
58 private void checkAndMaskAddressAndPrefixLength() {
59 if (address.length != 4 && address.length != 16) {
60 throw new IllegalArgumentException(
61 "IpPrefix has " + address.length + " bytes which is neither 4 nor 16");
62 }
Chiachang Wanga858d3b2021-02-03 18:40:42 +080063 NetUtils.maskRawAddress(address, prefixLength);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090064 }
65
66 /**
67 * Constructs a new {@code IpPrefix} from a byte array containing an IPv4 or IPv6 address in
68 * network byte order and a prefix length. Silently truncates the address to the prefix length,
69 * so for example {@code 192.0.2.1/24} is silently converted to {@code 192.0.2.0/24}.
70 *
71 * @param address the IP address. Must be non-null and exactly 4 or 16 bytes long.
72 * @param prefixLength the prefix length. Must be &gt;= 0 and &lt;= (32 or 128) (IPv4 or IPv6).
73 *
74 * @hide
75 */
76 public IpPrefix(@NonNull byte[] address, @IntRange(from = 0, to = 128) int prefixLength) {
77 this.address = address.clone();
78 this.prefixLength = prefixLength;
79 checkAndMaskAddressAndPrefixLength();
80 }
81
82 /**
83 * Constructs a new {@code IpPrefix} from an IPv4 or IPv6 address and a prefix length. Silently
84 * truncates the address to the prefix length, so for example {@code 192.0.2.1/24} is silently
85 * converted to {@code 192.0.2.0/24}.
86 *
87 * @param address the IP address. Must be non-null.
88 * @param prefixLength the prefix length. Must be &gt;= 0 and &lt;= (32 or 128) (IPv4 or IPv6).
89 * @hide
90 */
91 @SystemApi
92 public IpPrefix(@NonNull InetAddress address, @IntRange(from = 0, to = 128) int prefixLength) {
93 // We don't reuse the (byte[], int) constructor because it calls clone() on the byte array,
94 // which is unnecessary because getAddress() already returns a clone.
95 this.address = address.getAddress();
96 this.prefixLength = prefixLength;
97 checkAndMaskAddressAndPrefixLength();
98 }
99
100 /**
101 * Constructs a new IpPrefix from a string such as "192.0.2.1/24" or "2001:db8::1/64".
102 * Silently truncates the address to the prefix length, so for example {@code 192.0.2.1/24}
103 * is silently converted to {@code 192.0.2.0/24}.
104 *
105 * @param prefix the prefix to parse
106 *
107 * @hide
108 */
109 @SystemApi
110 public IpPrefix(@NonNull String prefix) {
111 // We don't reuse the (InetAddress, int) constructor because "error: call to this must be
112 // first statement in constructor". We could factor out setting the member variables to an
113 // init() method, but if we did, then we'd have to make the members non-final, or "error:
114 // cannot assign a value to final variable address". So we just duplicate the code here.
115 Pair<InetAddress, Integer> ipAndMask = NetworkUtils.parseIpAndMask(prefix);
116 this.address = ipAndMask.first.getAddress();
117 this.prefixLength = ipAndMask.second;
118 checkAndMaskAddressAndPrefixLength();
119 }
120
121 /**
122 * Compares this {@code IpPrefix} object against the specified object in {@code obj}. Two
123 * objects are equal if they have the same startAddress and prefixLength.
124 *
125 * @param obj the object to be tested for equality.
126 * @return {@code true} if both objects are equal, {@code false} otherwise.
127 */
128 @Override
129 public boolean equals(Object obj) {
130 if (!(obj instanceof IpPrefix)) {
131 return false;
132 }
133 IpPrefix that = (IpPrefix) obj;
134 return Arrays.equals(this.address, that.address) && this.prefixLength == that.prefixLength;
135 }
136
137 /**
138 * Gets the hashcode of the represented IP prefix.
139 *
140 * @return the appropriate hashcode value.
141 */
142 @Override
143 public int hashCode() {
144 return Arrays.hashCode(address) + 11 * prefixLength;
145 }
146
147 /**
148 * Returns a copy of the first IP address in the prefix. Modifying the returned object does not
149 * change this object's contents.
150 *
151 * @return the address in the form of a byte array.
152 */
153 public @NonNull InetAddress getAddress() {
154 try {
155 return InetAddress.getByAddress(address);
156 } catch (UnknownHostException e) {
157 // Cannot happen. InetAddress.getByAddress can only throw an exception if the byte
158 // array is the wrong length, but we check that in the constructor.
159 throw new IllegalArgumentException("Address is invalid");
160 }
161 }
162
163 /**
164 * Returns a copy of the IP address bytes in network order (the highest order byte is the zeroth
165 * element). Modifying the returned array does not change this object's contents.
166 *
167 * @return the address in the form of a byte array.
168 */
169 public @NonNull byte[] getRawAddress() {
170 return address.clone();
171 }
172
173 /**
174 * Returns the prefix length of this {@code IpPrefix}.
175 *
176 * @return the prefix length.
177 */
178 @IntRange(from = 0, to = 128)
179 public int getPrefixLength() {
180 return prefixLength;
181 }
182
183 /**
184 * Determines whether the prefix contains the specified address.
185 *
186 * @param address An {@link InetAddress} to test.
187 * @return {@code true} if the prefix covers the given address. {@code false} otherwise.
188 */
189 public boolean contains(@NonNull InetAddress address) {
190 byte[] addrBytes = address.getAddress();
191 if (addrBytes == null || addrBytes.length != this.address.length) {
192 return false;
193 }
Chiachang Wanga858d3b2021-02-03 18:40:42 +0800194 NetUtils.maskRawAddress(addrBytes, prefixLength);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900195 return Arrays.equals(this.address, addrBytes);
196 }
197
198 /**
199 * Returns whether the specified prefix is entirely contained in this prefix.
200 *
201 * Note this is mathematical inclusion, so a prefix is always contained within itself.
202 * @param otherPrefix the prefix to test
203 * @hide
204 */
205 public boolean containsPrefix(@NonNull IpPrefix otherPrefix) {
206 if (otherPrefix.getPrefixLength() < prefixLength) return false;
207 final byte[] otherAddress = otherPrefix.getRawAddress();
Chiachang Wanga858d3b2021-02-03 18:40:42 +0800208 NetUtils.maskRawAddress(otherAddress, prefixLength);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900209 return Arrays.equals(otherAddress, address);
210 }
211
212 /**
213 * @hide
214 */
215 public boolean isIPv6() {
216 return getAddress() instanceof Inet6Address;
217 }
218
219 /**
220 * @hide
221 */
222 public boolean isIPv4() {
223 return getAddress() instanceof Inet4Address;
224 }
225
226 /**
227 * Returns a string representation of this {@code IpPrefix}.
228 *
229 * @return a string such as {@code "192.0.2.0/24"} or {@code "2001:db8:1:2::/64"}.
230 */
231 public String toString() {
232 try {
233 return InetAddress.getByAddress(address).getHostAddress() + "/" + prefixLength;
234 } catch(UnknownHostException e) {
235 // Cosmic rays?
236 throw new IllegalStateException("IpPrefix with invalid address! Shouldn't happen.", e);
237 }
238 }
239
240 /**
241 * Implement the Parcelable interface.
242 */
243 public int describeContents() {
244 return 0;
245 }
246
247 /**
248 * Implement the Parcelable interface.
249 */
250 public void writeToParcel(Parcel dest, int flags) {
251 dest.writeByteArray(address);
252 dest.writeInt(prefixLength);
253 }
254
255 /**
256 * Returns a comparator ordering IpPrefixes by length, shorter to longer.
257 * Contents of the address will break ties.
258 * @hide
259 */
260 public static Comparator<IpPrefix> lengthComparator() {
261 return new Comparator<IpPrefix>() {
262 @Override
263 public int compare(IpPrefix prefix1, IpPrefix prefix2) {
264 if (prefix1.isIPv4()) {
265 if (prefix2.isIPv6()) return -1;
266 } else {
267 if (prefix2.isIPv4()) return 1;
268 }
269 final int p1len = prefix1.getPrefixLength();
270 final int p2len = prefix2.getPrefixLength();
271 if (p1len < p2len) return -1;
272 if (p2len < p1len) return 1;
273 final byte[] a1 = prefix1.address;
274 final byte[] a2 = prefix2.address;
275 final int len = a1.length < a2.length ? a1.length : a2.length;
276 for (int i = 0; i < len; ++i) {
277 if (a1[i] < a2[i]) return -1;
278 if (a1[i] > a2[i]) return 1;
279 }
280 if (a2.length < len) return 1;
281 if (a1.length < len) return -1;
282 return 0;
283 }
284 };
285 }
286
287 /**
288 * Implement the Parcelable interface.
289 */
290 public static final @android.annotation.NonNull Creator<IpPrefix> CREATOR =
291 new Creator<IpPrefix>() {
292 public IpPrefix createFromParcel(Parcel in) {
293 byte[] address = in.createByteArray();
294 int prefixLength = in.readInt();
295 return new IpPrefix(address, prefixLength);
296 }
297
298 public IpPrefix[] newArray(int size) {
299 return new IpPrefix[size];
300 }
301 };
302}