NetworkUtils.java revision fe3b33d4ead06c546202753e38188db5e2eaa7fa
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;
23
24import android.util.Log;
25
26/**
27 * Native methods for managing network interfaces.
28 *
29 * {@hide}
30 */
31public class NetworkUtils {
32
33    private static final String TAG = "NetworkUtils";
34
35    /** Bring the named network interface up. */
36    public native static int enableInterface(String interfaceName);
37
38    /** Bring the named network interface down. */
39    public native static int disableInterface(String interfaceName);
40
41    /**
42     * Add a route to the routing table.
43     *
44     * @param interfaceName the interface to route through.
45     * @param dst the network or host to route to. May be IPv4 or IPv6, e.g.
46     * "0.0.0.0" or "2001:4860::".
47     * @param prefixLength the prefix length of the route.
48     * @param gw the gateway to use, e.g., "192.168.251.1". If null,
49     * indicates a directly-connected route.
50     */
51    public native static int addRoute(String interfaceName, String dst,
52          int prefixLength, String gw);
53
54    /** Return the gateway address for the default route for the named interface. */
55    public static InetAddress getDefaultRoute(String interfaceName) {
56        int addr = getDefaultRouteNative(interfaceName);
57        return intToInetAddress(addr);
58    }
59    private native static int getDefaultRouteNative(String interfaceName);
60
61    /** Remove host routes that uses the named interface. */
62    public native static int removeHostRoutes(String interfaceName);
63
64    /** Remove the default route for the named interface. */
65    public native static int removeDefaultRoute(String interfaceName);
66
67    /** Reset any sockets that are connected via the named interface. */
68    public native static int resetConnections(String interfaceName);
69
70    /**
71     * Start the DHCP client daemon, in order to have it request addresses
72     * for the named interface, and then configure the interface with those
73     * addresses. This call blocks until it obtains a result (either success
74     * or failure) from the daemon.
75     * @param interfaceName the name of the interface to configure
76     * @param ipInfo 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 runDhcp(String interfaceName, DhcpInfoInternal ipInfo);
81
82    /**
83     * Initiate renewal on the Dhcp client daemon. This call blocks until it obtains
84     * a result (either success or failure) from the daemon.
85     * @param interfaceName the name of the interface to configure
86     * @param ipInfo if the request succeeds, this object is filled in with
87     * the IP address information.
88     * @return {@code true} for success, {@code false} for failure
89     */
90    public native static boolean runDhcpRenew(String interfaceName, DhcpInfoInternal ipInfo);
91
92    /**
93     * Shut down the DHCP client daemon.
94     * @param interfaceName the name of the interface for which the daemon
95     * should be stopped
96     * @return {@code true} for success, {@code false} for failure
97     */
98    public native static boolean stopDhcp(String interfaceName);
99
100    /**
101     * Release the current DHCP lease.
102     * @param interfaceName the name of the interface for which the lease should
103     * be released
104     * @return {@code true} for success, {@code false} for failure
105     */
106    public native static boolean releaseDhcpLease(String interfaceName);
107
108    /**
109     * Return the last DHCP-related error message that was recorded.
110     * <p/>NOTE: This string is not localized, but currently it is only
111     * used in logging.
112     * @return the most recent error message, if any
113     */
114    public native static String getDhcpError();
115
116    /**
117     * Convert a IPv4 address from an integer to an InetAddress.
118     * @param hostAddress an int corresponding to the IPv4 address in network byte order
119     */
120    public static InetAddress intToInetAddress(int hostAddress) {
121        byte[] addressBytes = { (byte)(0xff & hostAddress),
122                                (byte)(0xff & (hostAddress >> 8)),
123                                (byte)(0xff & (hostAddress >> 16)),
124                                (byte)(0xff & (hostAddress >> 24)) };
125
126        try {
127           return InetAddress.getByAddress(addressBytes);
128        } catch (UnknownHostException e) {
129           throw new AssertionError();
130        }
131    }
132
133    /**
134     * Convert a IPv4 address from an InetAddress to an integer
135     * @param inetAddr is an InetAddress corresponding to the IPv4 address
136     * @return the IP address as an integer in network byte order
137     */
138    public static int inetAddressToInt(InetAddress inetAddr)
139            throws IllegalArgumentException {
140        byte [] addr = inetAddr.getAddress();
141        if (addr.length != 4) {
142            throw new IllegalArgumentException("Not an IPv4 address");
143        }
144        return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) |
145                ((addr[1] & 0xff) << 8) | (addr[0] & 0xff);
146    }
147
148    /**
149     * Convert a network prefix length to an IPv4 netmask integer
150     * @param prefixLength
151     * @return the IPv4 netmask as an integer in network byte order
152     */
153    public static int prefixLengthToNetmaskInt(int prefixLength)
154            throws IllegalArgumentException {
155        if (prefixLength < 0 || prefixLength > 32) {
156            throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)");
157        }
158        int value = 0xffffffff << (32 - prefixLength);
159        return Integer.reverseBytes(value);
160    }
161
162    /**
163     * Create an InetAddress from a string where the string must be a standard
164     * representation of a V4 or V6 address.  Avoids doing a DNS lookup on failure
165     * but it will throw an IllegalArgumentException in that case.
166     * @param addrString
167     * @return the InetAddress
168     * @hide
169     */
170    public static InetAddress numericToInetAddress(String addrString)
171            throws IllegalArgumentException {
172        return InetAddress.parseNumericAddress(addrString);
173    }
174
175    /**
176     * Add a default route through the specified gateway.
177     * @param interfaceName interface on which the route should be added
178     * @param gw the IP address of the gateway to which the route is desired,
179     * @return {@code true} on success, {@code false} on failure
180     */
181    public static boolean addDefaultRoute(String interfaceName, InetAddress gw) {
182        String dstStr;
183        String gwStr = gw.getHostAddress();
184
185        if (gw instanceof Inet4Address) {
186            dstStr = "0.0.0.0";
187        } else if (gw instanceof Inet6Address) {
188            dstStr = "::";
189        } else {
190            Log.w(TAG, "addDefaultRoute failure: address is neither IPv4 nor IPv6" +
191                       "(" + gwStr + ")");
192            return false;
193        }
194        return addRoute(interfaceName, dstStr, 0, gwStr) == 0;
195    }
196
197    /**
198     * Add a host route.
199     * @param interfaceName interface on which the route should be added
200     * @param dst the IP address of the host to which the route is desired,
201     * this should not be null.
202     * @param gw the IP address of the gateway to which the route is desired,
203     * if null, indicates a directly-connected route.
204     * @return {@code true} on success, {@code false} on failure
205     */
206    public static boolean addHostRoute(String interfaceName, InetAddress dst,
207          InetAddress gw) {
208        if (dst == null) {
209            Log.w(TAG, "addHostRoute: dst should not be null");
210            return false;
211        }
212
213        int prefixLength;
214        String dstStr = dst.getHostAddress();
215        String gwStr = (gw != null) ? gw.getHostAddress() : null;
216
217        if (dst instanceof Inet4Address) {
218            prefixLength = 32;
219        } else if (dst instanceof Inet6Address) {
220            prefixLength = 128;
221        } else {
222            Log.w(TAG, "addHostRoute failure: address is neither IPv4 nor IPv6" +
223                       "(" + dst + ")");
224            return false;
225        }
226        return addRoute(interfaceName, dstStr, prefixLength, gwStr) == 0;
227    }
228}
229