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 | |
| 19 | import java.net.InetAddress; |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 20 | import java.net.Inet4Address; |
| 21 | import java.net.Inet6Address; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 22 | import java.net.UnknownHostException; |
Robert Greenwalt | a10b7fd | 2011-07-25 16:06:25 -0700 | [diff] [blame] | 23 | import java.util.Collection; |
Jeff Sharkey | fea17de | 2013-06-11 14:13:09 -0700 | [diff] [blame] | 24 | import java.util.Locale; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 25 | |
Lorenzo Colitti | 0a82e80 | 2014-07-31 00:48:01 +0900 | [diff] [blame] | 26 | import android.os.Parcel; |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 27 | import android.util.Log; |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 28 | import android.util.Pair; |
| 29 | |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 30 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 31 | /** |
| 32 | * Native methods for managing network interfaces. |
| 33 | * |
| 34 | * {@hide} |
| 35 | */ |
| 36 | public class NetworkUtils { |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 37 | |
| 38 | private static final String TAG = "NetworkUtils"; |
| 39 | |
Wink Saville | 8171e6f | 2011-07-07 16:17:06 -0700 | [diff] [blame] | 40 | /** Setting bit 0 indicates reseting of IPv4 addresses required */ |
| 41 | public static final int RESET_IPV4_ADDRESSES = 0x01; |
| 42 | |
| 43 | /** Setting bit 1 indicates reseting of IPv4 addresses required */ |
| 44 | public static final int RESET_IPV6_ADDRESSES = 0x02; |
| 45 | |
| 46 | /** Reset all addresses */ |
| 47 | public static final int RESET_ALL_ADDRESSES = RESET_IPV4_ADDRESSES | RESET_IPV6_ADDRESSES; |
| 48 | |
| 49 | /** |
| 50 | * Reset IPv6 or IPv4 sockets that are connected via the named interface. |
| 51 | * |
| 52 | * @param interfaceName is the interface to reset |
| 53 | * @param mask {@see #RESET_IPV4_ADDRESSES} and {@see #RESET_IPV6_ADDRESSES} |
| 54 | */ |
| 55 | public native static int resetConnections(String interfaceName, int mask); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 56 | |
| 57 | /** |
| 58 | * Start the DHCP client daemon, in order to have it request addresses |
Erik Kline | 3c3ce17 | 2015-02-19 19:51:15 +0900 | [diff] [blame] | 59 | * for the named interface. This returns {@code true} if the DHCPv4 daemon |
| 60 | * starts, {@code false} otherwise. This call blocks until such time as a |
| 61 | * result is available or the default discovery timeout has been reached. |
| 62 | * Callers should check {@link #getDhcpResults} to determine whether DHCP |
| 63 | * succeeded or failed, and if it succeeded, to fetch the {@link DhcpResults}. |
| 64 | * @param interfaceName the name of the interface to configure |
| 65 | * @return {@code true} for success, {@code false} for failure |
| 66 | */ |
| 67 | public native static boolean startDhcp(String interfaceName); |
| 68 | |
| 69 | /** |
| 70 | * Initiate renewal on the DHCP client daemon for the named interface. This |
| 71 | * returns {@code true} if the DHCPv4 daemon has been notified, {@code false} |
| 72 | * otherwise. This call blocks until such time as a result is available or |
| 73 | * the default renew timeout has been reached. Callers should check |
| 74 | * {@link #getDhcpResults} to determine whether DHCP succeeded or failed, |
| 75 | * and if it succeeded, to fetch the {@link DhcpResults}. |
| 76 | * @param interfaceName the name of the interface to configure |
| 77 | * @return {@code true} for success, {@code false} for failure |
| 78 | */ |
| 79 | public native static boolean startDhcpRenew(String interfaceName); |
| 80 | |
| 81 | /** |
| 82 | * Start the DHCP client daemon, in order to have it request addresses |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 83 | * for the named interface, and then configure the interface with those |
| 84 | * addresses. This call blocks until it obtains a result (either success |
| 85 | * or failure) from the daemon. |
| 86 | * @param interfaceName the name of the interface to configure |
Robert Greenwalt | 4717c26 | 2012-10-31 14:32:53 -0700 | [diff] [blame] | 87 | * @param dhcpResults if the request succeeds, this object is filled in with |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 88 | * the IP address information. |
| 89 | * @return {@code true} for success, {@code false} for failure |
| 90 | */ |
Erik Kline | 3c3ce17 | 2015-02-19 19:51:15 +0900 | [diff] [blame] | 91 | public static boolean runDhcp(String interfaceName, DhcpResults dhcpResults) { |
| 92 | return startDhcp(interfaceName) && getDhcpResults(interfaceName, dhcpResults); |
| 93 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 94 | |
| 95 | /** |
Erik Kline | 3c3ce17 | 2015-02-19 19:51:15 +0900 | [diff] [blame] | 96 | * Initiate renewal on the DHCP client daemon. This call blocks until it obtains |
Irfan Sheriff | 914ed90 | 2011-06-21 14:26:37 -0700 | [diff] [blame] | 97 | * a result (either success or failure) from the daemon. |
| 98 | * @param interfaceName the name of the interface to configure |
Robert Greenwalt | 4717c26 | 2012-10-31 14:32:53 -0700 | [diff] [blame] | 99 | * @param dhcpResults if the request succeeds, this object is filled in with |
Irfan Sheriff | 914ed90 | 2011-06-21 14:26:37 -0700 | [diff] [blame] | 100 | * the IP address information. |
| 101 | * @return {@code true} for success, {@code false} for failure |
| 102 | */ |
Erik Kline | 3c3ce17 | 2015-02-19 19:51:15 +0900 | [diff] [blame] | 103 | public static boolean runDhcpRenew(String interfaceName, DhcpResults dhcpResults) { |
| 104 | return startDhcpRenew(interfaceName) && getDhcpResults(interfaceName, dhcpResults); |
| 105 | } |
| 106 | |
| 107 | /** |
| 108 | * Fetch results from the DHCP client daemon. This call returns {@code true} if |
| 109 | * if there are results available to be read, {@code false} otherwise. |
| 110 | * @param interfaceName the name of the interface to configure |
| 111 | * @param dhcpResults if the request succeeds, this object is filled in with |
| 112 | * the IP address information. |
| 113 | * @return {@code true} for success, {@code false} for failure |
| 114 | */ |
| 115 | public native static boolean getDhcpResults(String interfaceName, DhcpResults dhcpResults); |
Irfan Sheriff | 914ed90 | 2011-06-21 14:26:37 -0700 | [diff] [blame] | 116 | |
| 117 | /** |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 118 | * Shut down the DHCP client daemon. |
| 119 | * @param interfaceName the name of the interface for which the daemon |
| 120 | * should be stopped |
| 121 | * @return {@code true} for success, {@code false} for failure |
| 122 | */ |
| 123 | public native static boolean stopDhcp(String interfaceName); |
| 124 | |
| 125 | /** |
| 126 | * Release the current DHCP lease. |
| 127 | * @param interfaceName the name of the interface for which the lease should |
| 128 | * be released |
| 129 | * @return {@code true} for success, {@code false} for failure |
| 130 | */ |
| 131 | public native static boolean releaseDhcpLease(String interfaceName); |
| 132 | |
| 133 | /** |
| 134 | * Return the last DHCP-related error message that was recorded. |
| 135 | * <p/>NOTE: This string is not localized, but currently it is only |
| 136 | * used in logging. |
| 137 | * @return the most recent error message, if any |
| 138 | */ |
| 139 | public native static String getDhcpError(); |
| 140 | |
| 141 | /** |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 142 | * Binds the current process to the network designated by {@code netId}. All sockets created |
| 143 | * 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] | 144 | * {@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] | 145 | * {@code Network} ever disconnects all sockets created in this way will cease to work. This |
| 146 | * 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] | 147 | * a particular {@code Network}. Passing NETID_UNSET clears the binding. |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 148 | */ |
Paul Jensen | 32a58f0 | 2014-06-20 13:58:14 -0400 | [diff] [blame] | 149 | public native static boolean bindProcessToNetwork(int netId); |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 150 | |
| 151 | /** |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 152 | * Return the netId last passed to {@link #bindProcessToNetwork}, or NETID_UNSET if |
| 153 | * {@link #unbindProcessToNetwork} has been called since {@link #bindProcessToNetwork}. |
| 154 | */ |
| 155 | public native static int getNetworkBoundToProcess(); |
| 156 | |
| 157 | /** |
| 158 | * 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] | 159 | * {@link #bindProcessToNetwork} takes precedence over this setting. Passing NETID_UNSET clears |
| 160 | * the binding. |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 161 | * |
| 162 | * @deprecated This is strictly for legacy usage to support startUsingNetworkFeature(). |
| 163 | */ |
Paul Jensen | 32a58f0 | 2014-06-20 13:58:14 -0400 | [diff] [blame] | 164 | public native static boolean bindProcessToNetworkForHostResolution(int netId); |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 165 | |
| 166 | /** |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 167 | * Explicitly binds {@code socketfd} to the network designated by {@code netId}. This |
| 168 | * overrides any binding via {@link #bindProcessToNetwork}. |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 169 | * @return 0 on success or negative errno on failure. |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 170 | */ |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 171 | public native static int bindSocketToNetwork(int socketfd, int netId); |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 172 | |
| 173 | /** |
Paul Jensen | 6bc2c2c | 2014-05-07 15:27:40 -0400 | [diff] [blame] | 174 | * Protect {@code socketfd} from VPN connections. After protecting, data sent through |
| 175 | * this socket will go directly to the underlying network, so its traffic will not be |
| 176 | * forwarded through the VPN. |
| 177 | */ |
| 178 | public native static boolean protectFromVpn(int socketfd); |
| 179 | |
| 180 | /** |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 181 | * Convert a IPv4 address from an integer to an InetAddress. |
Jesse Wilson | 07481cc | 2011-01-06 17:18:23 -0800 | [diff] [blame] | 182 | * @param hostAddress an int corresponding to the IPv4 address in network byte order |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 183 | */ |
| 184 | public static InetAddress intToInetAddress(int hostAddress) { |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 185 | byte[] addressBytes = { (byte)(0xff & hostAddress), |
| 186 | (byte)(0xff & (hostAddress >> 8)), |
| 187 | (byte)(0xff & (hostAddress >> 16)), |
| 188 | (byte)(0xff & (hostAddress >> 24)) }; |
| 189 | |
| 190 | try { |
Jesse Wilson | 07481cc | 2011-01-06 17:18:23 -0800 | [diff] [blame] | 191 | return InetAddress.getByAddress(addressBytes); |
| 192 | } catch (UnknownHostException e) { |
| 193 | throw new AssertionError(); |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 194 | } |
Robert Greenwalt | 47f69fe | 2010-06-15 15:43:39 -0700 | [diff] [blame] | 195 | } |
| 196 | |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 197 | /** |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 198 | * Convert a IPv4 address from an InetAddress to an integer |
| 199 | * @param inetAddr is an InetAddress corresponding to the IPv4 address |
| 200 | * @return the IP address as an integer in network byte order |
| 201 | */ |
Robert Greenwalt | 4717c26 | 2012-10-31 14:32:53 -0700 | [diff] [blame] | 202 | public static int inetAddressToInt(Inet4Address inetAddr) |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 203 | throws IllegalArgumentException { |
| 204 | byte [] addr = inetAddr.getAddress(); |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 205 | return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) | |
| 206 | ((addr[1] & 0xff) << 8) | (addr[0] & 0xff); |
| 207 | } |
| 208 | |
| 209 | /** |
| 210 | * Convert a network prefix length to an IPv4 netmask integer |
| 211 | * @param prefixLength |
| 212 | * @return the IPv4 netmask as an integer in network byte order |
| 213 | */ |
| 214 | public static int prefixLengthToNetmaskInt(int prefixLength) |
| 215 | throws IllegalArgumentException { |
| 216 | if (prefixLength < 0 || prefixLength > 32) { |
| 217 | throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)"); |
| 218 | } |
| 219 | int value = 0xffffffff << (32 - prefixLength); |
| 220 | return Integer.reverseBytes(value); |
| 221 | } |
| 222 | |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 223 | /** |
Robert Greenwalt | 59b1a4e | 2011-05-10 15:05:02 -0700 | [diff] [blame] | 224 | * Convert a IPv4 netmask integer to a prefix length |
| 225 | * @param netmask as an integer in network byte order |
| 226 | * @return the network prefix length |
| 227 | */ |
| 228 | public static int netmaskIntToPrefixLength(int netmask) { |
| 229 | return Integer.bitCount(netmask); |
| 230 | } |
| 231 | |
| 232 | /** |
Lorenzo Colitti | 475085b | 2015-03-10 01:32:40 +0900 | [diff] [blame^] | 233 | * Convert an IPv4 netmask to a prefix length, checking that the netmask is contiguous. |
| 234 | * @param netmask as a {@code Inet4Address}. |
| 235 | * @return the network prefix length |
| 236 | * @throws IllegalArgumentException the specified netmask was not contiguous. |
| 237 | * @hide |
| 238 | */ |
| 239 | public static int netmaskToPrefixLength(Inet4Address netmask) { |
| 240 | // inetAddressToInt returns an int in *network* byte order. |
| 241 | int i = Integer.reverseBytes(inetAddressToInt(netmask)); |
| 242 | int prefixLength = Integer.bitCount(i); |
| 243 | int trailingZeros = Integer.numberOfTrailingZeros(i); |
| 244 | if (trailingZeros != 32 - prefixLength) { |
| 245 | throw new IllegalArgumentException("Non-contiguous netmask: " + Integer.toHexString(i)); |
| 246 | } |
| 247 | return prefixLength; |
| 248 | } |
| 249 | |
| 250 | |
| 251 | /** |
Robert Greenwalt | 0216e61 | 2011-01-14 16:29:58 -0800 | [diff] [blame] | 252 | * Create an InetAddress from a string where the string must be a standard |
| 253 | * representation of a V4 or V6 address. Avoids doing a DNS lookup on failure |
| 254 | * but it will throw an IllegalArgumentException in that case. |
| 255 | * @param addrString |
| 256 | * @return the InetAddress |
| 257 | * @hide |
| 258 | */ |
| 259 | public static InetAddress numericToInetAddress(String addrString) |
| 260 | throws IllegalArgumentException { |
Elliott Hughes | f5bbb57 | 2011-02-15 17:11:29 -0800 | [diff] [blame] | 261 | return InetAddress.parseNumericAddress(addrString); |
Robert Greenwalt | 0216e61 | 2011-01-14 16:29:58 -0800 | [diff] [blame] | 262 | } |
| 263 | |
| 264 | /** |
Lorenzo Colitti | 0a82e80 | 2014-07-31 00:48:01 +0900 | [diff] [blame] | 265 | * Writes an InetAddress to a parcel. The address may be null. This is likely faster than |
| 266 | * calling writeSerializable. |
| 267 | */ |
| 268 | protected static void parcelInetAddress(Parcel parcel, InetAddress address, int flags) { |
| 269 | byte[] addressArray = (address != null) ? address.getAddress() : null; |
| 270 | parcel.writeByteArray(addressArray); |
| 271 | } |
| 272 | |
| 273 | /** |
| 274 | * Reads an InetAddress from a parcel. Returns null if the address that was written was null |
| 275 | * or if the data is invalid. |
| 276 | */ |
| 277 | protected static InetAddress unparcelInetAddress(Parcel in) { |
| 278 | byte[] addressArray = in.createByteArray(); |
| 279 | if (addressArray == null) { |
| 280 | return null; |
| 281 | } |
| 282 | try { |
| 283 | return InetAddress.getByAddress(addressArray); |
| 284 | } catch (UnknownHostException e) { |
| 285 | return null; |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | |
| 290 | /** |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 291 | * Masks a raw IP address byte array with the specified prefix length. |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 292 | */ |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 293 | public static void maskRawAddress(byte[] array, int prefixLength) { |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 294 | if (prefixLength < 0 || prefixLength > array.length * 8) { |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 295 | throw new RuntimeException("IP address with " + array.length + |
| 296 | " bytes has invalid prefix length " + prefixLength); |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 297 | } |
| 298 | |
| 299 | int offset = prefixLength / 8; |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 300 | int remainder = prefixLength % 8; |
| 301 | byte mask = (byte)(0xFF << (8 - remainder)); |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 302 | |
| 303 | if (offset < array.length) array[offset] = (byte)(array[offset] & mask); |
| 304 | |
| 305 | offset++; |
| 306 | |
| 307 | for (; offset < array.length; offset++) { |
| 308 | array[offset] = 0; |
| 309 | } |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 310 | } |
| 311 | |
| 312 | /** |
| 313 | * Get InetAddress masked with prefixLength. Will never return null. |
| 314 | * @param address the IP address to mask with |
| 315 | * @param prefixLength the prefixLength used to mask the IP |
| 316 | */ |
| 317 | public static InetAddress getNetworkPart(InetAddress address, int prefixLength) { |
| 318 | byte[] array = address.getAddress(); |
| 319 | maskRawAddress(array, prefixLength); |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 320 | |
| 321 | InetAddress netPart = null; |
| 322 | try { |
| 323 | netPart = InetAddress.getByAddress(array); |
| 324 | } catch (UnknownHostException e) { |
| 325 | throw new RuntimeException("getNetworkPart error - " + e.toString()); |
| 326 | } |
| 327 | return netPart; |
| 328 | } |
| 329 | |
| 330 | /** |
Lorenzo Colitti | 475085b | 2015-03-10 01:32:40 +0900 | [diff] [blame^] | 331 | * Returns the implicit netmask of an IPv4 address, as was the custom before 1993. |
| 332 | */ |
| 333 | public static int getImplicitNetmask(Inet4Address address) { |
| 334 | int firstByte = address.getAddress()[0] & 0xff; // Convert to an unsigned value. |
| 335 | if (firstByte < 128) { |
| 336 | return 8; |
| 337 | } else if (firstByte < 192) { |
| 338 | return 16; |
| 339 | } else if (firstByte < 224) { |
| 340 | return 24; |
| 341 | } else { |
| 342 | return 32; // Will likely not end well for other reasons. |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | /** |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 347 | * Utility method to parse strings such as "192.0.2.5/24" or "2001:db8::cafe:d00d/64". |
| 348 | * @hide |
| 349 | */ |
| 350 | public static Pair<InetAddress, Integer> parseIpAndMask(String ipAndMaskString) { |
| 351 | InetAddress address = null; |
| 352 | int prefixLength = -1; |
| 353 | try { |
| 354 | String[] pieces = ipAndMaskString.split("/", 2); |
| 355 | prefixLength = Integer.parseInt(pieces[1]); |
| 356 | address = InetAddress.parseNumericAddress(pieces[0]); |
| 357 | } catch (NullPointerException e) { // Null string. |
| 358 | } catch (ArrayIndexOutOfBoundsException e) { // No prefix length. |
| 359 | } catch (NumberFormatException e) { // Non-numeric prefix. |
| 360 | } catch (IllegalArgumentException e) { // Invalid IP address. |
| 361 | } |
| 362 | |
| 363 | if (address == null || prefixLength == -1) { |
| 364 | throw new IllegalArgumentException("Invalid IP address and mask " + ipAndMaskString); |
| 365 | } |
| 366 | |
| 367 | return new Pair<InetAddress, Integer>(address, prefixLength); |
| 368 | } |
| 369 | |
| 370 | /** |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 371 | * Check if IP address type is consistent between two InetAddress. |
| 372 | * @return true if both are the same type. False otherwise. |
| 373 | */ |
| 374 | public static boolean addressTypeMatches(InetAddress left, InetAddress right) { |
| 375 | return (((left instanceof Inet4Address) && (right instanceof Inet4Address)) || |
| 376 | ((left instanceof Inet6Address) && (right instanceof Inet6Address))); |
| 377 | } |
Robert Greenwalt | 59b1a4e | 2011-05-10 15:05:02 -0700 | [diff] [blame] | 378 | |
| 379 | /** |
| 380 | * Convert a 32 char hex string into a Inet6Address. |
| 381 | * throws a runtime exception if the string isn't 32 chars, isn't hex or can't be |
| 382 | * made into an Inet6Address |
| 383 | * @param addrHexString a 32 character hex string representing an IPv6 addr |
| 384 | * @return addr an InetAddress representation for the string |
| 385 | */ |
| 386 | public static InetAddress hexToInet6Address(String addrHexString) |
| 387 | throws IllegalArgumentException { |
| 388 | try { |
Jeff Sharkey | fea17de | 2013-06-11 14:13:09 -0700 | [diff] [blame] | 389 | 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] | 390 | addrHexString.substring(0,4), addrHexString.substring(4,8), |
| 391 | addrHexString.substring(8,12), addrHexString.substring(12,16), |
| 392 | addrHexString.substring(16,20), addrHexString.substring(20,24), |
| 393 | addrHexString.substring(24,28), addrHexString.substring(28,32))); |
| 394 | } catch (Exception e) { |
| 395 | Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e); |
| 396 | throw new IllegalArgumentException(e); |
| 397 | } |
| 398 | } |
Robert Greenwalt | a10b7fd | 2011-07-25 16:06:25 -0700 | [diff] [blame] | 399 | |
| 400 | /** |
| 401 | * Create a string array of host addresses from a collection of InetAddresses |
| 402 | * @param addrs a Collection of InetAddresses |
| 403 | * @return an array of Strings containing their host addresses |
| 404 | */ |
| 405 | public static String[] makeStrings(Collection<InetAddress> addrs) { |
| 406 | String[] result = new String[addrs.size()]; |
| 407 | int i = 0; |
| 408 | for (InetAddress addr : addrs) { |
| 409 | result[i++] = addr.getHostAddress(); |
| 410 | } |
| 411 | return result; |
| 412 | } |
Robert Greenwalt | d4420ab | 2011-12-07 09:58:48 -0800 | [diff] [blame] | 413 | |
| 414 | /** |
| 415 | * Trim leading zeros from IPv4 address strings |
| 416 | * Our base libraries will interpret that as octel.. |
| 417 | * Must leave non v4 addresses and host names alone. |
| 418 | * For example, 192.168.000.010 -> 192.168.0.10 |
| 419 | * TODO - fix base libraries and remove this function |
| 420 | * @param addr a string representing an ip addr |
| 421 | * @return a string propertly trimmed |
| 422 | */ |
| 423 | public static String trimV4AddrZeros(String addr) { |
Robert Greenwalt | 0faacf0 | 2011-12-07 16:43:59 -0800 | [diff] [blame] | 424 | if (addr == null) return null; |
Robert Greenwalt | d4420ab | 2011-12-07 09:58:48 -0800 | [diff] [blame] | 425 | String[] octets = addr.split("\\."); |
| 426 | if (octets.length != 4) return addr; |
| 427 | StringBuilder builder = new StringBuilder(16); |
| 428 | String result = null; |
| 429 | for (int i = 0; i < 4; i++) { |
| 430 | try { |
Robert Greenwalt | 3957b5f | 2011-12-07 13:10:59 -0800 | [diff] [blame] | 431 | if (octets[i].length() > 3) return addr; |
Robert Greenwalt | d4420ab | 2011-12-07 09:58:48 -0800 | [diff] [blame] | 432 | builder.append(Integer.parseInt(octets[i])); |
| 433 | } catch (NumberFormatException e) { |
| 434 | return addr; |
| 435 | } |
| 436 | if (i < 3) builder.append('.'); |
| 437 | } |
| 438 | result = builder.toString(); |
| 439 | return result; |
| 440 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 441 | } |