blob: edb32866d3b708dd10268674f9a5a6c2f10fbdf3 [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;
27
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028/**
29 * Native methods for managing network interfaces.
30 *
31 * {@hide}
32 */
33public class NetworkUtils {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070034
35 private static final String TAG = "NetworkUtils";
36
Mike Lockwood0900f362009-07-10 17:24:07 -040037 /** Bring the named network interface up. */
38 public native static int enableInterface(String interfaceName);
39
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040 /** Bring the named network interface down. */
41 public native static int disableInterface(String interfaceName);
42
Wink Saville8171e6f2011-07-07 16:17:06 -070043 /** Setting bit 0 indicates reseting of IPv4 addresses required */
44 public static final int RESET_IPV4_ADDRESSES = 0x01;
45
46 /** Setting bit 1 indicates reseting of IPv4 addresses required */
47 public static final int RESET_IPV6_ADDRESSES = 0x02;
48
49 /** Reset all addresses */
50 public static final int RESET_ALL_ADDRESSES = RESET_IPV4_ADDRESSES | RESET_IPV6_ADDRESSES;
51
52 /**
53 * Reset IPv6 or IPv4 sockets that are connected via the named interface.
54 *
55 * @param interfaceName is the interface to reset
56 * @param mask {@see #RESET_IPV4_ADDRESSES} and {@see #RESET_IPV6_ADDRESSES}
57 */
58 public native static int resetConnections(String interfaceName, int mask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059
60 /**
61 * Start the DHCP client daemon, in order to have it request addresses
62 * for the named interface, and then configure the interface with those
63 * addresses. This call blocks until it obtains a result (either success
64 * or failure) from the daemon.
65 * @param interfaceName the name of the interface to configure
Robert Greenwalt4717c262012-10-31 14:32:53 -070066 * @param dhcpResults if the request succeeds, this object is filled in with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 * the IP address information.
68 * @return {@code true} for success, {@code false} for failure
69 */
Robert Greenwalt4717c262012-10-31 14:32:53 -070070 public native static boolean runDhcp(String interfaceName, DhcpResults dhcpResults);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071
72 /**
Irfan Sheriff914ed902011-06-21 14:26:37 -070073 * Initiate renewal on the Dhcp client daemon. This call blocks until it obtains
74 * a result (either success or failure) from the daemon.
75 * @param interfaceName the name of the interface to configure
Robert Greenwalt4717c262012-10-31 14:32:53 -070076 * @param dhcpResults if the request succeeds, this object is filled in with
Irfan Sheriff914ed902011-06-21 14:26:37 -070077 * the IP address information.
78 * @return {@code true} for success, {@code false} for failure
79 */
Robert Greenwalt4717c262012-10-31 14:32:53 -070080 public native static boolean runDhcpRenew(String interfaceName, DhcpResults dhcpResults);
Irfan Sheriff914ed902011-06-21 14:26:37 -070081
82 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 * Shut down the DHCP client daemon.
84 * @param interfaceName the name of the interface for which the daemon
85 * should be stopped
86 * @return {@code true} for success, {@code false} for failure
87 */
88 public native static boolean stopDhcp(String interfaceName);
89
90 /**
91 * Release the current DHCP lease.
92 * @param interfaceName the name of the interface for which the lease should
93 * be released
94 * @return {@code true} for success, {@code false} for failure
95 */
96 public native static boolean releaseDhcpLease(String interfaceName);
97
98 /**
99 * Return the last DHCP-related error message that was recorded.
100 * <p/>NOTE: This string is not localized, but currently it is only
101 * used in logging.
102 * @return the most recent error message, if any
103 */
104 public native static String getDhcpError();
105
106 /**
Chad Brubaker12324b42013-07-11 13:30:36 -0700107 * Set the SO_MARK of {@code socketfd} to {@code mark}
108 */
109 public native static void markSocket(int socketfd, int mark);
110
111 /**
Paul Jensen38764952014-05-20 11:25:35 -0400112 * Binds the current process to the network designated by {@code netId}. All sockets created
113 * in the future (and not explicitly bound via a bound {@link SocketFactory} (see
114 * {@link Network#socketFactory}) will be bound to this network. Note that if this
115 * {@code Network} ever disconnects all sockets created in this way will cease to work. This
116 * is by design so an application doesn't accidentally use sockets it thinks are still bound to
117 * a particular {@code Network}.
118 */
119 public native static void bindProcessToNetwork(int netId);
120
121 /**
122 * Clear any process specific {@code Network} binding. This reverts a call to
123 * {@link #bindProcessToNetwork}.
124 */
125 public native static void unbindProcessToNetwork();
126
127 /**
128 * Return the netId last passed to {@link #bindProcessToNetwork}, or NETID_UNSET if
129 * {@link #unbindProcessToNetwork} has been called since {@link #bindProcessToNetwork}.
130 */
131 public native static int getNetworkBoundToProcess();
132
133 /**
134 * Binds host resolutions performed by this process to the network designated by {@code netId}.
135 * {@link #bindProcessToNetwork} takes precedence over this setting.
136 *
137 * @deprecated This is strictly for legacy usage to support startUsingNetworkFeature().
138 */
139 public native static void bindProcessToNetworkForHostResolution(int netId);
140
141 /**
142 * Clears any process specific {@link Network} binding for host resolution. This does
143 * not clear bindings enacted via {@link #bindProcessToNetwork}.
144 *
145 * @deprecated This is strictly for legacy usage to support startUsingNetworkFeature().
146 */
147 public native static void unbindProcessToNetworkForHostResolution();
148
149 /**
150 * Explicitly binds {@code socketfd} to the network designated by {@code netId}. This
151 * overrides any binding via {@link #bindProcessToNetwork}.
152 */
153 public native static void bindSocketToNetwork(int socketfd, int netId);
154
155 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700156 * Convert a IPv4 address from an integer to an InetAddress.
Jesse Wilson07481cc2011-01-06 17:18:23 -0800157 * @param hostAddress an int corresponding to the IPv4 address in network byte order
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700158 */
159 public static InetAddress intToInetAddress(int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700160 byte[] addressBytes = { (byte)(0xff & hostAddress),
161 (byte)(0xff & (hostAddress >> 8)),
162 (byte)(0xff & (hostAddress >> 16)),
163 (byte)(0xff & (hostAddress >> 24)) };
164
165 try {
Jesse Wilson07481cc2011-01-06 17:18:23 -0800166 return InetAddress.getByAddress(addressBytes);
167 } catch (UnknownHostException e) {
168 throw new AssertionError();
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700169 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700170 }
171
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700172 /**
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700173 * Convert a IPv4 address from an InetAddress to an integer
174 * @param inetAddr is an InetAddress corresponding to the IPv4 address
175 * @return the IP address as an integer in network byte order
176 */
Robert Greenwalt4717c262012-10-31 14:32:53 -0700177 public static int inetAddressToInt(Inet4Address inetAddr)
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700178 throws IllegalArgumentException {
179 byte [] addr = inetAddr.getAddress();
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700180 return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) |
181 ((addr[1] & 0xff) << 8) | (addr[0] & 0xff);
182 }
183
184 /**
185 * Convert a network prefix length to an IPv4 netmask integer
186 * @param prefixLength
187 * @return the IPv4 netmask as an integer in network byte order
188 */
189 public static int prefixLengthToNetmaskInt(int prefixLength)
190 throws IllegalArgumentException {
191 if (prefixLength < 0 || prefixLength > 32) {
192 throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)");
193 }
194 int value = 0xffffffff << (32 - prefixLength);
195 return Integer.reverseBytes(value);
196 }
197
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700198 /**
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700199 * Convert a IPv4 netmask integer to a prefix length
200 * @param netmask as an integer in network byte order
201 * @return the network prefix length
202 */
203 public static int netmaskIntToPrefixLength(int netmask) {
204 return Integer.bitCount(netmask);
205 }
206
207 /**
Robert Greenwalt0216e612011-01-14 16:29:58 -0800208 * Create an InetAddress from a string where the string must be a standard
209 * representation of a V4 or V6 address. Avoids doing a DNS lookup on failure
210 * but it will throw an IllegalArgumentException in that case.
211 * @param addrString
212 * @return the InetAddress
213 * @hide
214 */
215 public static InetAddress numericToInetAddress(String addrString)
216 throws IllegalArgumentException {
Elliott Hughesf5bbb572011-02-15 17:11:29 -0800217 return InetAddress.parseNumericAddress(addrString);
Robert Greenwalt0216e612011-01-14 16:29:58 -0800218 }
219
220 /**
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700221 * Get InetAddress masked with prefixLength. Will never return null.
222 * @param IP address which will be masked with specified prefixLength
223 * @param prefixLength the prefixLength used to mask the IP
224 */
225 public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
226 if (address == null) {
227 throw new RuntimeException("getNetworkPart doesn't accept null address");
228 }
229
230 byte[] array = address.getAddress();
231
232 if (prefixLength < 0 || prefixLength > array.length * 8) {
233 throw new RuntimeException("getNetworkPart - bad prefixLength");
234 }
235
236 int offset = prefixLength / 8;
237 int reminder = prefixLength % 8;
238 byte mask = (byte)(0xFF << (8 - reminder));
239
240 if (offset < array.length) array[offset] = (byte)(array[offset] & mask);
241
242 offset++;
243
244 for (; offset < array.length; offset++) {
245 array[offset] = 0;
246 }
247
248 InetAddress netPart = null;
249 try {
250 netPart = InetAddress.getByAddress(array);
251 } catch (UnknownHostException e) {
252 throw new RuntimeException("getNetworkPart error - " + e.toString());
253 }
254 return netPart;
255 }
256
257 /**
258 * Check if IP address type is consistent between two InetAddress.
259 * @return true if both are the same type. False otherwise.
260 */
261 public static boolean addressTypeMatches(InetAddress left, InetAddress right) {
262 return (((left instanceof Inet4Address) && (right instanceof Inet4Address)) ||
263 ((left instanceof Inet6Address) && (right instanceof Inet6Address)));
264 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700265
266 /**
267 * Convert a 32 char hex string into a Inet6Address.
268 * throws a runtime exception if the string isn't 32 chars, isn't hex or can't be
269 * made into an Inet6Address
270 * @param addrHexString a 32 character hex string representing an IPv6 addr
271 * @return addr an InetAddress representation for the string
272 */
273 public static InetAddress hexToInet6Address(String addrHexString)
274 throws IllegalArgumentException {
275 try {
Jeff Sharkeyfea17de2013-06-11 14:13:09 -0700276 return numericToInetAddress(String.format(Locale.US, "%s:%s:%s:%s:%s:%s:%s:%s",
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700277 addrHexString.substring(0,4), addrHexString.substring(4,8),
278 addrHexString.substring(8,12), addrHexString.substring(12,16),
279 addrHexString.substring(16,20), addrHexString.substring(20,24),
280 addrHexString.substring(24,28), addrHexString.substring(28,32)));
281 } catch (Exception e) {
282 Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e);
283 throw new IllegalArgumentException(e);
284 }
285 }
Robert Greenwalta10b7fd2011-07-25 16:06:25 -0700286
287 /**
288 * Create a string array of host addresses from a collection of InetAddresses
289 * @param addrs a Collection of InetAddresses
290 * @return an array of Strings containing their host addresses
291 */
292 public static String[] makeStrings(Collection<InetAddress> addrs) {
293 String[] result = new String[addrs.size()];
294 int i = 0;
295 for (InetAddress addr : addrs) {
296 result[i++] = addr.getHostAddress();
297 }
298 return result;
299 }
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800300
301 /**
302 * Trim leading zeros from IPv4 address strings
303 * Our base libraries will interpret that as octel..
304 * Must leave non v4 addresses and host names alone.
305 * For example, 192.168.000.010 -> 192.168.0.10
306 * TODO - fix base libraries and remove this function
307 * @param addr a string representing an ip addr
308 * @return a string propertly trimmed
309 */
310 public static String trimV4AddrZeros(String addr) {
Robert Greenwalt0faacf02011-12-07 16:43:59 -0800311 if (addr == null) return null;
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800312 String[] octets = addr.split("\\.");
313 if (octets.length != 4) return addr;
314 StringBuilder builder = new StringBuilder(16);
315 String result = null;
316 for (int i = 0; i < 4; i++) {
317 try {
Robert Greenwalt3957b5f2011-12-07 13:10:59 -0800318 if (octets[i].length() > 3) return addr;
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800319 builder.append(Integer.parseInt(octets[i]));
320 } catch (NumberFormatException e) {
321 return addr;
322 }
323 if (i < 3) builder.append('.');
324 }
325 result = builder.toString();
326 return result;
327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328}