为什么这个方法不给我android中的子网掩码

时间:2017-04-04 15:06:42

标签: java android subnet

我有一个使用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;
    }

1 个答案:

答案 0 :(得分:1)

如果您希望使用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();
                }
            }
        }
    }