6
6
import java .net .InetAddress ;
7
7
import java .net .UnknownHostException ;
8
8
import java .util .ArrayList ;
9
+ import java .util .HashMap ;
9
10
import java .util .List ;
10
11
import java .util .concurrent .ExecutorService ;
11
12
import java .util .concurrent .Executors ;
@@ -22,6 +23,7 @@ public class SubnetDevices {
22
23
private OnSubnetDeviceFound listener ;
23
24
private int timeOutMillis = 2500 ;
24
25
private boolean cancelled = false ;
26
+ private HashMap <String , String > ipMacHashMap = null ;
25
27
26
28
// This class is not to be instantiated
27
29
private SubnetDevices () {
@@ -73,7 +75,7 @@ public static SubnetDevices fromIPAddress(final String ipAddress) {
73
75
74
76
subnetDevice .addresses = new ArrayList <>();
75
77
76
- // Get addresses from ARP Info first as they are likely to be pingable
78
+ // Get addresses from ARP Info first as they are likely to be reachable
77
79
subnetDevice .addresses .addAll (ARPInfo .getAllIPAddressesInARPCache ());
78
80
79
81
// Add all missing addresses in subnet
@@ -159,6 +161,10 @@ public SubnetDevices findDevices(final OnSubnetDeviceFound listener) {
159
161
@ Override
160
162
public void run () {
161
163
164
+ // Load mac addresses into cache var (to avoid hammering the /proc/net/arp file when
165
+ // lots of devices are found on the network.
166
+ ipMacHashMap = ARPInfo .getAllIPAndMACAddressesInARPCache ();
167
+
162
168
ExecutorService executor = Executors .newFixedThreadPool (noThreads );
163
169
164
170
for (final String add : addresses ) {
@@ -176,6 +182,17 @@ public void run() {
176
182
e .printStackTrace ();
177
183
}
178
184
185
+ // Loop over devices found and add in the MAC addresses if missing.
186
+ // We do this after scanning for all devices as /proc/net/arp may add info
187
+ // because of the scan.
188
+ ipMacHashMap = ARPInfo .getAllIPAndMACAddressesInARPCache ();
189
+ for (Device device : devicesFound ) {
190
+ if (device .mac == null && ipMacHashMap .containsKey (device .ip )) {
191
+ device .mac = ipMacHashMap .get (device .ip );
192
+ }
193
+ }
194
+
195
+
179
196
listener .onFinished (devicesFound );
180
197
181
198
}
@@ -206,7 +223,12 @@ public void run() {
206
223
PingResult pingResult = Ping .onAddress (ia ).setTimeOutMillis (timeOutMillis ).doPing ();
207
224
if (pingResult .isReachable ) {
208
225
Device device = new Device (ia );
209
- device .mac = ARPInfo .getMACFromIPAddress (ia .getHostAddress ());
226
+
227
+ // Add the device MAC address if it is in the cache
228
+ if (ipMacHashMap .containsKey (ia .getHostAddress ())) {
229
+ device .mac = ipMacHashMap .get (ia .getHostAddress ());
230
+ }
231
+
210
232
device .time = pingResult .timeTaken ;
211
233
subnetDeviceFound (device );
212
234
}
0 commit comments