blob: 599ccb287a26723a5fe7dcb884dc781fbc759f60 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 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
Mathew Inwoodfa3a7462018-08-08 14:52:47 +010019import android.annotation.UnsupportedAppUsage;
Lorenzo Colitti0a82e802014-07-31 00:48:01 +090020import android.os.Parcel;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070021import android.util.Log;
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +090022import android.util.Pair;
23
Chalard Jeanadbf1d02018-02-26 11:52:46 +090024import java.io.FileDescriptor;
25import java.math.BigInteger;
26import java.net.Inet4Address;
27import java.net.Inet6Address;
28import java.net.InetAddress;
29import java.net.SocketException;
30import java.net.UnknownHostException;
31import java.util.Collection;
32import java.util.Locale;
33import java.util.TreeSet;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035/**
36 * Native methods for managing network interfaces.
37 *
38 * {@hide}
39 */
40public class NetworkUtils {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070041
42 private static final String TAG = "NetworkUtils";
43
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044 /**
Lorenzo Colitti566e0cb2015-03-06 19:57:39 +090045 * Attaches a socket filter that accepts DHCP packets to the given socket.
46 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +010047 @UnsupportedAppUsage
Lorenzo Colitti566e0cb2015-03-06 19:57:39 +090048 public native static void attachDhcpFilter(FileDescriptor fd) throws SocketException;
49
50 /**
Erik Klinea3ca6bd2016-05-24 20:12:08 +090051 * Attaches a socket filter that accepts ICMPv6 router advertisements to the given socket.
Paul Jensen578a76e2016-01-14 14:54:39 -050052 * @param fd the socket's {@link FileDescriptor}.
53 * @param packetType the hardware address type, one of ARPHRD_*.
54 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +010055 @UnsupportedAppUsage
Paul Jensen578a76e2016-01-14 14:54:39 -050056 public native static void attachRaFilter(FileDescriptor fd, int packetType) throws SocketException;
57
58 /**
Erik Kline473355f2016-10-19 17:42:01 +090059 * Attaches a socket filter that accepts L2-L4 signaling traffic required for IP connectivity.
60 *
61 * This includes: all ARP, ICMPv6 RS/RA/NS/NA messages, and DHCPv4 exchanges.
62 *
63 * @param fd the socket's {@link FileDescriptor}.
64 * @param packetType the hardware address type, one of ARPHRD_*.
65 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +010066 @UnsupportedAppUsage
Erik Kline473355f2016-10-19 17:42:01 +090067 public native static void attachControlPacketFilter(FileDescriptor fd, int packetType)
68 throws SocketException;
69
70 /**
Erik Klinea3ca6bd2016-05-24 20:12:08 +090071 * Configures a socket for receiving ICMPv6 router solicitations and sending advertisements.
72 * @param fd the socket's {@link FileDescriptor}.
73 * @param ifIndex the interface index.
74 */
75 public native static void setupRaSocket(FileDescriptor fd, int ifIndex) throws SocketException;
76
77 /**
Paul Jensen38764952014-05-20 11:25:35 -040078 * Binds the current process to the network designated by {@code netId}. All sockets created
79 * in the future (and not explicitly bound via a bound {@link SocketFactory} (see
Paul Jensen6d3ff9e2014-05-29 10:12:39 -040080 * {@link Network#getSocketFactory}) will be bound to this network. Note that if this
Paul Jensen38764952014-05-20 11:25:35 -040081 * {@code Network} ever disconnects all sockets created in this way will cease to work. This
82 * is by design so an application doesn't accidentally use sockets it thinks are still bound to
Paul Jensenbcc76d32014-07-11 08:17:29 -040083 * a particular {@code Network}. Passing NETID_UNSET clears the binding.
Paul Jensen38764952014-05-20 11:25:35 -040084 */
Paul Jensen32a58f02014-06-20 13:58:14 -040085 public native static boolean bindProcessToNetwork(int netId);
Paul Jensen38764952014-05-20 11:25:35 -040086
87 /**
Paul Jensen38764952014-05-20 11:25:35 -040088 * Return the netId last passed to {@link #bindProcessToNetwork}, or NETID_UNSET if
89 * {@link #unbindProcessToNetwork} has been called since {@link #bindProcessToNetwork}.
90 */
Paul Jensen72db88e2015-03-10 10:54:12 -040091 public native static int getBoundNetworkForProcess();
Paul Jensen38764952014-05-20 11:25:35 -040092
93 /**
94 * Binds host resolutions performed by this process to the network designated by {@code netId}.
Paul Jensenbcc76d32014-07-11 08:17:29 -040095 * {@link #bindProcessToNetwork} takes precedence over this setting. Passing NETID_UNSET clears
96 * the binding.
Paul Jensen38764952014-05-20 11:25:35 -040097 *
98 * @deprecated This is strictly for legacy usage to support startUsingNetworkFeature().
99 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700100 @Deprecated
Paul Jensen32a58f02014-06-20 13:58:14 -0400101 public native static boolean bindProcessToNetworkForHostResolution(int netId);
Paul Jensen38764952014-05-20 11:25:35 -0400102
103 /**
Paul Jensen38764952014-05-20 11:25:35 -0400104 * Explicitly binds {@code socketfd} to the network designated by {@code netId}. This
105 * overrides any binding via {@link #bindProcessToNetwork}.
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700106 * @return 0 on success or negative errno on failure.
Paul Jensen38764952014-05-20 11:25:35 -0400107 */
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700108 public native static int bindSocketToNetwork(int socketfd, int netId);
Paul Jensen38764952014-05-20 11:25:35 -0400109
110 /**
Lorenzo Colitti4ff9f0f2015-03-17 17:56:10 +0900111 * Protect {@code fd} from VPN connections. After protecting, data sent through
112 * this socket will go directly to the underlying network, so its traffic will not be
113 * forwarded through the VPN.
114 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100115 @UnsupportedAppUsage
Lorenzo Colitti4ff9f0f2015-03-17 17:56:10 +0900116 public static boolean protectFromVpn(FileDescriptor fd) {
117 return protectFromVpn(fd.getInt$());
118 }
119
120 /**
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400121 * Protect {@code socketfd} from VPN connections. After protecting, data sent through
122 * this socket will go directly to the underlying network, so its traffic will not be
123 * forwarded through the VPN.
124 */
125 public native static boolean protectFromVpn(int socketfd);
126
127 /**
Paul Jensencee9b512015-05-06 07:32:40 -0400128 * Determine if {@code uid} can access network designated by {@code netId}.
129 * @return {@code true} if {@code uid} can access network, {@code false} otherwise.
130 */
131 public native static boolean queryUserAccess(int uid, int netId);
132
133 /**
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900134 * @see #intToInet4AddressHTL(int)
135 * @deprecated Use either {@link #intToInet4AddressHTH(int)}
136 * or {@link #intToInet4AddressHTL(int)}
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700137 */
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900138 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100139 @UnsupportedAppUsage
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700140 public static InetAddress intToInetAddress(int hostAddress) {
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900141 return intToInet4AddressHTL(hostAddress);
142 }
143
144 /**
145 * Convert a IPv4 address from an integer to an InetAddress (0x04030201 -> 1.2.3.4)
146 *
147 * <p>This method uses the higher-order int bytes as the lower-order IPv4 address bytes,
148 * which is an unusual convention. Consider {@link #intToInet4AddressHTH(int)} instead.
149 * @param hostAddress an int coding for an IPv4 address, where higher-order int byte is
150 * lower-order IPv4 address byte
151 */
152 public static InetAddress intToInet4AddressHTL(int hostAddress) {
153 return intToInet4AddressHTH(Integer.reverseBytes(hostAddress));
154 }
155
156 /**
157 * Convert a IPv4 address from an integer to an InetAddress (0x01020304 -> 1.2.3.4)
158 * @param hostAddress an int coding for an IPv4 address
159 */
160 public static InetAddress intToInet4AddressHTH(int hostAddress) {
161 byte[] addressBytes = { (byte) (0xff & (hostAddress >> 24)),
162 (byte) (0xff & (hostAddress >> 16)),
163 (byte) (0xff & (hostAddress >> 8)),
164 (byte) (0xff & hostAddress) };
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700165
166 try {
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900167 return InetAddress.getByAddress(addressBytes);
Jesse Wilson07481cc2011-01-06 17:18:23 -0800168 } catch (UnknownHostException e) {
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900169 throw new AssertionError();
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700170 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700171 }
172
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700173 /**
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900174 * @see #inet4AddressToIntHTL(Inet4Address)
175 * @deprecated Use either {@link #inet4AddressToIntHTH(Inet4Address)}
176 * or {@link #inet4AddressToIntHTL(Inet4Address)}
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700177 */
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900178 @Deprecated
Robert Greenwalt4717c262012-10-31 14:32:53 -0700179 public static int inetAddressToInt(Inet4Address inetAddr)
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700180 throws IllegalArgumentException {
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900181 return inet4AddressToIntHTL(inetAddr);
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700182 }
183
184 /**
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900185 * Convert an IPv4 address from an InetAddress to an integer (1.2.3.4 -> 0x01020304)
186 *
187 * <p>This conversion can help order IP addresses: considering the ordering
188 * 192.0.2.1 < 192.0.2.2 < ..., resulting ints will follow that ordering if read as unsigned
189 * integers with {@link Integer#toUnsignedLong}.
190 * @param inetAddr is an InetAddress corresponding to the IPv4 address
191 * @return the IP address as integer
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700192 */
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900193 public static int inet4AddressToIntHTH(Inet4Address inetAddr)
194 throws IllegalArgumentException {
195 byte [] addr = inetAddr.getAddress();
196 return ((addr[0] & 0xff) << 24) | ((addr[1] & 0xff) << 16)
197 | ((addr[2] & 0xff) << 8) | (addr[3] & 0xff);
198 }
199
200 /**
201 * Convert a IPv4 address from an InetAddress to an integer (1.2.3.4 -> 0x04030201)
202 *
203 * <p>This method stores the higher-order IPv4 address bytes in the lower-order int bytes,
204 * which is an unusual convention. Consider {@link #inet4AddressToIntHTH(Inet4Address)} instead.
205 * @param inetAddr is an InetAddress corresponding to the IPv4 address
206 * @return the IP address as integer
207 */
208 public static int inet4AddressToIntHTL(Inet4Address inetAddr) {
209 return Integer.reverseBytes(inet4AddressToIntHTH(inetAddr));
210 }
211
212 /**
213 * @see #prefixLengthToV4NetmaskIntHTL(int)
214 * @deprecated Use either {@link #prefixLengthToV4NetmaskIntHTH(int)}
215 * or {@link #prefixLengthToV4NetmaskIntHTL(int)}
216 */
217 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100218 @UnsupportedAppUsage
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700219 public static int prefixLengthToNetmaskInt(int prefixLength)
220 throws IllegalArgumentException {
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900221 return prefixLengthToV4NetmaskIntHTL(prefixLength);
222 }
223
224 /**
225 * Convert a network prefix length to an IPv4 netmask integer (prefixLength 17 -> 0xffff8000)
226 * @return the IPv4 netmask as an integer
227 */
228 public static int prefixLengthToV4NetmaskIntHTH(int prefixLength)
229 throws IllegalArgumentException {
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700230 if (prefixLength < 0 || prefixLength > 32) {
231 throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)");
232 }
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900233 // (int)a << b is equivalent to a << (b & 0x1f): can't shift by 32 (-1 << 32 == -1)
234 return prefixLength == 0 ? 0 : 0xffffffff << (32 - prefixLength);
235 }
236
237 /**
238 * Convert a network prefix length to an IPv4 netmask integer (prefixLength 17 -> 0x0080ffff).
239 *
240 * <p>This method stores the higher-order IPv4 address bytes in the lower-order int bytes,
241 * which is an unusual convention. Consider {@link #prefixLengthToV4NetmaskIntHTH(int)} instead.
242 * @return the IPv4 netmask as an integer
243 */
244 public static int prefixLengthToV4NetmaskIntHTL(int prefixLength)
245 throws IllegalArgumentException {
246 return Integer.reverseBytes(prefixLengthToV4NetmaskIntHTH(prefixLength));
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700247 }
248
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700249 /**
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700250 * Convert a IPv4 netmask integer to a prefix length
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900251 * @param netmask as an integer (0xff000000 for a /8 subnet)
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700252 * @return the network prefix length
253 */
254 public static int netmaskIntToPrefixLength(int netmask) {
255 return Integer.bitCount(netmask);
256 }
257
258 /**
Lorenzo Colitti475085b2015-03-10 01:32:40 +0900259 * Convert an IPv4 netmask to a prefix length, checking that the netmask is contiguous.
260 * @param netmask as a {@code Inet4Address}.
261 * @return the network prefix length
262 * @throws IllegalArgumentException the specified netmask was not contiguous.
263 * @hide
264 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100265 @UnsupportedAppUsage
Lorenzo Colitti475085b2015-03-10 01:32:40 +0900266 public static int netmaskToPrefixLength(Inet4Address netmask) {
267 // inetAddressToInt returns an int in *network* byte order.
268 int i = Integer.reverseBytes(inetAddressToInt(netmask));
269 int prefixLength = Integer.bitCount(i);
270 int trailingZeros = Integer.numberOfTrailingZeros(i);
271 if (trailingZeros != 32 - prefixLength) {
272 throw new IllegalArgumentException("Non-contiguous netmask: " + Integer.toHexString(i));
273 }
274 return prefixLength;
275 }
276
277
278 /**
Robert Greenwalt0216e612011-01-14 16:29:58 -0800279 * Create an InetAddress from a string where the string must be a standard
280 * representation of a V4 or V6 address. Avoids doing a DNS lookup on failure
281 * but it will throw an IllegalArgumentException in that case.
282 * @param addrString
283 * @return the InetAddress
284 * @hide
285 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100286 @UnsupportedAppUsage
Robert Greenwalt0216e612011-01-14 16:29:58 -0800287 public static InetAddress numericToInetAddress(String addrString)
288 throws IllegalArgumentException {
Elliott Hughesf5bbb572011-02-15 17:11:29 -0800289 return InetAddress.parseNumericAddress(addrString);
Robert Greenwalt0216e612011-01-14 16:29:58 -0800290 }
291
292 /**
Lorenzo Colitti0a82e802014-07-31 00:48:01 +0900293 * Writes an InetAddress to a parcel. The address may be null. This is likely faster than
294 * calling writeSerializable.
295 */
296 protected static void parcelInetAddress(Parcel parcel, InetAddress address, int flags) {
297 byte[] addressArray = (address != null) ? address.getAddress() : null;
298 parcel.writeByteArray(addressArray);
299 }
300
301 /**
302 * Reads an InetAddress from a parcel. Returns null if the address that was written was null
303 * or if the data is invalid.
304 */
305 protected static InetAddress unparcelInetAddress(Parcel in) {
306 byte[] addressArray = in.createByteArray();
307 if (addressArray == null) {
308 return null;
309 }
310 try {
311 return InetAddress.getByAddress(addressArray);
312 } catch (UnknownHostException e) {
313 return null;
314 }
315 }
316
317
318 /**
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900319 * Masks a raw IP address byte array with the specified prefix length.
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700320 */
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900321 public static void maskRawAddress(byte[] array, int prefixLength) {
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700322 if (prefixLength < 0 || prefixLength > array.length * 8) {
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900323 throw new RuntimeException("IP address with " + array.length +
324 " bytes has invalid prefix length " + prefixLength);
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700325 }
326
327 int offset = prefixLength / 8;
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900328 int remainder = prefixLength % 8;
329 byte mask = (byte)(0xFF << (8 - remainder));
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700330
331 if (offset < array.length) array[offset] = (byte)(array[offset] & mask);
332
333 offset++;
334
335 for (; offset < array.length; offset++) {
336 array[offset] = 0;
337 }
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900338 }
339
340 /**
341 * Get InetAddress masked with prefixLength. Will never return null.
342 * @param address the IP address to mask with
343 * @param prefixLength the prefixLength used to mask the IP
344 */
345 public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
346 byte[] array = address.getAddress();
347 maskRawAddress(array, prefixLength);
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700348
349 InetAddress netPart = null;
350 try {
351 netPart = InetAddress.getByAddress(array);
352 } catch (UnknownHostException e) {
353 throw new RuntimeException("getNetworkPart error - " + e.toString());
354 }
355 return netPart;
356 }
357
358 /**
Lorenzo Colitti475085b2015-03-10 01:32:40 +0900359 * Returns the implicit netmask of an IPv4 address, as was the custom before 1993.
360 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100361 @UnsupportedAppUsage
Lorenzo Colitti475085b2015-03-10 01:32:40 +0900362 public static int getImplicitNetmask(Inet4Address address) {
363 int firstByte = address.getAddress()[0] & 0xff; // Convert to an unsigned value.
364 if (firstByte < 128) {
365 return 8;
366 } else if (firstByte < 192) {
367 return 16;
368 } else if (firstByte < 224) {
369 return 24;
370 } else {
371 return 32; // Will likely not end well for other reasons.
372 }
373 }
374
375 /**
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900376 * Utility method to parse strings such as "192.0.2.5/24" or "2001:db8::cafe:d00d/64".
377 * @hide
378 */
379 public static Pair<InetAddress, Integer> parseIpAndMask(String ipAndMaskString) {
380 InetAddress address = null;
381 int prefixLength = -1;
382 try {
383 String[] pieces = ipAndMaskString.split("/", 2);
384 prefixLength = Integer.parseInt(pieces[1]);
385 address = InetAddress.parseNumericAddress(pieces[0]);
386 } catch (NullPointerException e) { // Null string.
387 } catch (ArrayIndexOutOfBoundsException e) { // No prefix length.
388 } catch (NumberFormatException e) { // Non-numeric prefix.
389 } catch (IllegalArgumentException e) { // Invalid IP address.
390 }
391
392 if (address == null || prefixLength == -1) {
393 throw new IllegalArgumentException("Invalid IP address and mask " + ipAndMaskString);
394 }
395
396 return new Pair<InetAddress, Integer>(address, prefixLength);
397 }
398
399 /**
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700400 * Check if IP address type is consistent between two InetAddress.
401 * @return true if both are the same type. False otherwise.
402 */
403 public static boolean addressTypeMatches(InetAddress left, InetAddress right) {
404 return (((left instanceof Inet4Address) && (right instanceof Inet4Address)) ||
405 ((left instanceof Inet6Address) && (right instanceof Inet6Address)));
406 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700407
408 /**
409 * Convert a 32 char hex string into a Inet6Address.
410 * throws a runtime exception if the string isn't 32 chars, isn't hex or can't be
411 * made into an Inet6Address
412 * @param addrHexString a 32 character hex string representing an IPv6 addr
413 * @return addr an InetAddress representation for the string
414 */
415 public static InetAddress hexToInet6Address(String addrHexString)
416 throws IllegalArgumentException {
417 try {
Jeff Sharkeyfea17de2013-06-11 14:13:09 -0700418 return numericToInetAddress(String.format(Locale.US, "%s:%s:%s:%s:%s:%s:%s:%s",
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700419 addrHexString.substring(0,4), addrHexString.substring(4,8),
420 addrHexString.substring(8,12), addrHexString.substring(12,16),
421 addrHexString.substring(16,20), addrHexString.substring(20,24),
422 addrHexString.substring(24,28), addrHexString.substring(28,32)));
423 } catch (Exception e) {
424 Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e);
425 throw new IllegalArgumentException(e);
426 }
427 }
Robert Greenwalta10b7fd2011-07-25 16:06:25 -0700428
429 /**
430 * Create a string array of host addresses from a collection of InetAddresses
431 * @param addrs a Collection of InetAddresses
432 * @return an array of Strings containing their host addresses
433 */
434 public static String[] makeStrings(Collection<InetAddress> addrs) {
435 String[] result = new String[addrs.size()];
436 int i = 0;
437 for (InetAddress addr : addrs) {
438 result[i++] = addr.getHostAddress();
439 }
440 return result;
441 }
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800442
443 /**
444 * Trim leading zeros from IPv4 address strings
445 * Our base libraries will interpret that as octel..
446 * Must leave non v4 addresses and host names alone.
447 * For example, 192.168.000.010 -> 192.168.0.10
448 * TODO - fix base libraries and remove this function
449 * @param addr a string representing an ip addr
450 * @return a string propertly trimmed
451 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100452 @UnsupportedAppUsage
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800453 public static String trimV4AddrZeros(String addr) {
Robert Greenwalt0faacf02011-12-07 16:43:59 -0800454 if (addr == null) return null;
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800455 String[] octets = addr.split("\\.");
456 if (octets.length != 4) return addr;
457 StringBuilder builder = new StringBuilder(16);
458 String result = null;
459 for (int i = 0; i < 4; i++) {
460 try {
Robert Greenwalt3957b5f2011-12-07 13:10:59 -0800461 if (octets[i].length() > 3) return addr;
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800462 builder.append(Integer.parseInt(octets[i]));
463 } catch (NumberFormatException e) {
464 return addr;
465 }
466 if (i < 3) builder.append('.');
467 }
468 result = builder.toString();
469 return result;
470 }
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900471
472 /**
473 * Returns a prefix set without overlaps.
474 *
475 * This expects the src set to be sorted from shorter to longer. Results are undefined
476 * failing this condition. The returned prefix set is sorted in the same order as the
477 * passed set, with the same comparator.
478 */
479 private static TreeSet<IpPrefix> deduplicatePrefixSet(final TreeSet<IpPrefix> src) {
480 final TreeSet<IpPrefix> dst = new TreeSet<>(src.comparator());
481 // Prefixes match addresses that share their upper part up to their length, therefore
482 // the only kind of possible overlap in two prefixes is strict inclusion of the longer
483 // (more restrictive) in the shorter (including equivalence if they have the same
484 // length).
485 // Because prefixes in the src set are sorted from shorter to longer, deduplicating
486 // is done by simply iterating in order, and not adding any longer prefix that is
487 // already covered by a shorter one.
488 newPrefixes:
489 for (IpPrefix newPrefix : src) {
490 for (IpPrefix existingPrefix : dst) {
491 if (existingPrefix.containsPrefix(newPrefix)) {
492 continue newPrefixes;
493 }
494 }
495 dst.add(newPrefix);
496 }
497 return dst;
498 }
499
500 /**
501 * Returns how many IPv4 addresses match any of the prefixes in the passed ordered set.
502 *
503 * Obviously this returns an integral value between 0 and 2**32.
504 * The behavior is undefined if any of the prefixes is not an IPv4 prefix or if the
505 * set is not ordered smallest prefix to longer prefix.
506 *
507 * @param prefixes the set of prefixes, ordered by length
508 */
509 public static long routedIPv4AddressCount(final TreeSet<IpPrefix> prefixes) {
510 long routedIPCount = 0;
511 for (final IpPrefix prefix : deduplicatePrefixSet(prefixes)) {
512 if (!prefix.isIPv4()) {
513 Log.wtf(TAG, "Non-IPv4 prefix in routedIPv4AddressCount");
514 }
515 int rank = 32 - prefix.getPrefixLength();
516 routedIPCount += 1L << rank;
517 }
518 return routedIPCount;
519 }
520
521 /**
522 * Returns how many IPv6 addresses match any of the prefixes in the passed ordered set.
523 *
524 * This returns a BigInteger between 0 and 2**128.
525 * The behavior is undefined if any of the prefixes is not an IPv6 prefix or if the
526 * set is not ordered smallest prefix to longer prefix.
527 */
528 public static BigInteger routedIPv6AddressCount(final TreeSet<IpPrefix> prefixes) {
529 BigInteger routedIPCount = BigInteger.ZERO;
530 for (final IpPrefix prefix : deduplicatePrefixSet(prefixes)) {
531 if (!prefix.isIPv6()) {
532 Log.wtf(TAG, "Non-IPv6 prefix in routedIPv6AddressCount");
533 }
534 int rank = 128 - prefix.getPrefixLength();
535 routedIPCount = routedIPCount.add(BigInteger.ONE.shiftLeft(rank));
536 }
537 return routedIPCount;
538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539}