我正在编写的 Android 应用程序有两个问题。
我正在从 /proc/net/arp
中读取本地 arp 表,并将 ip 和相应的 mac 地址保存在 HashMap 中。看我的功能。它工作正常。
/**
* 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);
}
第一个问题:
我也在使用广播接收器。当我的应用收到状态
WifiManager.NETWORK_STATE_CHANGED_ACTION
时,我检查是否已建立与网关的连接。如果为真,我将调用我的函数来读取 arp 表。但是这个阶段系统还没有建立arp表。有时当我收到连接状态时,arp 表仍然是空的。有人有解决这个问题的想法吗?
第二个问题:
我想持久化保存网关的ip和mac地址。现在我正在使用 Shared Preferences为了这。也许写入内部存储更好?
有什么建议吗?
最佳答案
对于第一个问题,您可以启动一个新线程,该线程在 hibernate 一段时间后运行该方法或直到它有一些条目(制作一个带有邮箱的 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);
}
关于java - Android arp表——开发问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13646625/