I have a situation when my phone is working as a hotspot and I need to detect all devices which connected to my phone and find their MAC addresses. I wrote something like this:
public void getListOfConnectedDevice() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
BufferedReader br = null;
boolean isFirstLine = true;
try {
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
if (isFirstLine) {
isFirstLine = false;
continue;
}
String[] splitted = line.split(" +");
if (splitted != null && splitted.length >= 4) {
String ipAddress = splitted[0];
String macAddress = splitted[3];
boolean isReachable = InetAddress.getByName(
splitted[0]).isReachable(300);// this is network call so we cant do that on UI thread, so I take background thread.
Log.d(TAG, "ip: " + splitted[0]);
Log.d(TAG, "isReachable: " + isReachable);
if (isReachable) {
Log.d("Device Information", ipAddress + " : "
+ macAddress);
macAddresses.add(macAddress); //My List<String>
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
But boolean isReachable = InetAddress.getByName(splitted[0]).isReachable(300);
returns only false if device connected or disconnected. And I can't find any info to find solution. Or are there any other solutions? (For not rooted phones).
Well, i found that android keep MAC addreses of devices for about 10 min (On different devices - different time), and only way - use ADB shell command to clear that list, BUT! it works only on rooted devices.
But this code can help you (works not with all devices):
public void getListOfConnectedDevice() {
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
macAddresses.clear();
BufferedReader br = null;
boolean isFirstLine = true;
try {
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
if (isFirstLine) {
isFirstLine = false;
continue;
}
String[] splitted = line.split(" +");
if (splitted != null && splitted.length >= 4) {
String ipAddress = splitted[0];
String macAddress = splitted[3];
Node node = new Node(ipAddress, macAddress);
boolean isReachable = node.isReachable;
Log.d(TAG, "isReachable: " + isReachable);
if (isReachable) {
Log.d("Device Information", ipAddress + " : "
+ macAddress);
macAddresses.add(macAddress);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}