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; 20 import java.net.Inet4Address; 21 import java.net.Inet6Address; 22 import java.net.UnknownHostException; 23 import java.util.Collection; 24 import java.util.Locale; 25 26 import android.util.Log; 27 28 /** 29 * Native methods for managing network interfaces. 30 * 31 * {@hide} 32 */ 33 public class NetworkUtils { 34 35 private static final String TAG = "NetworkUtils"; 36 37 /** Bring the named network interface up. */ enableInterface(String interfaceName)38 public native static int enableInterface(String interfaceName); 39 40 /** Bring the named network interface down. */ disableInterface(String interfaceName)41 public native static int disableInterface(String interfaceName); 42 43 /** 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 */ resetConnections(String interfaceName, int mask)58 public native static int resetConnections(String interfaceName, int mask); 59 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 66 * @param dhcpResults if the request succeeds, this object is filled in with 67 * the IP address information. 68 * @return {@code true} for success, {@code false} for failure 69 */ runDhcp(String interfaceName, DhcpResults dhcpResults)70 public native static boolean runDhcp(String interfaceName, DhcpResults dhcpResults); 71 72 /** 73 * 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 76 * @param dhcpResults if the request succeeds, this object is filled in with 77 * the IP address information. 78 * @return {@code true} for success, {@code false} for failure 79 */ runDhcpRenew(String interfaceName, DhcpResults dhcpResults)80 public native static boolean runDhcpRenew(String interfaceName, DhcpResults dhcpResults); 81 82 /** 83 * 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 */ stopDhcp(String interfaceName)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 */ releaseDhcpLease(String interfaceName)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 */ getDhcpError()104 public native static String getDhcpError(); 105 106 /** 107 * Set the SO_MARK of {@code socketfd} to {@code mark} 108 */ markSocket(int socketfd, int mark)109 public native static void markSocket(int socketfd, int mark); 110 111 /** 112 * 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#getSocketFactory}) 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 */ bindProcessToNetwork(int netId)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 */ unbindProcessToNetwork()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 */ getNetworkBoundToProcess()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 */ bindProcessToNetworkForHostResolution(int netId)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 */ unbindProcessToNetworkForHostResolution()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 */ bindSocketToNetwork(int socketfd, int netId)153 public native static void bindSocketToNetwork(int socketfd, int netId); 154 155 /** 156 * Convert a IPv4 address from an integer to an InetAddress. 157 * @param hostAddress an int corresponding to the IPv4 address in network byte order 158 */ intToInetAddress(int hostAddress)159 public static InetAddress intToInetAddress(int hostAddress) { 160 byte[] addressBytes = { (byte)(0xff & hostAddress), 161 (byte)(0xff & (hostAddress >> 8)), 162 (byte)(0xff & (hostAddress >> 16)), 163 (byte)(0xff & (hostAddress >> 24)) }; 164 165 try { 166 return InetAddress.getByAddress(addressBytes); 167 } catch (UnknownHostException e) { 168 throw new AssertionError(); 169 } 170 } 171 172 /** 173 * 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 */ inetAddressToInt(Inet4Address inetAddr)177 public static int inetAddressToInt(Inet4Address inetAddr) 178 throws IllegalArgumentException { 179 byte [] addr = inetAddr.getAddress(); 180 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 */ prefixLengthToNetmaskInt(int prefixLength)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 198 /** 199 * 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 */ netmaskIntToPrefixLength(int netmask)203 public static int netmaskIntToPrefixLength(int netmask) { 204 return Integer.bitCount(netmask); 205 } 206 207 /** 208 * 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 */ numericToInetAddress(String addrString)215 public static InetAddress numericToInetAddress(String addrString) 216 throws IllegalArgumentException { 217 return InetAddress.parseNumericAddress(addrString); 218 } 219 220 /** 221 * 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 */ getNetworkPart(InetAddress address, int prefixLength)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 */ addressTypeMatches(InetAddress left, InetAddress right)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 } 265 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 */ hexToInet6Address(String addrHexString)273 public static InetAddress hexToInet6Address(String addrHexString) 274 throws IllegalArgumentException { 275 try { 276 return numericToInetAddress(String.format(Locale.US, "%s:%s:%s:%s:%s:%s:%s:%s", 277 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 } 286 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 */ makeStrings(Collection<InetAddress> addrs)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 } 300 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 */ trimV4AddrZeros(String addr)310 public static String trimV4AddrZeros(String addr) { 311 if (addr == null) return null; 312 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 { 318 if (octets[i].length() > 3) return addr; 319 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 } 328 } 329