blob: b24d3969f760df4996c649ec92d0add96efba16c [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 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700112 * Convert a IPv4 address from an integer to an InetAddress.
Jesse Wilson07481cc2011-01-06 17:18:23 -0800113 * @param hostAddress an int corresponding to the IPv4 address in network byte order
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700114 */
115 public static InetAddress intToInetAddress(int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700116 byte[] addressBytes = { (byte)(0xff & hostAddress),
117 (byte)(0xff & (hostAddress >> 8)),
118 (byte)(0xff & (hostAddress >> 16)),
119 (byte)(0xff & (hostAddress >> 24)) };
120
121 try {
Jesse Wilson07481cc2011-01-06 17:18:23 -0800122 return InetAddress.getByAddress(addressBytes);
123 } catch (UnknownHostException e) {
124 throw new AssertionError();
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700125 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700126 }
127
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700128 /**
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700129 * Convert a IPv4 address from an InetAddress to an integer
130 * @param inetAddr is an InetAddress corresponding to the IPv4 address
131 * @return the IP address as an integer in network byte order
132 */
Robert Greenwalt4717c262012-10-31 14:32:53 -0700133 public static int inetAddressToInt(Inet4Address inetAddr)
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700134 throws IllegalArgumentException {
135 byte [] addr = inetAddr.getAddress();
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700136 return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) |
137 ((addr[1] & 0xff) << 8) | (addr[0] & 0xff);
138 }
139
140 /**
141 * Convert a network prefix length to an IPv4 netmask integer
142 * @param prefixLength
143 * @return the IPv4 netmask as an integer in network byte order
144 */
145 public static int prefixLengthToNetmaskInt(int prefixLength)
146 throws IllegalArgumentException {
147 if (prefixLength < 0 || prefixLength > 32) {
148 throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)");
149 }
150 int value = 0xffffffff << (32 - prefixLength);
151 return Integer.reverseBytes(value);
152 }
153
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700154 /**
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700155 * Convert a IPv4 netmask integer to a prefix length
156 * @param netmask as an integer in network byte order
157 * @return the network prefix length
158 */
159 public static int netmaskIntToPrefixLength(int netmask) {
160 return Integer.bitCount(netmask);
161 }
162
163 /**
Robert Greenwalt0216e612011-01-14 16:29:58 -0800164 * Create an InetAddress from a string where the string must be a standard
165 * representation of a V4 or V6 address. Avoids doing a DNS lookup on failure
166 * but it will throw an IllegalArgumentException in that case.
167 * @param addrString
168 * @return the InetAddress
169 * @hide
170 */
171 public static InetAddress numericToInetAddress(String addrString)
172 throws IllegalArgumentException {
Elliott Hughesf5bbb572011-02-15 17:11:29 -0800173 return InetAddress.parseNumericAddress(addrString);
Robert Greenwalt0216e612011-01-14 16:29:58 -0800174 }
175
176 /**
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700177 * Get InetAddress masked with prefixLength. Will never return null.
178 * @param IP address which will be masked with specified prefixLength
179 * @param prefixLength the prefixLength used to mask the IP
180 */
181 public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
182 if (address == null) {
183 throw new RuntimeException("getNetworkPart doesn't accept null address");
184 }
185
186 byte[] array = address.getAddress();
187
188 if (prefixLength < 0 || prefixLength > array.length * 8) {
189 throw new RuntimeException("getNetworkPart - bad prefixLength");
190 }
191
192 int offset = prefixLength / 8;
193 int reminder = prefixLength % 8;
194 byte mask = (byte)(0xFF << (8 - reminder));
195
196 if (offset < array.length) array[offset] = (byte)(array[offset] & mask);
197
198 offset++;
199
200 for (; offset < array.length; offset++) {
201 array[offset] = 0;
202 }
203
204 InetAddress netPart = null;
205 try {
206 netPart = InetAddress.getByAddress(array);
207 } catch (UnknownHostException e) {
208 throw new RuntimeException("getNetworkPart error - " + e.toString());
209 }
210 return netPart;
211 }
212
213 /**
214 * Check if IP address type is consistent between two InetAddress.
215 * @return true if both are the same type. False otherwise.
216 */
217 public static boolean addressTypeMatches(InetAddress left, InetAddress right) {
218 return (((left instanceof Inet4Address) && (right instanceof Inet4Address)) ||
219 ((left instanceof Inet6Address) && (right instanceof Inet6Address)));
220 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700221
222 /**
223 * Convert a 32 char hex string into a Inet6Address.
224 * throws a runtime exception if the string isn't 32 chars, isn't hex or can't be
225 * made into an Inet6Address
226 * @param addrHexString a 32 character hex string representing an IPv6 addr
227 * @return addr an InetAddress representation for the string
228 */
229 public static InetAddress hexToInet6Address(String addrHexString)
230 throws IllegalArgumentException {
231 try {
Jeff Sharkeyfea17de2013-06-11 14:13:09 -0700232 return numericToInetAddress(String.format(Locale.US, "%s:%s:%s:%s:%s:%s:%s:%s",
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700233 addrHexString.substring(0,4), addrHexString.substring(4,8),
234 addrHexString.substring(8,12), addrHexString.substring(12,16),
235 addrHexString.substring(16,20), addrHexString.substring(20,24),
236 addrHexString.substring(24,28), addrHexString.substring(28,32)));
237 } catch (Exception e) {
238 Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e);
239 throw new IllegalArgumentException(e);
240 }
241 }
Robert Greenwalta10b7fd2011-07-25 16:06:25 -0700242
243 /**
244 * Create a string array of host addresses from a collection of InetAddresses
245 * @param addrs a Collection of InetAddresses
246 * @return an array of Strings containing their host addresses
247 */
248 public static String[] makeStrings(Collection<InetAddress> addrs) {
249 String[] result = new String[addrs.size()];
250 int i = 0;
251 for (InetAddress addr : addrs) {
252 result[i++] = addr.getHostAddress();
253 }
254 return result;
255 }
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800256
257 /**
258 * Trim leading zeros from IPv4 address strings
259 * Our base libraries will interpret that as octel..
260 * Must leave non v4 addresses and host names alone.
261 * For example, 192.168.000.010 -> 192.168.0.10
262 * TODO - fix base libraries and remove this function
263 * @param addr a string representing an ip addr
264 * @return a string propertly trimmed
265 */
266 public static String trimV4AddrZeros(String addr) {
Robert Greenwalt0faacf02011-12-07 16:43:59 -0800267 if (addr == null) return null;
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800268 String[] octets = addr.split("\\.");
269 if (octets.length != 4) return addr;
270 StringBuilder builder = new StringBuilder(16);
271 String result = null;
272 for (int i = 0; i < 4; i++) {
273 try {
Robert Greenwalt3957b5f2011-12-07 13:10:59 -0800274 if (octets[i].length() > 3) return addr;
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800275 builder.append(Integer.parseInt(octets[i]));
276 } catch (NumberFormatException e) {
277 return addr;
278 }
279 if (i < 3) builder.append('.');
280 }
281 result = builder.toString();
282 return result;
283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284}