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 | |
Mathew Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame^] | 19 | import android.annotation.UnsupportedAppUsage; |
Lorenzo Colitti | 0a82e80 | 2014-07-31 00:48:01 +0900 | [diff] [blame] | 20 | import android.os.Parcel; |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 21 | import android.util.Log; |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 22 | import android.util.Pair; |
| 23 | |
Chalard Jean | adbf1d0 | 2018-02-26 11:52:46 +0900 | [diff] [blame] | 24 | import java.io.FileDescriptor; |
| 25 | import java.math.BigInteger; |
| 26 | import java.net.Inet4Address; |
| 27 | import java.net.Inet6Address; |
| 28 | import java.net.InetAddress; |
| 29 | import java.net.SocketException; |
| 30 | import java.net.UnknownHostException; |
| 31 | import java.util.Collection; |
| 32 | import java.util.Locale; |
| 33 | import java.util.TreeSet; |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 34 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 35 | /** |
| 36 | * Native methods for managing network interfaces. |
| 37 | * |
| 38 | * {@hide} |
| 39 | */ |
| 40 | public class NetworkUtils { |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 41 | |
| 42 | private static final String TAG = "NetworkUtils"; |
| 43 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 44 | /** |
Lorenzo Colitti | 566e0cb | 2015-03-06 19:57:39 +0900 | [diff] [blame] | 45 | * Attaches a socket filter that accepts DHCP packets to the given socket. |
| 46 | */ |
Mathew Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame^] | 47 | @UnsupportedAppUsage |
Lorenzo Colitti | 566e0cb | 2015-03-06 19:57:39 +0900 | [diff] [blame] | 48 | public native static void attachDhcpFilter(FileDescriptor fd) throws SocketException; |
| 49 | |
| 50 | /** |
Erik Kline | a3ca6bd | 2016-05-24 20:12:08 +0900 | [diff] [blame] | 51 | * 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] | 52 | * @param fd the socket's {@link FileDescriptor}. |
| 53 | * @param packetType the hardware address type, one of ARPHRD_*. |
| 54 | */ |
Mathew Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame^] | 55 | @UnsupportedAppUsage |
Paul Jensen | 578a76e | 2016-01-14 14:54:39 -0500 | [diff] [blame] | 56 | public native static void attachRaFilter(FileDescriptor fd, int packetType) throws SocketException; |
| 57 | |
| 58 | /** |
Erik Kline | 473355f | 2016-10-19 17:42:01 +0900 | [diff] [blame] | 59 | * 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 Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame^] | 66 | @UnsupportedAppUsage |
Erik Kline | 473355f | 2016-10-19 17:42:01 +0900 | [diff] [blame] | 67 | public native static void attachControlPacketFilter(FileDescriptor fd, int packetType) |
| 68 | throws SocketException; |
| 69 | |
| 70 | /** |
Erik Kline | a3ca6bd | 2016-05-24 20:12:08 +0900 | [diff] [blame] | 71 | * 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 Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 78 | * 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 Jensen | 6d3ff9e | 2014-05-29 10:12:39 -0400 | [diff] [blame] | 80 | * {@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] | 81 | * {@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 Jensen | bcc76d3 | 2014-07-11 08:17:29 -0400 | [diff] [blame] | 83 | * a particular {@code Network}. Passing NETID_UNSET clears the binding. |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 84 | */ |
Paul Jensen | 32a58f0 | 2014-06-20 13:58:14 -0400 | [diff] [blame] | 85 | public native static boolean bindProcessToNetwork(int netId); |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 86 | |
| 87 | /** |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 88 | * Return the netId last passed to {@link #bindProcessToNetwork}, or NETID_UNSET if |
| 89 | * {@link #unbindProcessToNetwork} has been called since {@link #bindProcessToNetwork}. |
| 90 | */ |
Paul Jensen | 72db88e | 2015-03-10 10:54:12 -0400 | [diff] [blame] | 91 | public native static int getBoundNetworkForProcess(); |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 92 | |
| 93 | /** |
| 94 | * 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] | 95 | * {@link #bindProcessToNetwork} takes precedence over this setting. Passing NETID_UNSET clears |
| 96 | * the binding. |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 97 | * |
| 98 | * @deprecated This is strictly for legacy usage to support startUsingNetworkFeature(). |
| 99 | */ |
Aurimas Liutikas | 514c5ef | 2016-05-24 15:22:55 -0700 | [diff] [blame] | 100 | @Deprecated |
Paul Jensen | 32a58f0 | 2014-06-20 13:58:14 -0400 | [diff] [blame] | 101 | public native static boolean bindProcessToNetworkForHostResolution(int netId); |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 102 | |
| 103 | /** |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 104 | * Explicitly binds {@code socketfd} to the network designated by {@code netId}. This |
| 105 | * overrides any binding via {@link #bindProcessToNetwork}. |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 106 | * @return 0 on success or negative errno on failure. |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 107 | */ |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 108 | public native static int bindSocketToNetwork(int socketfd, int netId); |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 109 | |
| 110 | /** |
Lorenzo Colitti | 4ff9f0f | 2015-03-17 17:56:10 +0900 | [diff] [blame] | 111 | * 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 Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame^] | 115 | @UnsupportedAppUsage |
Lorenzo Colitti | 4ff9f0f | 2015-03-17 17:56:10 +0900 | [diff] [blame] | 116 | public static boolean protectFromVpn(FileDescriptor fd) { |
| 117 | return protectFromVpn(fd.getInt$()); |
| 118 | } |
| 119 | |
| 120 | /** |
Paul Jensen | 6bc2c2c | 2014-05-07 15:27:40 -0400 | [diff] [blame] | 121 | * 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 Jensen | cee9b51 | 2015-05-06 07:32:40 -0400 | [diff] [blame] | 128 | * 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 VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 134 | * @see #intToInet4AddressHTL(int) |
| 135 | * @deprecated Use either {@link #intToInet4AddressHTH(int)} |
| 136 | * or {@link #intToInet4AddressHTL(int)} |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 137 | */ |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 138 | @Deprecated |
Mathew Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame^] | 139 | @UnsupportedAppUsage |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 140 | public static InetAddress intToInetAddress(int hostAddress) { |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 141 | 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 Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 165 | |
| 166 | try { |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 167 | return InetAddress.getByAddress(addressBytes); |
Jesse Wilson | 07481cc | 2011-01-06 17:18:23 -0800 | [diff] [blame] | 168 | } catch (UnknownHostException e) { |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 169 | throw new AssertionError(); |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 170 | } |
Robert Greenwalt | 47f69fe | 2010-06-15 15:43:39 -0700 | [diff] [blame] | 171 | } |
| 172 | |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 173 | /** |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 174 | * @see #inet4AddressToIntHTL(Inet4Address) |
| 175 | * @deprecated Use either {@link #inet4AddressToIntHTH(Inet4Address)} |
| 176 | * or {@link #inet4AddressToIntHTL(Inet4Address)} |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 177 | */ |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 178 | @Deprecated |
Robert Greenwalt | 4717c26 | 2012-10-31 14:32:53 -0700 | [diff] [blame] | 179 | public static int inetAddressToInt(Inet4Address inetAddr) |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 180 | throws IllegalArgumentException { |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 181 | return inet4AddressToIntHTL(inetAddr); |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 182 | } |
| 183 | |
| 184 | /** |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 185 | * 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 Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 192 | */ |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 193 | 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 Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame^] | 218 | @UnsupportedAppUsage |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 219 | public static int prefixLengthToNetmaskInt(int prefixLength) |
| 220 | throws IllegalArgumentException { |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 221 | 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 Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 230 | if (prefixLength < 0 || prefixLength > 32) { |
| 231 | throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)"); |
| 232 | } |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 233 | // (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 Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 247 | } |
| 248 | |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 249 | /** |
Robert Greenwalt | 59b1a4e | 2011-05-10 15:05:02 -0700 | [diff] [blame] | 250 | * Convert a IPv4 netmask integer to a prefix length |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 251 | * @param netmask as an integer (0xff000000 for a /8 subnet) |
Robert Greenwalt | 59b1a4e | 2011-05-10 15:05:02 -0700 | [diff] [blame] | 252 | * @return the network prefix length |
| 253 | */ |
| 254 | public static int netmaskIntToPrefixLength(int netmask) { |
| 255 | return Integer.bitCount(netmask); |
| 256 | } |
| 257 | |
| 258 | /** |
Lorenzo Colitti | 475085b | 2015-03-10 01:32:40 +0900 | [diff] [blame] | 259 | * 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 Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame^] | 265 | @UnsupportedAppUsage |
Lorenzo Colitti | 475085b | 2015-03-10 01:32:40 +0900 | [diff] [blame] | 266 | 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 Greenwalt | 0216e61 | 2011-01-14 16:29:58 -0800 | [diff] [blame] | 279 | * 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 Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame^] | 286 | @UnsupportedAppUsage |
Robert Greenwalt | 0216e61 | 2011-01-14 16:29:58 -0800 | [diff] [blame] | 287 | public static InetAddress numericToInetAddress(String addrString) |
| 288 | throws IllegalArgumentException { |
Elliott Hughes | f5bbb57 | 2011-02-15 17:11:29 -0800 | [diff] [blame] | 289 | return InetAddress.parseNumericAddress(addrString); |
Robert Greenwalt | 0216e61 | 2011-01-14 16:29:58 -0800 | [diff] [blame] | 290 | } |
| 291 | |
| 292 | /** |
Lorenzo Colitti | 0a82e80 | 2014-07-31 00:48:01 +0900 | [diff] [blame] | 293 | * 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 Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 319 | * Masks a raw IP address byte array with the specified prefix length. |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 320 | */ |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 321 | public static void maskRawAddress(byte[] array, int prefixLength) { |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 322 | if (prefixLength < 0 || prefixLength > array.length * 8) { |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 323 | throw new RuntimeException("IP address with " + array.length + |
| 324 | " bytes has invalid prefix length " + prefixLength); |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 325 | } |
| 326 | |
| 327 | int offset = prefixLength / 8; |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 328 | int remainder = prefixLength % 8; |
| 329 | byte mask = (byte)(0xFF << (8 - remainder)); |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 330 | |
| 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 Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 338 | } |
| 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 Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 348 | |
| 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 Colitti | 475085b | 2015-03-10 01:32:40 +0900 | [diff] [blame] | 359 | * Returns the implicit netmask of an IPv4 address, as was the custom before 1993. |
| 360 | */ |
Mathew Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame^] | 361 | @UnsupportedAppUsage |
Lorenzo Colitti | 475085b | 2015-03-10 01:32:40 +0900 | [diff] [blame] | 362 | 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 Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 376 | * 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 Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 400 | * 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 Greenwalt | 59b1a4e | 2011-05-10 15:05:02 -0700 | [diff] [blame] | 407 | |
| 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 Sharkey | fea17de | 2013-06-11 14:13:09 -0700 | [diff] [blame] | 418 | 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] | 419 | 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 Greenwalt | a10b7fd | 2011-07-25 16:06:25 -0700 | [diff] [blame] | 428 | |
| 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 Greenwalt | d4420ab | 2011-12-07 09:58:48 -0800 | [diff] [blame] | 442 | |
| 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 Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame^] | 452 | @UnsupportedAppUsage |
Robert Greenwalt | d4420ab | 2011-12-07 09:58:48 -0800 | [diff] [blame] | 453 | public static String trimV4AddrZeros(String addr) { |
Robert Greenwalt | 0faacf0 | 2011-12-07 16:43:59 -0800 | [diff] [blame] | 454 | if (addr == null) return null; |
Robert Greenwalt | d4420ab | 2011-12-07 09:58:48 -0800 | [diff] [blame] | 455 | 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 Greenwalt | 3957b5f | 2011-12-07 13:10:59 -0800 | [diff] [blame] | 461 | if (octets[i].length() > 3) return addr; |
Robert Greenwalt | d4420ab | 2011-12-07 09:58:48 -0800 | [diff] [blame] | 462 | 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 Jean | adbf1d0 | 2018-02-26 11:52:46 +0900 | [diff] [blame] | 471 | |
| 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 Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 539 | } |