NetworkUtils.java revision 12324b46049f9bcba9aa3d5fe7ae540d49a03076
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
17package android.net;
18
19import java.net.InetAddress;
20import java.net.Inet4Address;
21import java.net.Inet6Address;
22import java.net.UnknownHostException;
23import java.util.Collection;
24import java.util.Locale;
25
26import android.util.Log;
27
28/**
29 * Native methods for managing network interfaces.
30 *
31 * {@hide}
32 */
33public class NetworkUtils {
34
35    private static final String TAG = "NetworkUtils";
36
37    /** Bring the named network interface up. */
38    public native static int enableInterface(String interfaceName);
39
40    /** Bring the named network interface down. */
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     */
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     */
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     */
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     */
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    /**
107     * Set the SO_MARK of {@code socketfd} to {@code mark}
108     */
109    public native static void markSocket(int socketfd, int mark);
110
111    /**
112     * Convert a IPv4 address from an integer to an InetAddress.
113     * @param hostAddress an int corresponding to the IPv4 address in network byte order
114     */
115    public static InetAddress intToInetAddress(int hostAddress) {
116        byte[] addressBytes = { (byte)(0xff & hostAddress),
117                                (byte)(0xff & (hostAddress >> 8)),
118                                (byte)(0xff & (hostAddress >> 16)),
119                                (byte)(0xff & (hostAddress >> 24)) };
120
121        try {
122           return InetAddress.getByAddress(addressBytes);
123        } catch (UnknownHostException e) {
124           throw new AssertionError();
125        }
126    }
127
128    /**
129     * 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     */
133    public static int inetAddressToInt(Inet4Address inetAddr)
134            throws IllegalArgumentException {
135        byte [] addr = inetAddr.getAddress();
136        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
154    /**
155     * 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    /**
164     * 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 {
173        return InetAddress.parseNumericAddress(addrString);
174    }
175
176    /**
177     * 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    }
221
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 {
232            return numericToInetAddress(String.format(Locale.US, "%s:%s:%s:%s:%s:%s:%s:%s",
233                    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    }
242
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    }
256
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) {
267        if (addr == null) return null;
268        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 {
274                if (octets[i].length() > 3) return addr;
275                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    }
284}
285