安卓ARP表-开发问题

5

我正在编写一个安卓应用程序,遇到两个问题。

我从/proc/net/arp读取本地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);
    }
  1. 第一个问题:

    我也在使用广播接收器。当我的应用程序接收到状态WifiManager.NETWORK_STATE_CHANGED_ACTION时,我会检查是否已经建立了与网关的连接。如果是,则调用我的函数读取arp表。但此时系统尚未建立arp表。有时当我接收到连接状态时,arp表仍为空。

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

  2. 第二个问题:

    我想以持久化的方式保存网关的IP和MAC地址。现在我正在使用共享首选项来实现这一点。也许将其写入内部存储器会更好?

    有什么提示吗?


第二个问题。使用sqlite数据库。当应用程序更新时,SharedPreferences可能会被清除。因此最好将值放入sqlite中。 - kumar
@kumar,除非像http://b.android.com/2066这样的错误,否则SharedPreferences不应该被清除- https://dev59.com/vW865IYBdhLWcg3wWtKz - zapl
所以使用SharedPreferences应该是可以的。 - IcedEarth
1个回答

2

对于第一个问题,您可以启动一个新线程,在睡眠一段时间或者直到有一些条目之后再运行该方法(使用带有邮箱的Runnable来获取Map)- 除非您需要直接使用Map,否则我认为唯一的方法是等待这些条目。例如(如果您需要直接使用Map):

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);
}

谢谢Pescis。我会测试这个! - IcedEarth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接