我最近正在开发一个需要访问ARP表的Android项目。其中一个要求是避免任何需要root设备的方法。所以,我的问题是:有没有办法在没有root设备的情况下访问android中的ARP表?
目前我发现大多数方法都使用/ proc / net / arp进行ARP表访问,这需要root权限,我不确定这是否是唯一的方法。
我可以访问没有root的ARP表。这是我的代码:
string GetMACAddressviaIP(string ipAddr)
{
string result = "";
ostringstream ss;
ss << "/proc/net/arp";
string loc = ss.str();
ifstream in(loc);
if(!in)
{
printf("open %s failed\n",loc.c_str());
return result;
}
string line;
while(getline(in, line)){
if(strstr(line.c_str(), ipAddr.c_str()))
{
const char *buf = strstr(line.c_str(), ":") - 2;
int counter = 0;
stringstream ss;
while(counter < 17)
{
ss << buf[counter];
counter++;
}
result = ss.str();
}
}
return result;
}
为了更好地理解,使用Java语言,您可以在android中检索ARP表:
BufferedReader br = null;
ArrayList<ClientScanResult> result = new ArrayList<ClientScanResult>();
try {
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}Catch(Exception e){
}finally {
try {
br.close();
} catch (IOException e) {
}
}
对于Java,我建议使用以下内容。这结合了其他两个的答案。它没有经过测试,所以可能需要一些调整,但你明白了。
public String getMacAddressForIp(final String ipAddress) {
try (BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"))) {
String line;
while ((line = br.readLine()) != null) {
if (line.contains(ipAddress)) {
final int macStartIndex = line.indexOf(":") - 2;
final int macEndPos = macStartIndex + 17;
if (macStartIndex >= 0 && macEndPos < line.length()) {
return line.substring(macStartIndex, macEndPos);
} else {
Log.w("MyClass", "Found ip address line, but mac address was invalid.");
}
}
}
} catch(Exception e){
Log.e("MyClass", "Exception reading the arp table.", e);
}
return null;
}