blob: af860b0889923ef4eb5dac6828787bee672a1b8d [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
19import java.net.InetAddress;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070020import java.net.Inet4Address;
21import java.net.Inet6Address;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import java.net.UnknownHostException;
Robert Greenwalta10b7fd2011-07-25 16:06:25 -070023import java.util.Collection;
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070024import java.util.Locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070026import android.util.Log;
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +090027import android.util.Pair;
28
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030/**
31 * Native methods for managing network interfaces.
32 *
33 * {@hide}
34 */
35public class NetworkUtils {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070036
37 private static final String TAG = "NetworkUtils";
38
Mike Lockwood0900f362009-07-10 17:24:07 -040039 /** Bring the named network interface up. */
40 public native static int enableInterface(String interfaceName);
41
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042 /** Bring the named network interface down. */
43 public native static int disableInterface(String interfaceName);
44
Wink Saville8171e6f2011-07-07 16:17:06 -070045 /** Setting bit 0 indicates reseting of IPv4 addresses required */
46 public static final int RESET_IPV4_ADDRESSES = 0x01;
47
48 /** Setting bit 1 indicates reseting of IPv4 addresses required */
49 public static final int RESET_IPV6_ADDRESSES = 0x02;
50
51 /** Reset all addresses */
52 public static final int RESET_ALL_ADDRESSES = RESET_IPV4_ADDRESSES | RESET_IPV6_ADDRESSES;
53
54 /**
55 * Reset IPv6 or IPv4 sockets that are connected via the named interface.
56 *
57 * @param interfaceName is the interface to reset
58 * @param mask {@see #RESET_IPV4_ADDRESSES} and {@see #RESET_IPV6_ADDRESSES}
59 */
60 public native static int resetConnections(String interfaceName, int mask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061
62 /**
63 * Start the DHCP client daemon, in order to have it request addresses
64 * for the named interface, and then configure the interface with those
65 * addresses. This call blocks until it obtains a result (either success
66 * or failure) from the daemon.
67 * @param interfaceName the name of the interface to configure
Robert Greenwalt4717c262012-10-31 14:32:53 -070068 * @param dhcpResults if the request succeeds, this object is filled in with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069 * the IP address information.
70 * @return {@code true} for success, {@code false} for failure
71 */
Robert Greenwalt4717c262012-10-31 14:32:53 -070072 public native static boolean runDhcp(String interfaceName, DhcpResults dhcpResults);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073
74 /**
Irfan Sheriff914ed902011-06-21 14:26:37 -070075 * Initiate renewal on the Dhcp client daemon. This call blocks until it obtains
76 * a result (either success or failure) from the daemon.
77 * @param interfaceName the name of the interface to configure
Robert Greenwalt4717c262012-10-31 14:32:53 -070078 * @param dhcpResults if the request succeeds, this object is filled in with
Irfan Sheriff914ed902011-06-21 14:26:37 -070079 * the IP address information.
80 * @return {@code true} for success, {@code false} for failure
81 */
Robert Greenwalt4717c262012-10-31 14:32:53 -070082 public native static boolean runDhcpRenew(String interfaceName, DhcpResults dhcpResults);
Irfan Sheriff914ed902011-06-21 14:26:37 -070083
84 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 * Shut down the DHCP client daemon.
86 * @param interfaceName the name of the interface for which the daemon
87 * should be stopped
88 * @return {@code true} for success, {@code false} for failure
89 */
90 public native static boolean stopDhcp(String interfaceName);
91
92 /**
93 * Release the current DHCP lease.
94 * @param interfaceName the name of the interface for which the lease should
95 * be released
96 * @return {@code true} for success, {@code false} for failure
97 */
98 public native static boolean releaseDhcpLease(String interfaceName);
99
100 /**
101 * Return the last DHCP-related error message that was recorded.
102 * <p/>NOTE: This string is not localized, but currently it is only
103 * used in logging.
104 * @return the most recent error message, if any
105 */
106 public native static String getDhcpError();
107
108 /**
Chad Brubaker12324b42013-07-11 13:30:36 -0700109 * Set the SO_MARK of {@code socketfd} to {@code mark}
110 */
111 public native static void markSocket(int socketfd, int mark);
112
113 /**
Paul Jensen38764952014-05-20 11:25:35 -0400114 * Binds the current process to the network designated by {@code netId}. All sockets created
115 * in the future (and not explicitly bound via a bound {@link SocketFactory} (see
Paul Jensen6d3ff9e2014-05-29 10:12:39 -0400116 * {@link Network#getSocketFactory}) will be bound to this network. Note that if this
Paul Jensen38764952014-05-20 11:25:35 -0400117 * {@code Network} ever disconnects all sockets created in this way will cease to work. This
118 * is by design so an application doesn't accidentally use sockets it thinks are still bound to
Paul Jensenbcc76d32014-07-11 08:17:29 -0400119 * a particular {@code Network}. Passing NETID_UNSET clears the binding.
Paul Jensen38764952014-05-20 11:25:35 -0400120 */
Paul Jensen32a58f02014-06-20 13:58:14 -0400121 public native static boolean bindProcessToNetwork(int netId);
Paul Jensen38764952014-05-20 11:25:35 -0400122
123 /**
Paul Jensen38764952014-05-20 11:25:35 -0400124 * Return the netId last passed to {@link #bindProcessToNetwork}, or NETID_UNSET if
125 * {@link #unbindProcessToNetwork} has been called since {@link #bindProcessToNetwork}.
126 */
127 public native static int getNetworkBoundToProcess();
128
129 /**
130 * Binds host resolutions performed by this process to the network designated by {@code netId}.
Paul Jensenbcc76d32014-07-11 08:17:29 -0400131 * {@link #bindProcessToNetwork} takes precedence over this setting. Passing NETID_UNSET clears
132 * the binding.
Paul Jensen38764952014-05-20 11:25:35 -0400133 *
134 * @deprecated This is strictly for legacy usage to support startUsingNetworkFeature().
135 */
Paul Jensen32a58f02014-06-20 13:58:14 -0400136 public native static boolean bindProcessToNetworkForHostResolution(int netId);
Paul Jensen38764952014-05-20 11:25:35 -0400137
138 /**
Paul Jensen38764952014-05-20 11:25:35 -0400139 * Explicitly binds {@code socketfd} to the network designated by {@code netId}. This
140 * overrides any binding via {@link #bindProcessToNetwork}.
141 */
Paul Jensen32a58f02014-06-20 13:58:14 -0400142 public native static boolean bindSocketToNetwork(int socketfd, int netId);
Paul Jensen38764952014-05-20 11:25:35 -0400143
144 /**
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400145 * Protect {@code socketfd} from VPN connections. After protecting, data sent through
146 * this socket will go directly to the underlying network, so its traffic will not be
147 * forwarded through the VPN.
148 */
149 public native static boolean protectFromVpn(int socketfd);
150
151 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700152 * Convert a IPv4 address from an integer to an InetAddress.
Jesse Wilson07481cc2011-01-06 17:18:23 -0800153 * @param hostAddress an int corresponding to the IPv4 address in network byte order
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700154 */
155 public static InetAddress intToInetAddress(int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700156 byte[] addressBytes = { (byte)(0xff & hostAddress),
157 (byte)(0xff & (hostAddress >> 8)),
158 (byte)(0xff & (hostAddress >> 16)),
159 (byte)(0xff & (hostAddress >> 24)) };
160
161 try {
Jesse Wilson07481cc2011-01-06 17:18:23 -0800162 return InetAddress.getByAddress(addressBytes);
163 } catch (UnknownHostException e) {
164 throw new AssertionError();
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700165 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700166 }
167
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700168 /**
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700169 * Convert a IPv4 address from an InetAddress to an integer
170 * @param inetAddr is an InetAddress corresponding to the IPv4 address
171 * @return the IP address as an integer in network byte order
172 */
Robert Greenwalt4717c262012-10-31 14:32:53 -0700173 public static int inetAddressToInt(Inet4Address inetAddr)
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700174 throws IllegalArgumentException {
175 byte [] addr = inetAddr.getAddress();
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700176 return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) |
177 ((addr[1] & 0xff) << 8) | (addr[0] & 0xff);
178 }
179
180 /**
181 * Convert a network prefix length to an IPv4 netmask integer
182 * @param prefixLength
183 * @return the IPv4 netmask as an integer in network byte order
184 */
185 public static int prefixLengthToNetmaskInt(int prefixLength)
186 throws IllegalArgumentException {
187 if (prefixLength < 0 || prefixLength > 32) {
188 throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)");
189 }
190 int value = 0xffffffff << (32 - prefixLength);
191 return Integer.reverseBytes(value);
192 }
193
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700194 /**
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700195 * Convert a IPv4 netmask integer to a prefix length
196 * @param netmask as an integer in network byte order
197 * @return the network prefix length
198 */
199 public static int netmaskIntToPrefixLength(int netmask) {
200 return Integer.bitCount(netmask);
201 }
202
203 /**
Robert Greenwalt0216e612011-01-14 16:29:58 -0800204 * Create an InetAddress from a string where the string must be a standard
205 * representation of a V4 or V6 address. Avoids doing a DNS lookup on failure
206 * but it will throw an IllegalArgumentException in that case.
207 * @param addrString
208 * @return the InetAddress
209 * @hide
210 */
211 public static InetAddress numericToInetAddress(String addrString)
212 throws IllegalArgumentException {
Elliott Hughesf5bbb572011-02-15 17:11:29 -0800213 return InetAddress.parseNumericAddress(addrString);
Robert Greenwalt0216e612011-01-14 16:29:58 -0800214 }
215
216 /**
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900217 * Masks a raw IP address byte array with the specified prefix length.
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700218 */
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900219 public static void maskRawAddress(byte[] array, int prefixLength) {
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700220 if (prefixLength < 0 || prefixLength > array.length * 8) {
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900221 throw new RuntimeException("IP address with " + array.length +
222 " bytes has invalid prefix length " + prefixLength);
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700223 }
224
225 int offset = prefixLength / 8;
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900226 int remainder = prefixLength % 8;
227 byte mask = (byte)(0xFF << (8 - remainder));
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700228
229 if (offset < array.length) array[offset] = (byte)(array[offset] & mask);
230
231 offset++;
232
233 for (; offset < array.length; offset++) {
234 array[offset] = 0;
235 }
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900236 }
237
238 /**
239 * Get InetAddress masked with prefixLength. Will never return null.
240 * @param address the IP address to mask with
241 * @param prefixLength the prefixLength used to mask the IP
242 */
243 public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
244 byte[] array = address.getAddress();
245 maskRawAddress(array, prefixLength);
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700246
247 InetAddress netPart = null;
248 try {
249 netPart = InetAddress.getByAddress(array);
250 } catch (UnknownHostException e) {
251 throw new RuntimeException("getNetworkPart error - " + e.toString());
252 }
253 return netPart;
254 }
255
256 /**
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900257 * Utility method to parse strings such as "192.0.2.5/24" or "2001:db8::cafe:d00d/64".
258 * @hide
259 */
260 public static Pair<InetAddress, Integer> parseIpAndMask(String ipAndMaskString) {
261 InetAddress address = null;
262 int prefixLength = -1;
263 try {
264 String[] pieces = ipAndMaskString.split("/", 2);
265 prefixLength = Integer.parseInt(pieces[1]);
266 address = InetAddress.parseNumericAddress(pieces[0]);
267 } catch (NullPointerException e) { // Null string.
268 } catch (ArrayIndexOutOfBoundsException e) { // No prefix length.
269 } catch (NumberFormatException e) { // Non-numeric prefix.
270 } catch (IllegalArgumentException e) { // Invalid IP address.
271 }
272
273 if (address == null || prefixLength == -1) {
274 throw new IllegalArgumentException("Invalid IP address and mask " + ipAndMaskString);
275 }
276
277 return new Pair<InetAddress, Integer>(address, prefixLength);
278 }
279
280 /**
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700281 * Check if IP address type is consistent between two InetAddress.
282 * @return true if both are the same type. False otherwise.
283 */
284 public static boolean addressTypeMatches(InetAddress left, InetAddress right) {
285 return (((left instanceof Inet4Address) && (right instanceof Inet4Address)) ||
286 ((left instanceof Inet6Address) && (right instanceof Inet6Address)));
287 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700288
289 /**
290 * Convert a 32 char hex string into a Inet6Address.
291 * throws a runtime exception if the string isn't 32 chars, isn't hex or can't be
292 * made into an Inet6Address
293 * @param addrHexString a 32 character hex string representing an IPv6 addr
294 * @return addr an InetAddress representation for the string
295 */
296 public static InetAddress hexToInet6Address(String addrHexString)
297 throws IllegalArgumentException {
298 try {
Jeff Sharkeyfea17de2013-06-11 14:13:09 -0700299 return numericToInetAddress(String.format(Locale.US, "%s:%s:%s:%s:%s:%s:%s:%s",
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700300 addrHexString.substring(0,4), addrHexString.substring(4,8),
301 addrHexString.substring(8,12), addrHexString.substring(12,16),
302 addrHexString.substring(16,20), addrHexString.substring(20,24),
303 addrHexString.substring(24,28), addrHexString.substring(28,32)));
304 } catch (Exception e) {
305 Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e);
306 throw new IllegalArgumentException(e);
307 }
308 }
Robert Greenwalta10b7fd2011-07-25 16:06:25 -0700309
310 /**
311 * Create a string array of host addresses from a collection of InetAddresses
312 * @param addrs a Collection of InetAddresses
313 * @return an array of Strings containing their host addresses
314 */
315 public static String[] makeStrings(Collection<InetAddress> addrs) {
316 String[] result = new String[addrs.size()];
317 int i = 0;
318 for (InetAddress addr : addrs) {
319 result[i++] = addr.getHostAddress();
320 }
321 return result;
322 }
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800323
324 /**
325 * Trim leading zeros from IPv4 address strings
326 * Our base libraries will interpret that as octel..
327 * Must leave non v4 addresses and host names alone.
328 * For example, 192.168.000.010 -> 192.168.0.10
329 * TODO - fix base libraries and remove this function
330 * @param addr a string representing an ip addr
331 * @return a string propertly trimmed
332 */
333 public static String trimV4AddrZeros(String addr) {
Robert Greenwalt0faacf02011-12-07 16:43:59 -0800334 if (addr == null) return null;
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800335 String[] octets = addr.split("\\.");
336 if (octets.length != 4) return addr;
337 StringBuilder builder = new StringBuilder(16);
338 String result = null;
339 for (int i = 0; i < 4; i++) {
340 try {
Robert Greenwalt3957b5f2011-12-07 13:10:59 -0800341 if (octets[i].length() > 3) return addr;
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800342 builder.append(Integer.parseInt(octets[i]));
343 } catch (NumberFormatException e) {
344 return addr;
345 }
346 if (i < 3) builder.append('.');
347 }
348 result = builder.toString();
349 return result;
350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351}