Android arp表——开发题

Ice*_*rth 5 java android

我正在编写的 android 应用程序有两个问题。

我正在读取本地 arp 表/proc/net/arp,并将 ip 和相应的 mac 地址保存在哈希映射中。看我的功能。它工作正常。

    /**
     * Extract and save ip and corresponding MAC address from arp table in HashMap
     */
    public Map<String, String> createArpMap() throws IOException {      
        checkMapARP.clear();
        BufferedReader localBufferdReader = new BufferedReader(new FileReader(new File("/proc/net/arp")));
        String line = "";       

        while ((line = localBufferdReader.readLine()) != null) {            
            String[] ipmac = line.split("[ ]+");
            if (!ipmac[0].matches("IP")) {
                String ip = ipmac[0];
                String mac = ipmac[3];
                if (!checkMapARP.containsKey(ip)) {
                    checkMapARP.put(ip, mac);               
                }                   
            }
        }
        return Collections.unmodifiableMap(checkMapARP);
    }
Run Code Online (Sandbox Code Playgroud)
  1. 第一个问题:

    我也在使用广播接收器。当我的应用程序收到状态时,WifiManager.NETWORK_STATE_CHANGED_ACTION我检查是否建立了与网关的连接。如果为真,我将调用我的函数来读取 arp 表。但是在这个阶段系统还没有建立arp表。有时当我收到连接状态时,arp 表还是空的。

    有人有解决这个问题的想法吗?

  2. 第二个问题:

    我想以持久的方式保存网关的ip和mac地址。现在我正在为此使用共享首选项。也许写入内部存储更好?

    有小费吗?

ddm*_*mps 2

对于第一个问题,您可以启动一个新线程,在休眠一定时间后或直到它有一些条目(使用Runnable邮箱创建一个来获取地图)后运行该方法 - 除非您需要直接使用地图,然后我认为唯一的办法就是等待参赛。例如(如果需要直接使用地图):

public Map<String, String> createArpMap() throws IOException {      
    checkMapARP.clear();
    BufferedReader localBufferdReader = new BufferedReader(new FileReader(new File("/proc/net/arp")));
    String line = "";       
    while ((line = localBufferdReader.readLine()) == null) {
        localBufferdReader.close();
        Thread.sleep(1000);
        localBufferdReader = new BufferedReader(new FileReader(new File("/proc/net/arp")));
    }
    do {            
        String[] ipmac = line.split("[ ]+");
        if (!ipmac[0].matches("IP")) {
            String ip = ipmac[0];
            String mac = ipmac[3];
            if (!checkMapARP.containsKey(ip)) {
                checkMapARP.put(ip, mac);               
            }                   
        }
    } while ((line = localBufferdReader.readLine()) != null);
    return Collections.unmodifiableMap(checkMapARP);
}
Run Code Online (Sandbox Code Playgroud)