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