blob: c431e40ede2f17fc05624a00e470a6a4f30e238e [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.net;
18
Eran Messeria2e0ca72018-09-20 15:15:41 +010019import static android.system.OsConstants.AF_INET;
20import static android.system.OsConstants.AF_INET6;
21
22import android.annotation.NonNull;
Mathew Inwoodfa3a7462018-08-08 14:52:47 +010023import android.annotation.UnsupportedAppUsage;
Lorenzo Colitti0a82e802014-07-31 00:48:01 +090024import android.os.Parcel;
Eran Messeria2e0ca72018-09-20 15:15:41 +010025import android.system.Os;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070026import android.util.Log;
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +090027import android.util.Pair;
28
Chalard Jeanadbf1d02018-02-26 11:52:46 +090029import java.io.FileDescriptor;
Remi NGUYEN VAN12da4a52018-07-04 11:15:56 +090030import java.io.IOException;
Chalard Jeanadbf1d02018-02-26 11:52:46 +090031import java.math.BigInteger;
32import java.net.Inet4Address;
33import java.net.Inet6Address;
34import java.net.InetAddress;
35import java.net.SocketException;
36import java.net.UnknownHostException;
37import java.util.Collection;
38import java.util.Locale;
39import java.util.TreeSet;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041/**
42 * Native methods for managing network interfaces.
43 *
44 * {@hide}
45 */
46public class NetworkUtils {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070047
48 private static final String TAG = "NetworkUtils";
49
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050 /**
Lorenzo Colitti566e0cb2015-03-06 19:57:39 +090051 * Attaches a socket filter that accepts DHCP packets to the given socket.
52 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +010053 @UnsupportedAppUsage
Lorenzo Colitti566e0cb2015-03-06 19:57:39 +090054 public native static void attachDhcpFilter(FileDescriptor fd) throws SocketException;
55
56 /**
Erik Klinea3ca6bd2016-05-24 20:12:08 +090057 * Attaches a socket filter that accepts ICMPv6 router advertisements to the given socket.
Paul Jensen578a76e2016-01-14 14:54:39 -050058 * @param fd the socket's {@link FileDescriptor}.
59 * @param packetType the hardware address type, one of ARPHRD_*.
60 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +010061 @UnsupportedAppUsage
Paul Jensen578a76e2016-01-14 14:54:39 -050062 public native static void attachRaFilter(FileDescriptor fd, int packetType) throws SocketException;
63
64 /**
Erik Kline473355f2016-10-19 17:42:01 +090065 * Attaches a socket filter that accepts L2-L4 signaling traffic required for IP connectivity.
66 *
67 * This includes: all ARP, ICMPv6 RS/RA/NS/NA messages, and DHCPv4 exchanges.
68 *
69 * @param fd the socket's {@link FileDescriptor}.
70 * @param packetType the hardware address type, one of ARPHRD_*.
71 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +010072 @UnsupportedAppUsage
Erik Kline473355f2016-10-19 17:42:01 +090073 public native static void attachControlPacketFilter(FileDescriptor fd, int packetType)
74 throws SocketException;
75
76 /**
Erik Klinea3ca6bd2016-05-24 20:12:08 +090077 * Configures a socket for receiving ICMPv6 router solicitations and sending advertisements.
78 * @param fd the socket's {@link FileDescriptor}.
79 * @param ifIndex the interface index.
80 */
81 public native static void setupRaSocket(FileDescriptor fd, int ifIndex) throws SocketException;
82
83 /**
Paul Jensen38764952014-05-20 11:25:35 -040084 * Binds the current process to the network designated by {@code netId}. All sockets created
85 * in the future (and not explicitly bound via a bound {@link SocketFactory} (see
Paul Jensen6d3ff9e2014-05-29 10:12:39 -040086 * {@link Network#getSocketFactory}) will be bound to this network. Note that if this
Paul Jensen38764952014-05-20 11:25:35 -040087 * {@code Network} ever disconnects all sockets created in this way will cease to work. This
88 * is by design so an application doesn't accidentally use sockets it thinks are still bound to
Paul Jensenbcc76d32014-07-11 08:17:29 -040089 * a particular {@code Network}. Passing NETID_UNSET clears the binding.
Paul Jensen38764952014-05-20 11:25:35 -040090 */
Paul Jensen32a58f02014-06-20 13:58:14 -040091 public native static boolean bindProcessToNetwork(int netId);
Paul Jensen38764952014-05-20 11:25:35 -040092
93 /**
Paul Jensen38764952014-05-20 11:25:35 -040094 * Return the netId last passed to {@link #bindProcessToNetwork}, or NETID_UNSET if
95 * {@link #unbindProcessToNetwork} has been called since {@link #bindProcessToNetwork}.
96 */
Paul Jensen72db88e2015-03-10 10:54:12 -040097 public native static int getBoundNetworkForProcess();
Paul Jensen38764952014-05-20 11:25:35 -040098
99 /**
100 * Binds host resolutions performed by this process to the network designated by {@code netId}.
Paul Jensenbcc76d32014-07-11 08:17:29 -0400101 * {@link #bindProcessToNetwork} takes precedence over this setting. Passing NETID_UNSET clears
102 * the binding.
Paul Jensen38764952014-05-20 11:25:35 -0400103 *
104 * @deprecated This is strictly for legacy usage to support startUsingNetworkFeature().
105 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700106 @Deprecated
Paul Jensen32a58f02014-06-20 13:58:14 -0400107 public native static boolean bindProcessToNetworkForHostResolution(int netId);
Paul Jensen38764952014-05-20 11:25:35 -0400108
109 /**
Paul Jensen38764952014-05-20 11:25:35 -0400110 * Explicitly binds {@code socketfd} to the network designated by {@code netId}. This
111 * overrides any binding via {@link #bindProcessToNetwork}.
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700112 * @return 0 on success or negative errno on failure.
Paul Jensen38764952014-05-20 11:25:35 -0400113 */
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700114 public native static int bindSocketToNetwork(int socketfd, int netId);
Paul Jensen38764952014-05-20 11:25:35 -0400115
116 /**
Lorenzo Colitti4ff9f0f2015-03-17 17:56:10 +0900117 * Protect {@code fd} from VPN connections. After protecting, data sent through
118 * this socket will go directly to the underlying network, so its traffic will not be
119 * forwarded through the VPN.
120 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100121 @UnsupportedAppUsage
Lorenzo Colitti4ff9f0f2015-03-17 17:56:10 +0900122 public static boolean protectFromVpn(FileDescriptor fd) {
123 return protectFromVpn(fd.getInt$());
124 }
125
126 /**
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400127 * Protect {@code socketfd} from VPN connections. After protecting, data sent through
128 * this socket will go directly to the underlying network, so its traffic will not be
129 * forwarded through the VPN.
130 */
131 public native static boolean protectFromVpn(int socketfd);
132
133 /**
Paul Jensencee9b512015-05-06 07:32:40 -0400134 * Determine if {@code uid} can access network designated by {@code netId}.
135 * @return {@code true} if {@code uid} can access network, {@code false} otherwise.
136 */
137 public native static boolean queryUserAccess(int uid, int netId);
138
139 /**
Remi NGUYEN VAN12da4a52018-07-04 11:15:56 +0900140 * Add an entry into the ARP cache.
141 */
142 public static void addArpEntry(Inet4Address ipv4Addr, MacAddress ethAddr, String ifname,
143 FileDescriptor fd) throws IOException {
144 addArpEntry(ethAddr.toByteArray(), ipv4Addr.getAddress(), ifname, fd);
145 }
146
147 private static native void addArpEntry(byte[] ethAddr, byte[] netAddr, String ifname,
148 FileDescriptor fd) throws IOException;
149
150 /**
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900151 * @see #intToInet4AddressHTL(int)
152 * @deprecated Use either {@link #intToInet4AddressHTH(int)}
153 * or {@link #intToInet4AddressHTL(int)}
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700154 */
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900155 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100156 @UnsupportedAppUsage
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700157 public static InetAddress intToInetAddress(int hostAddress) {
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900158 return intToInet4AddressHTL(hostAddress);
159 }
160
161 /**
162 * Convert a IPv4 address from an integer to an InetAddress (0x04030201 -> 1.2.3.4)
163 *
164 * <p>This method uses the higher-order int bytes as the lower-order IPv4 address bytes,
165 * which is an unusual convention. Consider {@link #intToInet4AddressHTH(int)} instead.
166 * @param hostAddress an int coding for an IPv4 address, where higher-order int byte is
167 * lower-order IPv4 address byte
168 */
Remi NGUYEN VANa420b572018-07-04 15:09:42 +0900169 public static Inet4Address intToInet4AddressHTL(int hostAddress) {
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900170 return intToInet4AddressHTH(Integer.reverseBytes(hostAddress));
171 }
172
173 /**
174 * Convert a IPv4 address from an integer to an InetAddress (0x01020304 -> 1.2.3.4)
175 * @param hostAddress an int coding for an IPv4 address
176 */
Remi NGUYEN VANa420b572018-07-04 15:09:42 +0900177 public static Inet4Address intToInet4AddressHTH(int hostAddress) {
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900178 byte[] addressBytes = { (byte) (0xff & (hostAddress >> 24)),
179 (byte) (0xff & (hostAddress >> 16)),
180 (byte) (0xff & (hostAddress >> 8)),
181 (byte) (0xff & hostAddress) };
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700182
183 try {
Remi NGUYEN VANa420b572018-07-04 15:09:42 +0900184 return (Inet4Address) InetAddress.getByAddress(addressBytes);
Jesse Wilson07481cc2011-01-06 17:18:23 -0800185 } catch (UnknownHostException e) {
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900186 throw new AssertionError();
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700187 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700188 }
189
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700190 /**
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900191 * @see #inet4AddressToIntHTL(Inet4Address)
192 * @deprecated Use either {@link #inet4AddressToIntHTH(Inet4Address)}
193 * or {@link #inet4AddressToIntHTL(Inet4Address)}
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700194 */
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900195 @Deprecated
Robert Greenwalt4717c262012-10-31 14:32:53 -0700196 public static int inetAddressToInt(Inet4Address inetAddr)
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700197 throws IllegalArgumentException {
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900198 return inet4AddressToIntHTL(inetAddr);
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700199 }
200
201 /**
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900202 * Convert an IPv4 address from an InetAddress to an integer (1.2.3.4 -> 0x01020304)
203 *
204 * <p>This conversion can help order IP addresses: considering the ordering
205 * 192.0.2.1 < 192.0.2.2 < ..., resulting ints will follow that ordering if read as unsigned
206 * integers with {@link Integer#toUnsignedLong}.
207 * @param inetAddr is an InetAddress corresponding to the IPv4 address
208 * @return the IP address as integer
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700209 */
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900210 public static int inet4AddressToIntHTH(Inet4Address inetAddr)
211 throws IllegalArgumentException {
212 byte [] addr = inetAddr.getAddress();
213 return ((addr[0] & 0xff) << 24) | ((addr[1] & 0xff) << 16)
214 | ((addr[2] & 0xff) << 8) | (addr[3] & 0xff);
215 }
216
217 /**
218 * Convert a IPv4 address from an InetAddress to an integer (1.2.3.4 -> 0x04030201)
219 *
220 * <p>This method stores the higher-order IPv4 address bytes in the lower-order int bytes,
221 * which is an unusual convention. Consider {@link #inet4AddressToIntHTH(Inet4Address)} instead.
222 * @param inetAddr is an InetAddress corresponding to the IPv4 address
223 * @return the IP address as integer
224 */
225 public static int inet4AddressToIntHTL(Inet4Address inetAddr) {
226 return Integer.reverseBytes(inet4AddressToIntHTH(inetAddr));
227 }
228
229 /**
230 * @see #prefixLengthToV4NetmaskIntHTL(int)
231 * @deprecated Use either {@link #prefixLengthToV4NetmaskIntHTH(int)}
232 * or {@link #prefixLengthToV4NetmaskIntHTL(int)}
233 */
234 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100235 @UnsupportedAppUsage
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700236 public static int prefixLengthToNetmaskInt(int prefixLength)
237 throws IllegalArgumentException {
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900238 return prefixLengthToV4NetmaskIntHTL(prefixLength);
239 }
240
241 /**
242 * Convert a network prefix length to an IPv4 netmask integer (prefixLength 17 -> 0xffff8000)
243 * @return the IPv4 netmask as an integer
244 */
245 public static int prefixLengthToV4NetmaskIntHTH(int prefixLength)
246 throws IllegalArgumentException {
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700247 if (prefixLength < 0 || prefixLength > 32) {
248 throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)");
249 }
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900250 // (int)a << b is equivalent to a << (b & 0x1f): can't shift by 32 (-1 << 32 == -1)
251 return prefixLength == 0 ? 0 : 0xffffffff << (32 - prefixLength);
252 }
253
254 /**
255 * Convert a network prefix length to an IPv4 netmask integer (prefixLength 17 -> 0x0080ffff).
256 *
257 * <p>This method stores the higher-order IPv4 address bytes in the lower-order int bytes,
258 * which is an unusual convention. Consider {@link #prefixLengthToV4NetmaskIntHTH(int)} instead.
259 * @return the IPv4 netmask as an integer
260 */
261 public static int prefixLengthToV4NetmaskIntHTL(int prefixLength)
262 throws IllegalArgumentException {
263 return Integer.reverseBytes(prefixLengthToV4NetmaskIntHTH(prefixLength));
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700264 }
265
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700266 /**
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700267 * Convert a IPv4 netmask integer to a prefix length
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900268 * @param netmask as an integer (0xff000000 for a /8 subnet)
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700269 * @return the network prefix length
270 */
271 public static int netmaskIntToPrefixLength(int netmask) {
272 return Integer.bitCount(netmask);
273 }
274
275 /**
Lorenzo Colitti475085b2015-03-10 01:32:40 +0900276 * Convert an IPv4 netmask to a prefix length, checking that the netmask is contiguous.
277 * @param netmask as a {@code Inet4Address}.
278 * @return the network prefix length
279 * @throws IllegalArgumentException the specified netmask was not contiguous.
280 * @hide
281 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100282 @UnsupportedAppUsage
Lorenzo Colitti475085b2015-03-10 01:32:40 +0900283 public static int netmaskToPrefixLength(Inet4Address netmask) {
284 // inetAddressToInt returns an int in *network* byte order.
285 int i = Integer.reverseBytes(inetAddressToInt(netmask));
286 int prefixLength = Integer.bitCount(i);
287 int trailingZeros = Integer.numberOfTrailingZeros(i);
288 if (trailingZeros != 32 - prefixLength) {
289 throw new IllegalArgumentException("Non-contiguous netmask: " + Integer.toHexString(i));
290 }
291 return prefixLength;
292 }
293
294
295 /**
Robert Greenwalt0216e612011-01-14 16:29:58 -0800296 * Create an InetAddress from a string where the string must be a standard
297 * representation of a V4 or V6 address. Avoids doing a DNS lookup on failure
298 * but it will throw an IllegalArgumentException in that case.
299 * @param addrString
300 * @return the InetAddress
301 * @hide
302 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100303 @UnsupportedAppUsage
Robert Greenwalt0216e612011-01-14 16:29:58 -0800304 public static InetAddress numericToInetAddress(String addrString)
305 throws IllegalArgumentException {
Elliott Hughesf5bbb572011-02-15 17:11:29 -0800306 return InetAddress.parseNumericAddress(addrString);
Robert Greenwalt0216e612011-01-14 16:29:58 -0800307 }
308
309 /**
Lorenzo Colitti0a82e802014-07-31 00:48:01 +0900310 * Writes an InetAddress to a parcel. The address may be null. This is likely faster than
311 * calling writeSerializable.
312 */
313 protected static void parcelInetAddress(Parcel parcel, InetAddress address, int flags) {
314 byte[] addressArray = (address != null) ? address.getAddress() : null;
315 parcel.writeByteArray(addressArray);
316 }
317
318 /**
319 * Reads an InetAddress from a parcel. Returns null if the address that was written was null
320 * or if the data is invalid.
321 */
322 protected static InetAddress unparcelInetAddress(Parcel in) {
323 byte[] addressArray = in.createByteArray();
324 if (addressArray == null) {
325 return null;
326 }
327 try {
328 return InetAddress.getByAddress(addressArray);
329 } catch (UnknownHostException e) {
330 return null;
331 }
332 }
333
334
335 /**
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900336 * Masks a raw IP address byte array with the specified prefix length.
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700337 */
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900338 public static void maskRawAddress(byte[] array, int prefixLength) {
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700339 if (prefixLength < 0 || prefixLength > array.length * 8) {
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900340 throw new RuntimeException("IP address with " + array.length +
341 " bytes has invalid prefix length " + prefixLength);
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700342 }
343
344 int offset = prefixLength / 8;
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900345 int remainder = prefixLength % 8;
346 byte mask = (byte)(0xFF << (8 - remainder));
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700347
348 if (offset < array.length) array[offset] = (byte)(array[offset] & mask);
349
350 offset++;
351
352 for (; offset < array.length; offset++) {
353 array[offset] = 0;
354 }
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900355 }
356
357 /**
358 * Get InetAddress masked with prefixLength. Will never return null.
359 * @param address the IP address to mask with
360 * @param prefixLength the prefixLength used to mask the IP
361 */
362 public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
363 byte[] array = address.getAddress();
364 maskRawAddress(array, prefixLength);
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700365
366 InetAddress netPart = null;
367 try {
368 netPart = InetAddress.getByAddress(array);
369 } catch (UnknownHostException e) {
370 throw new RuntimeException("getNetworkPart error - " + e.toString());
371 }
372 return netPart;
373 }
374
375 /**
Lorenzo Colitti475085b2015-03-10 01:32:40 +0900376 * Returns the implicit netmask of an IPv4 address, as was the custom before 1993.
377 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100378 @UnsupportedAppUsage
Lorenzo Colitti475085b2015-03-10 01:32:40 +0900379 public static int getImplicitNetmask(Inet4Address address) {
380 int firstByte = address.getAddress()[0] & 0xff; // Convert to an unsigned value.
381 if (firstByte < 128) {
382 return 8;
383 } else if (firstByte < 192) {
384 return 16;
385 } else if (firstByte < 224) {
386 return 24;
387 } else {
388 return 32; // Will likely not end well for other reasons.
389 }
390 }
391
392 /**
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900393 * Utility method to parse strings such as "192.0.2.5/24" or "2001:db8::cafe:d00d/64".
394 * @hide
395 */
396 public static Pair<InetAddress, Integer> parseIpAndMask(String ipAndMaskString) {
397 InetAddress address = null;
398 int prefixLength = -1;
399 try {
400 String[] pieces = ipAndMaskString.split("/", 2);
401 prefixLength = Integer.parseInt(pieces[1]);
402 address = InetAddress.parseNumericAddress(pieces[0]);
403 } catch (NullPointerException e) { // Null string.
404 } catch (ArrayIndexOutOfBoundsException e) { // No prefix length.
405 } catch (NumberFormatException e) { // Non-numeric prefix.
406 } catch (IllegalArgumentException e) { // Invalid IP address.
407 }
408
409 if (address == null || prefixLength == -1) {
410 throw new IllegalArgumentException("Invalid IP address and mask " + ipAndMaskString);
411 }
412
413 return new Pair<InetAddress, Integer>(address, prefixLength);
414 }
415
416 /**
Remi NGUYEN VANa420b572018-07-04 15:09:42 +0900417 * Get a prefix mask as Inet4Address for a given prefix length.
418 *
419 * <p>For example 20 -> 255.255.240.0
420 */
421 public static Inet4Address getPrefixMaskAsInet4Address(int prefixLength)
422 throws IllegalArgumentException {
423 return intToInet4AddressHTH(prefixLengthToV4NetmaskIntHTH(prefixLength));
424 }
425
426 /**
427 * Get the broadcast address for a given prefix.
428 *
429 * <p>For example 192.168.0.1/24 -> 192.168.0.255
430 */
431 public static Inet4Address getBroadcastAddress(Inet4Address addr, int prefixLength)
432 throws IllegalArgumentException {
433 final int intBroadcastAddr = inet4AddressToIntHTH(addr)
434 | ~prefixLengthToV4NetmaskIntHTH(prefixLength);
435 return intToInet4AddressHTH(intBroadcastAddr);
436 }
437
438 /**
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700439 * Check if IP address type is consistent between two InetAddress.
440 * @return true if both are the same type. False otherwise.
441 */
442 public static boolean addressTypeMatches(InetAddress left, InetAddress right) {
443 return (((left instanceof Inet4Address) && (right instanceof Inet4Address)) ||
444 ((left instanceof Inet6Address) && (right instanceof Inet6Address)));
445 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700446
447 /**
448 * Convert a 32 char hex string into a Inet6Address.
449 * throws a runtime exception if the string isn't 32 chars, isn't hex or can't be
450 * made into an Inet6Address
451 * @param addrHexString a 32 character hex string representing an IPv6 addr
452 * @return addr an InetAddress representation for the string
453 */
454 public static InetAddress hexToInet6Address(String addrHexString)
455 throws IllegalArgumentException {
456 try {
Jeff Sharkeyfea17de2013-06-11 14:13:09 -0700457 return numericToInetAddress(String.format(Locale.US, "%s:%s:%s:%s:%s:%s:%s:%s",
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700458 addrHexString.substring(0,4), addrHexString.substring(4,8),
459 addrHexString.substring(8,12), addrHexString.substring(12,16),
460 addrHexString.substring(16,20), addrHexString.substring(20,24),
461 addrHexString.substring(24,28), addrHexString.substring(28,32)));
462 } catch (Exception e) {
463 Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e);
464 throw new IllegalArgumentException(e);
465 }
466 }
Robert Greenwalta10b7fd2011-07-25 16:06:25 -0700467
468 /**
469 * Create a string array of host addresses from a collection of InetAddresses
470 * @param addrs a Collection of InetAddresses
471 * @return an array of Strings containing their host addresses
472 */
473 public static String[] makeStrings(Collection<InetAddress> addrs) {
474 String[] result = new String[addrs.size()];
475 int i = 0;
476 for (InetAddress addr : addrs) {
477 result[i++] = addr.getHostAddress();
478 }
479 return result;
480 }
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800481
482 /**
483 * Trim leading zeros from IPv4 address strings
484 * Our base libraries will interpret that as octel..
485 * Must leave non v4 addresses and host names alone.
486 * For example, 192.168.000.010 -> 192.168.0.10
487 * TODO - fix base libraries and remove this function
488 * @param addr a string representing an ip addr
489 * @return a string propertly trimmed
490 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100491 @UnsupportedAppUsage
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800492 public static String trimV4AddrZeros(String addr) {
Robert Greenwalt0faacf02011-12-07 16:43:59 -0800493 if (addr == null) return null;
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800494 String[] octets = addr.split("\\.");
495 if (octets.length != 4) return addr;
496 StringBuilder builder = new StringBuilder(16);
497 String result = null;
498 for (int i = 0; i < 4; i++) {
499 try {
Robert Greenwalt3957b5f2011-12-07 13:10:59 -0800500 if (octets[i].length() > 3) return addr;
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800501 builder.append(Integer.parseInt(octets[i]));
502 } catch (NumberFormatException e) {
503 return addr;
504 }
505 if (i < 3) builder.append('.');
506 }
507 result = builder.toString();
508 return result;
509 }
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900510
511 /**
512 * Returns a prefix set without overlaps.
513 *
514 * This expects the src set to be sorted from shorter to longer. Results are undefined
515 * failing this condition. The returned prefix set is sorted in the same order as the
516 * passed set, with the same comparator.
517 */
518 private static TreeSet<IpPrefix> deduplicatePrefixSet(final TreeSet<IpPrefix> src) {
519 final TreeSet<IpPrefix> dst = new TreeSet<>(src.comparator());
520 // Prefixes match addresses that share their upper part up to their length, therefore
521 // the only kind of possible overlap in two prefixes is strict inclusion of the longer
522 // (more restrictive) in the shorter (including equivalence if they have the same
523 // length).
524 // Because prefixes in the src set are sorted from shorter to longer, deduplicating
525 // is done by simply iterating in order, and not adding any longer prefix that is
526 // already covered by a shorter one.
527 newPrefixes:
528 for (IpPrefix newPrefix : src) {
529 for (IpPrefix existingPrefix : dst) {
530 if (existingPrefix.containsPrefix(newPrefix)) {
531 continue newPrefixes;
532 }
533 }
534 dst.add(newPrefix);
535 }
536 return dst;
537 }
538
539 /**
540 * Returns how many IPv4 addresses match any of the prefixes in the passed ordered set.
541 *
542 * Obviously this returns an integral value between 0 and 2**32.
543 * The behavior is undefined if any of the prefixes is not an IPv4 prefix or if the
544 * set is not ordered smallest prefix to longer prefix.
545 *
546 * @param prefixes the set of prefixes, ordered by length
547 */
548 public static long routedIPv4AddressCount(final TreeSet<IpPrefix> prefixes) {
549 long routedIPCount = 0;
550 for (final IpPrefix prefix : deduplicatePrefixSet(prefixes)) {
551 if (!prefix.isIPv4()) {
552 Log.wtf(TAG, "Non-IPv4 prefix in routedIPv4AddressCount");
553 }
554 int rank = 32 - prefix.getPrefixLength();
555 routedIPCount += 1L << rank;
556 }
557 return routedIPCount;
558 }
559
560 /**
561 * Returns how many IPv6 addresses match any of the prefixes in the passed ordered set.
562 *
563 * This returns a BigInteger between 0 and 2**128.
564 * The behavior is undefined if any of the prefixes is not an IPv6 prefix or if the
565 * set is not ordered smallest prefix to longer prefix.
566 */
567 public static BigInteger routedIPv6AddressCount(final TreeSet<IpPrefix> prefixes) {
568 BigInteger routedIPCount = BigInteger.ZERO;
569 for (final IpPrefix prefix : deduplicatePrefixSet(prefixes)) {
570 if (!prefix.isIPv6()) {
571 Log.wtf(TAG, "Non-IPv6 prefix in routedIPv6AddressCount");
572 }
573 int rank = 128 - prefix.getPrefixLength();
574 routedIPCount = routedIPCount.add(BigInteger.ONE.shiftLeft(rank));
575 }
576 return routedIPCount;
577 }
Eran Messeria2e0ca72018-09-20 15:15:41 +0100578
579 private static final int[] ADDRESS_FAMILIES = new int[] {AF_INET, AF_INET6};
580
581 /**
582 * Returns true if the hostname is weakly validated.
583 * @param hostname Name of host to validate.
584 * @return True if it's a valid-ish hostname.
585 *
586 * @hide
587 */
588 public static boolean isWeaklyValidatedHostname(@NonNull String hostname) {
589 // TODO(b/34953048): Use a validation method that permits more accurate,
590 // but still inexpensive, checking of likely valid DNS hostnames.
591 final String weakHostnameRegex = "^[a-zA-Z0-9_.-]+$";
592 if (!hostname.matches(weakHostnameRegex)) {
593 return false;
594 }
595
596 for (int address_family : ADDRESS_FAMILIES) {
597 if (Os.inet_pton(address_family, hostname) != null) {
598 return false;
599 }
600 }
601
602 return true;
603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604}