为usb网卡设置ip地址之二

    private boolean setIpAndMask(String ip,String mask){
            Log.i(TAG," ip=" + ip +",mask=" + mask);
            // bring toggle the interfaces
            IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
            INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
            String[] currentIfaces = new String[0];
            try {
                currentIfaces = service.listInterfaces();
            } catch (Exception e) {
                Log.w(TAG, "listInterfaces="+e);
                return false;
            }
            
            boolean found = false;
            for (String currIface: currentIfaces) {
                if (currIface.equals(ETH0)) {
                    Log.d(TAG, "eth0 iface found");
                    found = true;
                    break;
                }
            }
            if (!found) {
                Log.d(TAG, "eth0 iface NOT found");
                return false;
            }
            InterfaceConfiguration ifcg = null;
            try {
                ifcg = service.getInterfaceConfig(ETH0);
                if (ifcg != null) {
                    Log.i(TAG,"ifcg first="+ifcg);
                    InetAddress addr = null;
                    if (ifcg.addr == null || (addr = ifcg.addr.getAddress()) == null ||
                            addr.equals(NetworkUtils.numericToInetAddress("0.0.0.0")) ||
                            addr.equals(NetworkUtils.numericToInetAddress("::0"))) {
                        addr = NetworkUtils.numericToInetAddress(ip);
                    } else {
                        addr = NetworkUtils.numericToInetAddress(ip);
                    }
                    ifcg.interfaceFlags = ifcg.interfaceFlags.replace("down", "up");
                    InetAddress gw = NetworkUtils.numericToInetAddress(mask);
                    int prelength  = computeprefixLength(gw);
                    Log.i(TAG,"prelength=" + prelength);
                    ifcg.addr = new LinkAddress(addr, prelength); 
                    ifcg.interfaceFlags = ifcg.interfaceFlags.replace("running", "");
                    ifcg.interfaceFlags = ifcg.interfaceFlags.replace("  "," ");
                    service.setInterfaceConfig(ETH0, ifcg);
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                Log.w(TAG, "setInterfaceConfig="+e);
                return false;
            }
    }

你可能感兴趣的:(IP地址)