Skip to content

Commit

Permalink
Added arp cache in SubnetDevices to prevent repeated file reads
Browse files Browse the repository at this point in the history
  • Loading branch information
stealthcopter committed Aug 14, 2018
1 parent 24a7788 commit 67732b5
Showing 1 changed file with 24 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
Expand All @@ -22,6 +23,7 @@ public class SubnetDevices {
private OnSubnetDeviceFound listener;
private int timeOutMillis = 2500;
private boolean cancelled = false;
private HashMap<String, String> ipMacHashMap = null;

// This class is not to be instantiated
private SubnetDevices() {
Expand Down Expand Up @@ -73,7 +75,7 @@ public static SubnetDevices fromIPAddress(final String ipAddress) {

subnetDevice.addresses = new ArrayList<>();

// Get addresses from ARP Info first as they are likely to be pingable
// Get addresses from ARP Info first as they are likely to be reachable
subnetDevice.addresses.addAll(ARPInfo.getAllIPAddressesInARPCache());

// Add all missing addresses in subnet
Expand Down Expand Up @@ -159,6 +161,10 @@ public SubnetDevices findDevices(final OnSubnetDeviceFound listener) {
@Override
public void run() {

// Load mac addresses into cache var (to avoid hammering the /proc/net/arp file when
// lots of devices are found on the network.
ipMacHashMap = ARPInfo.getAllIPAndMACAddressesInARPCache();

ExecutorService executor = Executors.newFixedThreadPool(noThreads);

for (final String add : addresses) {
Expand All @@ -176,6 +182,17 @@ public void run() {
e.printStackTrace();
}

// Loop over devices found and add in the MAC addresses if missing.
// We do this after scanning for all devices as /proc/net/arp may add info
// because of the scan.
ipMacHashMap = ARPInfo.getAllIPAndMACAddressesInARPCache();
for (Device device : devicesFound) {
if (device.mac == null && ipMacHashMap.containsKey(device.ip)) {
device.mac = ipMacHashMap.get(device.ip);
}
}


listener.onFinished(devicesFound);

}
Expand Down Expand Up @@ -206,7 +223,12 @@ public void run() {
PingResult pingResult = Ping.onAddress(ia).setTimeOutMillis(timeOutMillis).doPing();
if (pingResult.isReachable) {
Device device = new Device(ia);
device.mac = ARPInfo.getMACFromIPAddress(ia.getHostAddress());

// Add the device MAC address if it is in the cache
if (ipMacHashMap.containsKey(ia.getHostAddress())) {
device.mac = ipMacHashMap.get(ia.getHostAddress());
}

device.time = pingResult.timeTaken;
subnetDeviceFound(device);
}
Expand Down

0 comments on commit 67732b5

Please sign in to comment.