The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1 | /* |
| 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 | |
| 17 | package android.net; |
| 18 | |
Lorenzo Colitti | 0a82e80 | 2014-07-31 00:48:01 +0900 | [diff] [blame] | 19 | import android.os.Parcel; |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 20 | import android.util.Log; |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 21 | import android.util.Pair; |
| 22 | |
Chalard Jean | adbf1d0 | 2018-02-26 11:52:46 +0900 | [diff] [blame] | 23 | import java.io.FileDescriptor; |
| 24 | import java.math.BigInteger; |
| 25 | import java.net.Inet4Address; |
| 26 | import java.net.Inet6Address; |
| 27 | import java.net.InetAddress; |
| 28 | import java.net.SocketException; |
| 29 | import java.net.UnknownHostException; |
| 30 | import java.util.Collection; |
| 31 | import java.util.Locale; |
| 32 | import java.util.TreeSet; |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 33 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 34 | /** |
| 35 | * Native methods for managing network interfaces. |
| 36 | * |
| 37 | * {@hide} |
| 38 | */ |
| 39 | public class NetworkUtils { |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 40 | |
| 41 | private static final String TAG = "NetworkUtils"; |
| 42 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 43 | /** |
Lorenzo Colitti | 566e0cb | 2015-03-06 19:57:39 +0900 | [diff] [blame] | 44 | * Attaches a socket filter that accepts DHCP packets to the given socket. |
| 45 | */ |
| 46 | public native static void attachDhcpFilter(FileDescriptor fd) throws SocketException; |
| 47 | |
| 48 | /** |
Erik Kline | a3ca6bd | 2016-05-24 20:12:08 +0900 | [diff] [blame] | 49 | * Attaches a socket filter that accepts ICMPv6 router advertisements to the given socket. |
Paul Jensen | 578a76e | 2016-01-14 14:54:39 -0500 | [diff] [blame] | 50 | * @param fd the socket's {@link FileDescriptor}. |
| 51 | * @param packetType the hardware address type, one of ARPHRD_*. |
| 52 | */ |
| 53 | public native static void attachRaFilter(FileDescriptor fd, int packetType) throws SocketException; |
| 54 | |
| 55 | /** |
Erik Kline | 473355f | 2016-10-19 17:42:01 +0900 | [diff] [blame] | 56 | * Attaches a socket filter that accepts L2-L4 signaling traffic required for IP connectivity. |
| 57 | * |
| 58 | * This includes: all ARP, ICMPv6 RS/RA/NS/NA messages, and DHCPv4 exchanges. |
| 59 | * |
| 60 | * @param fd the socket's {@link FileDescriptor}. |
| 61 | * @param packetType the hardware address type, one of ARPHRD_*. |
| 62 | */ |
| 63 | public native static void attachControlPacketFilter(FileDescriptor fd, int packetType) |
| 64 | throws SocketException; |
| 65 | |
| 66 | /** |
Erik Kline | a3ca6bd | 2016-05-24 20:12:08 +0900 | [diff] [blame] | 67 | * Configures a socket for receiving ICMPv6 router solicitations and sending advertisements. |
| 68 | * @param fd the socket's {@link FileDescriptor}. |
| 69 | * @param ifIndex the interface index. |
| 70 | */ |
| 71 | public native static void setupRaSocket(FileDescriptor fd, int ifIndex) throws SocketException; |
| 72 | |
| 73 | /** |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 74 | * Binds the current process to the network designated by {@code netId}. All sockets created |
| 75 | * in the future (and not explicitly bound via a bound {@link SocketFactory} (see |
Paul Jensen | 6d3ff9e | 2014-05-29 10:12:39 -0400 | [diff] [blame] | 76 | * {@link Network#getSocketFactory}) will be bound to this network. Note that if this |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 77 | * {@code Network} ever disconnects all sockets created in this way will cease to work. This |
| 78 | * is by design so an application doesn't accidentally use sockets it thinks are still bound to |
Paul Jensen | bcc76d3 | 2014-07-11 08:17:29 -0400 | [diff] [blame] | 79 | * a particular {@code Network}. Passing NETID_UNSET clears the binding. |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 80 | */ |
Paul Jensen | 32a58f0 | 2014-06-20 13:58:14 -0400 | [diff] [blame] | 81 | public native static boolean bindProcessToNetwork(int netId); |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 82 | |
| 83 | /** |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 84 | * Return the netId last passed to {@link #bindProcessToNetwork}, or NETID_UNSET if |
| 85 | * {@link #unbindProcessToNetwork} has been called since {@link #bindProcessToNetwork}. |
| 86 | */ |
Paul Jensen | 72db88e | 2015-03-10 10:54:12 -0400 | [diff] [blame] | 87 | public native static int getBoundNetworkForProcess(); |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 88 | |
| 89 | /** |
| 90 | * Binds host resolutions performed by this process to the network designated by {@code netId}. |
Paul Jensen | bcc76d3 | 2014-07-11 08:17:29 -0400 | [diff] [blame] | 91 | * {@link #bindProcessToNetwork} takes precedence over this setting. Passing NETID_UNSET clears |
| 92 | * the binding. |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 93 | * |
| 94 | * @deprecated This is strictly for legacy usage to support startUsingNetworkFeature(). |
| 95 | */ |
Aurimas Liutikas | 514c5ef | 2016-05-24 15:22:55 -0700 | [diff] [blame] | 96 | @Deprecated |
Paul Jensen | 32a58f0 | 2014-06-20 13:58:14 -0400 | [diff] [blame] | 97 | public native static boolean bindProcessToNetworkForHostResolution(int netId); |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 98 | |
| 99 | /** |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 100 | * Explicitly binds {@code socketfd} to the network designated by {@code netId}. This |
| 101 | * overrides any binding via {@link #bindProcessToNetwork}. |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 102 | * @return 0 on success or negative errno on failure. |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 103 | */ |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 104 | public native static int bindSocketToNetwork(int socketfd, int netId); |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 105 | |
| 106 | /** |
Lorenzo Colitti | 4ff9f0f | 2015-03-17 17:56:10 +0900 | [diff] [blame] | 107 | * Protect {@code fd} from VPN connections. After protecting, data sent through |
| 108 | * this socket will go directly to the underlying network, so its traffic will not be |
| 109 | * forwarded through the VPN. |
| 110 | */ |
| 111 | public static boolean protectFromVpn(FileDescriptor fd) { |
| 112 | return protectFromVpn(fd.getInt$()); |
| 113 | } |
| 114 | |
| 115 | /** |
Paul Jensen | 6bc2c2c | 2014-05-07 15:27:40 -0400 | [diff] [blame] | 116 | * Protect {@code socketfd} from VPN connections. After protecting, data sent through |
| 117 | * this socket will go directly to the underlying network, so its traffic will not be |
| 118 | * forwarded through the VPN. |
| 119 | */ |
| 120 | public native static boolean protectFromVpn(int socketfd); |
| 121 | |
| 122 | /** |
Paul Jensen | cee9b51 | 2015-05-06 07:32:40 -0400 | [diff] [blame] | 123 | * Determine if {@code uid} can access network designated by {@code netId}. |
| 124 | * @return {@code true} if {@code uid} can access network, {@code false} otherwise. |
| 125 | */ |
| 126 | public native static boolean queryUserAccess(int uid, int netId); |
| 127 | |
| 128 | /** |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame^] | 129 | * @see #intToInet4AddressHTL(int) |
| 130 | * @deprecated Use either {@link #intToInet4AddressHTH(int)} |
| 131 | * or {@link #intToInet4AddressHTL(int)} |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 132 | */ |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame^] | 133 | @Deprecated |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 134 | public static InetAddress intToInetAddress(int hostAddress) { |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame^] | 135 | return intToInet4AddressHTL(hostAddress); |
| 136 | } |
| 137 | |
| 138 | /** |
| 139 | * Convert a IPv4 address from an integer to an InetAddress (0x04030201 -> 1.2.3.4) |
| 140 | * |
| 141 | * <p>This method uses the higher-order int bytes as the lower-order IPv4 address bytes, |
| 142 | * which is an unusual convention. Consider {@link #intToInet4AddressHTH(int)} instead. |
| 143 | * @param hostAddress an int coding for an IPv4 address, where higher-order int byte is |
| 144 | * lower-order IPv4 address byte |
| 145 | */ |
| 146 | public static InetAddress intToInet4AddressHTL(int hostAddress) { |
| 147 | return intToInet4AddressHTH(Integer.reverseBytes(hostAddress)); |
| 148 | } |
| 149 | |
| 150 | /** |
| 151 | * Convert a IPv4 address from an integer to an InetAddress (0x01020304 -> 1.2.3.4) |
| 152 | * @param hostAddress an int coding for an IPv4 address |
| 153 | */ |
| 154 | public static InetAddress intToInet4AddressHTH(int hostAddress) { |
| 155 | byte[] addressBytes = { (byte) (0xff & (hostAddress >> 24)), |
| 156 | (byte) (0xff & (hostAddress >> 16)), |
| 157 | (byte) (0xff & (hostAddress >> 8)), |
| 158 | (byte) (0xff & hostAddress) }; |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 159 | |
| 160 | try { |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame^] | 161 | return InetAddress.getByAddress(addressBytes); |
Jesse Wilson | 07481cc | 2011-01-06 17:18:23 -0800 | [diff] [blame] | 162 | } catch (UnknownHostException e) { |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame^] | 163 | throw new AssertionError(); |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 164 | } |
Robert Greenwalt | 47f69fe | 2010-06-15 15:43:39 -0700 | [diff] [blame] | 165 | } |
| 166 | |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 167 | /** |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame^] | 168 | * @see #inet4AddressToIntHTL(Inet4Address) |
| 169 | * @deprecated Use either {@link #inet4AddressToIntHTH(Inet4Address)} |
| 170 | * or {@link #inet4AddressToIntHTL(Inet4Address)} |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 171 | */ |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame^] | 172 | @Deprecated |
Robert Greenwalt | 4717c26 | 2012-10-31 14:32:53 -0700 | [diff] [blame] | 173 | public static int inetAddressToInt(Inet4Address inetAddr) |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 174 | throws IllegalArgumentException { |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame^] | 175 | return inet4AddressToIntHTL(inetAddr); |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 176 | } |
| 177 | |
| 178 | /** |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame^] | 179 | * Convert an IPv4 address from an InetAddress to an integer (1.2.3.4 -> 0x01020304) |
| 180 | * |
| 181 | * <p>This conversion can help order IP addresses: considering the ordering |
| 182 | * 192.0.2.1 < 192.0.2.2 < ..., resulting ints will follow that ordering if read as unsigned |
| 183 | * integers with {@link Integer#toUnsignedLong}. |
| 184 | * @param inetAddr is an InetAddress corresponding to the IPv4 address |
| 185 | * @return the IP address as integer |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 186 | */ |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame^] | 187 | public static int inet4AddressToIntHTH(Inet4Address inetAddr) |
| 188 | throws IllegalArgumentException { |
| 189 | byte [] addr = inetAddr.getAddress(); |
| 190 | return ((addr[0] & 0xff) << 24) | ((addr[1] & 0xff) << 16) |
| 191 | | ((addr[2] & 0xff) << 8) | (addr[3] & 0xff); |
| 192 | } |
| 193 | |
| 194 | /** |
| 195 | * Convert a IPv4 address from an InetAddress to an integer (1.2.3.4 -> 0x04030201) |
| 196 | * |
| 197 | * <p>This method stores the higher-order IPv4 address bytes in the lower-order int bytes, |
| 198 | * which is an unusual convention. Consider {@link #inet4AddressToIntHTH(Inet4Address)} instead. |
| 199 | * @param inetAddr is an InetAddress corresponding to the IPv4 address |
| 200 | * @return the IP address as integer |
| 201 | */ |
| 202 | public static int inet4AddressToIntHTL(Inet4Address inetAddr) { |
| 203 | return Integer.reverseBytes(inet4AddressToIntHTH(inetAddr)); |
| 204 | } |
| 205 | |
| 206 | /** |
| 207 | * @see #prefixLengthToV4NetmaskIntHTL(int) |
| 208 | * @deprecated Use either {@link #prefixLengthToV4NetmaskIntHTH(int)} |
| 209 | * or {@link #prefixLengthToV4NetmaskIntHTL(int)} |
| 210 | */ |
| 211 | @Deprecated |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 212 | public static int prefixLengthToNetmaskInt(int prefixLength) |
| 213 | throws IllegalArgumentException { |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame^] | 214 | return prefixLengthToV4NetmaskIntHTL(prefixLength); |
| 215 | } |
| 216 | |
| 217 | /** |
| 218 | * Convert a network prefix length to an IPv4 netmask integer (prefixLength 17 -> 0xffff8000) |
| 219 | * @return the IPv4 netmask as an integer |
| 220 | */ |
| 221 | public static int prefixLengthToV4NetmaskIntHTH(int prefixLength) |
| 222 | throws IllegalArgumentException { |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 223 | if (prefixLength < 0 || prefixLength > 32) { |
| 224 | throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)"); |
| 225 | } |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame^] | 226 | // (int)a << b is equivalent to a << (b & 0x1f): can't shift by 32 (-1 << 32 == -1) |
| 227 | return prefixLength == 0 ? 0 : 0xffffffff << (32 - prefixLength); |
| 228 | } |
| 229 | |
| 230 | /** |
| 231 | * Convert a network prefix length to an IPv4 netmask integer (prefixLength 17 -> 0x0080ffff). |
| 232 | * |
| 233 | * <p>This method stores the higher-order IPv4 address bytes in the lower-order int bytes, |
| 234 | * which is an unusual convention. Consider {@link #prefixLengthToV4NetmaskIntHTH(int)} instead. |
| 235 | * @return the IPv4 netmask as an integer |
| 236 | */ |
| 237 | public static int prefixLengthToV4NetmaskIntHTL(int prefixLength) |
| 238 | throws IllegalArgumentException { |
| 239 | return Integer.reverseBytes(prefixLengthToV4NetmaskIntHTH(prefixLength)); |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 240 | } |
| 241 | |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 242 | /** |
Robert Greenwalt | 59b1a4e | 2011-05-10 15:05:02 -0700 | [diff] [blame] | 243 | * Convert a IPv4 netmask integer to a prefix length |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame^] | 244 | * @param netmask as an integer (0xff000000 for a /8 subnet) |
Robert Greenwalt | 59b1a4e | 2011-05-10 15:05:02 -0700 | [diff] [blame] | 245 | * @return the network prefix length |
| 246 | */ |
| 247 | public static int netmaskIntToPrefixLength(int netmask) { |
| 248 | return Integer.bitCount(netmask); |
| 249 | } |
| 250 | |
| 251 | /** |
Lorenzo Colitti | 475085b | 2015-03-10 01:32:40 +0900 | [diff] [blame] | 252 | * Convert an IPv4 netmask to a prefix length, checking that the netmask is contiguous. |
| 253 | * @param netmask as a {@code Inet4Address}. |
| 254 | * @return the network prefix length |
| 255 | * @throws IllegalArgumentException the specified netmask was not contiguous. |
| 256 | * @hide |
| 257 | */ |
| 258 | public static int netmaskToPrefixLength(Inet4Address netmask) { |
| 259 | // inetAddressToInt returns an int in *network* byte order. |
| 260 | int i = Integer.reverseBytes(inetAddressToInt(netmask)); |
| 261 | int prefixLength = Integer.bitCount(i); |
| 262 | int trailingZeros = Integer.numberOfTrailingZeros(i); |
| 263 | if (trailingZeros != 32 - prefixLength) { |
| 264 | throw new IllegalArgumentException("Non-contiguous netmask: " + Integer.toHexString(i)); |
| 265 | } |
| 266 | return prefixLength; |
| 267 | } |
| 268 | |
| 269 | |
| 270 | /** |
Robert Greenwalt | 0216e61 | 2011-01-14 16:29:58 -0800 | [diff] [blame] | 271 | * Create an InetAddress from a string where the string must be a standard |
| 272 | * representation of a V4 or V6 address. Avoids doing a DNS lookup on failure |
| 273 | * but it will throw an IllegalArgumentException in that case. |
| 274 | * @param addrString |
| 275 | * @return the InetAddress |
| 276 | * @hide |
| 277 | */ |
| 278 | public static InetAddress numericToInetAddress(String addrString) |
| 279 | throws IllegalArgumentException { |
Elliott Hughes | f5bbb57 | 2011-02-15 17:11:29 -0800 | [diff] [blame] | 280 | return InetAddress.parseNumericAddress(addrString); |
Robert Greenwalt | 0216e61 | 2011-01-14 16:29:58 -0800 | [diff] [blame] | 281 | } |
| 282 | |
| 283 | /** |
Lorenzo Colitti | 0a82e80 | 2014-07-31 00:48:01 +0900 | [diff] [blame] | 284 | * Writes an InetAddress to a parcel. The address may be null. This is likely faster than |
| 285 | * calling writeSerializable. |
| 286 | */ |
| 287 | protected static void parcelInetAddress(Parcel parcel, InetAddress address, int flags) { |
| 288 | byte[] addressArray = (address != null) ? address.getAddress() : null; |
| 289 | parcel.writeByteArray(addressArray); |
| 290 | } |
| 291 | |
| 292 | /** |
| 293 | * Reads an InetAddress from a parcel. Returns null if the address that was written was null |
| 294 | * or if the data is invalid. |
| 295 | */ |
| 296 | protected static InetAddress unparcelInetAddress(Parcel in) { |
| 297 | byte[] addressArray = in.createByteArray(); |
| 298 | if (addressArray == null) { |
| 299 | return null; |
| 300 | } |
| 301 | try { |
| 302 | return InetAddress.getByAddress(addressArray); |
| 303 | } catch (UnknownHostException e) { |
| 304 | return null; |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | |
| 309 | /** |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 310 | * Masks a raw IP address byte array with the specified prefix length. |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 311 | */ |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 312 | public static void maskRawAddress(byte[] array, int prefixLength) { |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 313 | if (prefixLength < 0 || prefixLength > array.length * 8) { |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 314 | throw new RuntimeException("IP address with " + array.length + |
| 315 | " bytes has invalid prefix length " + prefixLength); |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 316 | } |
| 317 | |
| 318 | int offset = prefixLength / 8; |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 319 | int remainder = prefixLength % 8; |
| 320 | byte mask = (byte)(0xFF << (8 - remainder)); |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 321 | |
| 322 | if (offset < array.length) array[offset] = (byte)(array[offset] & mask); |
| 323 | |
| 324 | offset++; |
| 325 | |
| 326 | for (; offset < array.length; offset++) { |
| 327 | array[offset] = 0; |
| 328 | } |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 329 | } |
| 330 | |
| 331 | /** |
| 332 | * Get InetAddress masked with prefixLength. Will never return null. |
| 333 | * @param address the IP address to mask with |
| 334 | * @param prefixLength the prefixLength used to mask the IP |
| 335 | */ |
| 336 | public static InetAddress getNetworkPart(InetAddress address, int prefixLength) { |
| 337 | byte[] array = address.getAddress(); |
| 338 | maskRawAddress(array, prefixLength); |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 339 | |
| 340 | InetAddress netPart = null; |
| 341 | try { |
| 342 | netPart = InetAddress.getByAddress(array); |
| 343 | } catch (UnknownHostException e) { |
| 344 | throw new RuntimeException("getNetworkPart error - " + e.toString()); |
| 345 | } |
| 346 | return netPart; |
| 347 | } |
| 348 | |
| 349 | /** |
Lorenzo Colitti | 475085b | 2015-03-10 01:32:40 +0900 | [diff] [blame] | 350 | * Returns the implicit netmask of an IPv4 address, as was the custom before 1993. |
| 351 | */ |
| 352 | public static int getImplicitNetmask(Inet4Address address) { |
| 353 | int firstByte = address.getAddress()[0] & 0xff; // Convert to an unsigned value. |
| 354 | if (firstByte < 128) { |
| 355 | return 8; |
| 356 | } else if (firstByte < 192) { |
| 357 | return 16; |
| 358 | } else if (firstByte < 224) { |
| 359 | return 24; |
| 360 | } else { |
| 361 | return 32; // Will likely not end well for other reasons. |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | /** |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 366 | * Utility method to parse strings such as "192.0.2.5/24" or "2001:db8::cafe:d00d/64". |
| 367 | * @hide |
| 368 | */ |
| 369 | public static Pair<InetAddress, Integer> parseIpAndMask(String ipAndMaskString) { |
| 370 | InetAddress address = null; |
| 371 | int prefixLength = -1; |
| 372 | try { |
| 373 | String[] pieces = ipAndMaskString.split("/", 2); |
| 374 | prefixLength = Integer.parseInt(pieces[1]); |
| 375 | address = InetAddress.parseNumericAddress(pieces[0]); |
| 376 | } catch (NullPointerException e) { // Null string. |
| 377 | } catch (ArrayIndexOutOfBoundsException e) { // No prefix length. |
| 378 | } catch (NumberFormatException e) { // Non-numeric prefix. |
| 379 | } catch (IllegalArgumentException e) { // Invalid IP address. |
| 380 | } |
| 381 | |
| 382 | if (address == null || prefixLength == -1) { |
| 383 | throw new IllegalArgumentException("Invalid IP address and mask " + ipAndMaskString); |
| 384 | } |
| 385 | |
| 386 | return new Pair<InetAddress, Integer>(address, prefixLength); |
| 387 | } |
| 388 | |
| 389 | /** |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 390 | * Check if IP address type is consistent between two InetAddress. |
| 391 | * @return true if both are the same type. False otherwise. |
| 392 | */ |
| 393 | public static boolean addressTypeMatches(InetAddress left, InetAddress right) { |
| 394 | return (((left instanceof Inet4Address) && (right instanceof Inet4Address)) || |
| 395 | ((left instanceof Inet6Address) && (right instanceof Inet6Address))); |
| 396 | } |
Robert Greenwalt | 59b1a4e | 2011-05-10 15:05:02 -0700 | [diff] [blame] | 397 | |
| 398 | /** |
| 399 | * Convert a 32 char hex string into a Inet6Address. |
| 400 | * throws a runtime exception if the string isn't 32 chars, isn't hex or can't be |
| 401 | * made into an Inet6Address |
| 402 | * @param addrHexString a 32 character hex string representing an IPv6 addr |
| 403 | * @return addr an InetAddress representation for the string |
| 404 | */ |
| 405 | public static InetAddress hexToInet6Address(String addrHexString) |
| 406 | throws IllegalArgumentException { |
| 407 | try { |
Jeff Sharkey | fea17de | 2013-06-11 14:13:09 -0700 | [diff] [blame] | 408 | return numericToInetAddress(String.format(Locale.US, "%s:%s:%s:%s:%s:%s:%s:%s", |
Robert Greenwalt | 59b1a4e | 2011-05-10 15:05:02 -0700 | [diff] [blame] | 409 | addrHexString.substring(0,4), addrHexString.substring(4,8), |
| 410 | addrHexString.substring(8,12), addrHexString.substring(12,16), |
| 411 | addrHexString.substring(16,20), addrHexString.substring(20,24), |
| 412 | addrHexString.substring(24,28), addrHexString.substring(28,32))); |
| 413 | } catch (Exception e) { |
| 414 | Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e); |
| 415 | throw new IllegalArgumentException(e); |
| 416 | } |
| 417 | } |
Robert Greenwalt | a10b7fd | 2011-07-25 16:06:25 -0700 | [diff] [blame] | 418 | |
| 419 | /** |
| 420 | * Create a string array of host addresses from a collection of InetAddresses |
| 421 | * @param addrs a Collection of InetAddresses |
| 422 | * @return an array of Strings containing their host addresses |
| 423 | */ |
| 424 | public static String[] makeStrings(Collection<InetAddress> addrs) { |
| 425 | String[] result = new String[addrs.size()]; |
| 426 | int i = 0; |
| 427 | for (InetAddress addr : addrs) { |
| 428 | result[i++] = addr.getHostAddress(); |
| 429 | } |
| 430 | return result; |
| 431 | } |
Robert Greenwalt | d4420ab | 2011-12-07 09:58:48 -0800 | [diff] [blame] | 432 | |
| 433 | /** |
| 434 | * Trim leading zeros from IPv4 address strings |
| 435 | * Our base libraries will interpret that as octel.. |
| 436 | * Must leave non v4 addresses and host names alone. |
| 437 | * For example, 192.168.000.010 -> 192.168.0.10 |
| 438 | * TODO - fix base libraries and remove this function |
| 439 | * @param addr a string representing an ip addr |
| 440 | * @return a string propertly trimmed |
| 441 | */ |
| 442 | public static String trimV4AddrZeros(String addr) { |
Robert Greenwalt | 0faacf0 | 2011-12-07 16:43:59 -0800 | [diff] [blame] | 443 | if (addr == null) return null; |
Robert Greenwalt | d4420ab | 2011-12-07 09:58:48 -0800 | [diff] [blame] | 444 | String[] octets = addr.split("\\."); |
| 445 | if (octets.length != 4) return addr; |
| 446 | StringBuilder builder = new StringBuilder(16); |
| 447 | String result = null; |
| 448 | for (int i = 0; i < 4; i++) { |
| 449 | try { |
Robert Greenwalt | 3957b5f | 2011-12-07 13:10:59 -0800 | [diff] [blame] | 450 | if (octets[i].length() > 3) return addr; |
Robert Greenwalt | d4420ab | 2011-12-07 09:58:48 -0800 | [diff] [blame] | 451 | builder.append(Integer.parseInt(octets[i])); |
| 452 | } catch (NumberFormatException e) { |
| 453 | return addr; |
| 454 | } |
| 455 | if (i < 3) builder.append('.'); |
| 456 | } |
| 457 | result = builder.toString(); |
| 458 | return result; |
| 459 | } |
Chalard Jean | adbf1d0 | 2018-02-26 11:52:46 +0900 | [diff] [blame] | 460 | |
| 461 | /** |
| 462 | * Returns a prefix set without overlaps. |
| 463 | * |
| 464 | * This expects the src set to be sorted from shorter to longer. Results are undefined |
| 465 | * failing this condition. The returned prefix set is sorted in the same order as the |
| 466 | * passed set, with the same comparator. |
| 467 | */ |
| 468 | private static TreeSet<IpPrefix> deduplicatePrefixSet(final TreeSet<IpPrefix> src) { |
| 469 | final TreeSet<IpPrefix> dst = new TreeSet<>(src.comparator()); |
| 470 | // Prefixes match addresses that share their upper part up to their length, therefore |
| 471 | // the only kind of possible overlap in two prefixes is strict inclusion of the longer |
| 472 | // (more restrictive) in the shorter (including equivalence if they have the same |
| 473 | // length). |
| 474 | // Because prefixes in the src set are sorted from shorter to longer, deduplicating |
| 475 | // is done by simply iterating in order, and not adding any longer prefix that is |
| 476 | // already covered by a shorter one. |
| 477 | newPrefixes: |
| 478 | for (IpPrefix newPrefix : src) { |
| 479 | for (IpPrefix existingPrefix : dst) { |
| 480 | if (existingPrefix.containsPrefix(newPrefix)) { |
| 481 | continue newPrefixes; |
| 482 | } |
| 483 | } |
| 484 | dst.add(newPrefix); |
| 485 | } |
| 486 | return dst; |
| 487 | } |
| 488 | |
| 489 | /** |
| 490 | * Returns how many IPv4 addresses match any of the prefixes in the passed ordered set. |
| 491 | * |
| 492 | * Obviously this returns an integral value between 0 and 2**32. |
| 493 | * The behavior is undefined if any of the prefixes is not an IPv4 prefix or if the |
| 494 | * set is not ordered smallest prefix to longer prefix. |
| 495 | * |
| 496 | * @param prefixes the set of prefixes, ordered by length |
| 497 | */ |
| 498 | public static long routedIPv4AddressCount(final TreeSet<IpPrefix> prefixes) { |
| 499 | long routedIPCount = 0; |
| 500 | for (final IpPrefix prefix : deduplicatePrefixSet(prefixes)) { |
| 501 | if (!prefix.isIPv4()) { |
| 502 | Log.wtf(TAG, "Non-IPv4 prefix in routedIPv4AddressCount"); |
| 503 | } |
| 504 | int rank = 32 - prefix.getPrefixLength(); |
| 505 | routedIPCount += 1L << rank; |
| 506 | } |
| 507 | return routedIPCount; |
| 508 | } |
| 509 | |
| 510 | /** |
| 511 | * Returns how many IPv6 addresses match any of the prefixes in the passed ordered set. |
| 512 | * |
| 513 | * This returns a BigInteger between 0 and 2**128. |
| 514 | * The behavior is undefined if any of the prefixes is not an IPv6 prefix or if the |
| 515 | * set is not ordered smallest prefix to longer prefix. |
| 516 | */ |
| 517 | public static BigInteger routedIPv6AddressCount(final TreeSet<IpPrefix> prefixes) { |
| 518 | BigInteger routedIPCount = BigInteger.ZERO; |
| 519 | for (final IpPrefix prefix : deduplicatePrefixSet(prefixes)) { |
| 520 | if (!prefix.isIPv6()) { |
| 521 | Log.wtf(TAG, "Non-IPv6 prefix in routedIPv6AddressCount"); |
| 522 | } |
| 523 | int rank = 128 - prefix.getPrefixLength(); |
| 524 | routedIPCount = routedIPCount.add(BigInteger.ONE.shiftLeft(rank)); |
| 525 | } |
| 526 | return routedIPCount; |
| 527 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 528 | } |