我有一个使用android shell命令获取子网掩码的方法。我在adb上测试过并可以工作;但是,我只是将其放在一个方法中,并且可以在android监视器控制台上显示输出。如果有更简单的方法,请提出建议。谢谢。顺便说一句,我在主要活动线程中运行此(没有Asynctask)

/*
    * method to return private subnet mask
    */
    public String getPrivateSubnet() {

        String output = "";
        final String SUBNET_CMD = "/system/bin/ifconfig wlan0 | find \"Mask\"";
        try {
            Process p = Runtime.getRuntime().exec(SUBNET_CMD);
//            p.wait();
            Log.v("SUBNET OUTPUT", p.toString());
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                Log.v("SUBNET", inputLine);
            }
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        Log.v("SUBNET", output);
        return output;
    }

最佳答案

如果您希望使用ifconfig,请使用:

ifconfig wlan0 |  awk '/netmask/{print $4}'


编辑:我对自己做了一些非常快速的编码才能找到这个。是的,Java API使您可以使用NetworkInterface类获取接口的ipv4子网掩码。我编写了一段代码,可能对您有帮助。此代码为您提供每个接口的CIDR值(例如:24将为255.255.255.0)。在此处查看更多信息:https://en.wikipedia.org/wiki/IPv4_subnetting_reference

import java.net.*;
import java.util.Enumeration;

public class Main {

        public static void main(String[] args) throws UnknownHostException, SocketException {

            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();

            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                try {
                    for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
                        System.out.println(address.getNetworkPrefixLength());
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }
        }
    }

关于java - 为什么这种方法没有给我android中的子网掩码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43211011/

10-11 20:25
查看更多