Home | History | Annotate | Download | only in net
      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 
     25 import android.util.Log;
     26 
     27 /**
     28  * Native methods for managing network interfaces.
     29  *
     30  * {@hide}
     31  */
     32 public class NetworkUtils {
     33 
     34     private static final String TAG = "NetworkUtils";
     35 
     36     /** Bring the named network interface up. */
     37     public native static int enableInterface(String interfaceName);
     38 
     39     /** Bring the named network interface down. */
     40     public native static int disableInterface(String interfaceName);
     41 
     42     /** Setting bit 0 indicates reseting of IPv4 addresses required */
     43     public static final int RESET_IPV4_ADDRESSES = 0x01;
     44 
     45     /** Setting bit 1 indicates reseting of IPv4 addresses required */
     46     public static final int RESET_IPV6_ADDRESSES = 0x02;
     47 
     48     /** Reset all addresses */
     49     public static final int RESET_ALL_ADDRESSES = RESET_IPV4_ADDRESSES | RESET_IPV6_ADDRESSES;
     50 
     51     /**
     52      * Reset IPv6 or IPv4 sockets that are connected via the named interface.
     53      *
     54      * @param interfaceName is the interface to reset
     55      * @param mask {@see #RESET_IPV4_ADDRESSES} and {@see #RESET_IPV6_ADDRESSES}
     56      */
     57     public native static int resetConnections(String interfaceName, int mask);
     58 
     59     /**
     60      * Start the DHCP client daemon, in order to have it request addresses
     61      * for the named interface, and then configure the interface with those
     62      * addresses. This call blocks until it obtains a result (either success
     63      * or failure) from the daemon.
     64      * @param interfaceName the name of the interface to configure
     65      * @param ipInfo if the request succeeds, this object is filled in with
     66      * the IP address information.
     67      * @return {@code true} for success, {@code false} for failure
     68      */
     69     public native static boolean runDhcp(String interfaceName, DhcpInfoInternal ipInfo);
     70 
     71     /**
     72      * Initiate renewal on the Dhcp client daemon. This call blocks until it obtains
     73      * a result (either success or failure) from the daemon.
     74      * @param interfaceName the name of the interface to configure
     75      * @param ipInfo if the request succeeds, this object is filled in with
     76      * the IP address information.
     77      * @return {@code true} for success, {@code false} for failure
     78      */
     79     public native static boolean runDhcpRenew(String interfaceName, DhcpInfoInternal ipInfo);
     80 
     81     /**
     82      * Shut down the DHCP client daemon.
     83      * @param interfaceName the name of the interface for which the daemon
     84      * should be stopped
     85      * @return {@code true} for success, {@code false} for failure
     86      */
     87     public native static boolean stopDhcp(String interfaceName);
     88 
     89     /**
     90      * Release the current DHCP lease.
     91      * @param interfaceName the name of the interface for which the lease should
     92      * be released
     93      * @return {@code true} for success, {@code false} for failure
     94      */
     95     public native static boolean releaseDhcpLease(String interfaceName);
     96 
     97     /**
     98      * Return the last DHCP-related error message that was recorded.
     99      * <p/>NOTE: This string is not localized, but currently it is only
    100      * used in logging.
    101      * @return the most recent error message, if any
    102      */
    103     public native static String getDhcpError();
    104 
    105     /**
    106      * Convert a IPv4 address from an integer to an InetAddress.
    107      * @param hostAddress an int corresponding to the IPv4 address in network byte order
    108      */
    109     public static InetAddress intToInetAddress(int hostAddress) {
    110         byte[] addressBytes = { (byte)(0xff & hostAddress),
    111                                 (byte)(0xff & (hostAddress >> 8)),
    112                                 (byte)(0xff & (hostAddress >> 16)),
    113                                 (byte)(0xff & (hostAddress >> 24)) };
    114 
    115         try {
    116            return InetAddress.getByAddress(addressBytes);
    117         } catch (UnknownHostException e) {
    118            throw new AssertionError();
    119         }
    120     }
    121 
    122     /**
    123      * Convert a IPv4 address from an InetAddress to an integer
    124      * @param inetAddr is an InetAddress corresponding to the IPv4 address
    125      * @return the IP address as an integer in network byte order
    126      */
    127     public static int inetAddressToInt(InetAddress inetAddr)
    128             throws IllegalArgumentException {
    129         byte [] addr = inetAddr.getAddress();
    130         if (addr.length != 4) {
    131             throw new IllegalArgumentException("Not an IPv4 address");
    132         }
    133         return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) |
    134                 ((addr[1] & 0xff) << 8) | (addr[0] & 0xff);
    135     }
    136 
    137     /**
    138      * Convert a network prefix length to an IPv4 netmask integer
    139      * @param prefixLength
    140      * @return the IPv4 netmask as an integer in network byte order
    141      */
    142     public static int prefixLengthToNetmaskInt(int prefixLength)
    143             throws IllegalArgumentException {
    144         if (prefixLength < 0 || prefixLength > 32) {
    145             throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)");
    146         }
    147         int value = 0xffffffff << (32 - prefixLength);
    148         return Integer.reverseBytes(value);
    149     }
    150 
    151     /**
    152      * Convert a IPv4 netmask integer to a prefix length
    153      * @param netmask as an integer in network byte order
    154      * @return the network prefix length
    155      */
    156     public static int netmaskIntToPrefixLength(int netmask) {
    157         return Integer.bitCount(netmask);
    158     }
    159 
    160     /**
    161      * Create an InetAddress from a string where the string must be a standard
    162      * representation of a V4 or V6 address.  Avoids doing a DNS lookup on failure
    163      * but it will throw an IllegalArgumentException in that case.
    164      * @param addrString
    165      * @return the InetAddress
    166      * @hide
    167      */
    168     public static InetAddress numericToInetAddress(String addrString)
    169             throws IllegalArgumentException {
    170         return InetAddress.parseNumericAddress(addrString);
    171     }
    172 
    173     /**
    174      * Get InetAddress masked with prefixLength.  Will never return null.
    175      * @param IP address which will be masked with specified prefixLength
    176      * @param prefixLength the prefixLength used to mask the IP
    177      */
    178     public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
    179         if (address == null) {
    180             throw new RuntimeException("getNetworkPart doesn't accept null address");
    181         }
    182 
    183         byte[] array = address.getAddress();
    184 
    185         if (prefixLength < 0 || prefixLength > array.length * 8) {
    186             throw new RuntimeException("getNetworkPart - bad prefixLength");
    187         }
    188 
    189         int offset = prefixLength / 8;
    190         int reminder = prefixLength % 8;
    191         byte mask = (byte)(0xFF << (8 - reminder));
    192 
    193         if (offset < array.length) array[offset] = (byte)(array[offset] & mask);
    194 
    195         offset++;
    196 
    197         for (; offset < array.length; offset++) {
    198             array[offset] = 0;
    199         }
    200 
    201         InetAddress netPart = null;
    202         try {
    203             netPart = InetAddress.getByAddress(array);
    204         } catch (UnknownHostException e) {
    205             throw new RuntimeException("getNetworkPart error - " + e.toString());
    206         }
    207         return netPart;
    208     }
    209 
    210     /**
    211      * Check if IP address type is consistent between two InetAddress.
    212      * @return true if both are the same type.  False otherwise.
    213      */
    214     public static boolean addressTypeMatches(InetAddress left, InetAddress right) {
    215         return (((left instanceof Inet4Address) && (right instanceof Inet4Address)) ||
    216                 ((left instanceof Inet6Address) && (right instanceof Inet6Address)));
    217     }
    218 
    219     /**
    220      * Convert a 32 char hex string into a Inet6Address.
    221      * throws a runtime exception if the string isn't 32 chars, isn't hex or can't be
    222      * made into an Inet6Address
    223      * @param addrHexString a 32 character hex string representing an IPv6 addr
    224      * @return addr an InetAddress representation for the string
    225      */
    226     public static InetAddress hexToInet6Address(String addrHexString)
    227             throws IllegalArgumentException {
    228         try {
    229             return numericToInetAddress(String.format("%s:%s:%s:%s:%s:%s:%s:%s",
    230                     addrHexString.substring(0,4),   addrHexString.substring(4,8),
    231                     addrHexString.substring(8,12),  addrHexString.substring(12,16),
    232                     addrHexString.substring(16,20), addrHexString.substring(20,24),
    233                     addrHexString.substring(24,28), addrHexString.substring(28,32)));
    234         } catch (Exception e) {
    235             Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e);
    236             throw new IllegalArgumentException(e);
    237         }
    238     }
    239 
    240     /**
    241      * Create a string array of host addresses from a collection of InetAddresses
    242      * @param addrs a Collection of InetAddresses
    243      * @return an array of Strings containing their host addresses
    244      */
    245     public static String[] makeStrings(Collection<InetAddress> addrs) {
    246         String[] result = new String[addrs.size()];
    247         int i = 0;
    248         for (InetAddress addr : addrs) {
    249             result[i++] = addr.getHostAddress();
    250         }
    251         return result;
    252     }
    253 }
    254