-
Notifications
You must be signed in to change notification settings - Fork 30
/
ArpPinger.cpp
923 lines (664 loc) · 20.1 KB
/
ArpPinger.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
#include "ArpPinger.h"
#include "Utils.h"
#include "ServiceScanner.h"
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <thread>
#include <ctime>
#include <chrono>
#if Windows
#include <pcap.h>
#elif Unix
#include <cstring>
#include <ifaddrs.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <net/ethernet.h>
// Linux
#ifdef AF_PACKET
#include <netpacket/packet.h>
#include <linux/filter.h>
#endif
// BSD
#ifdef AF_LINK
#include <fcntl.h>
#include <net/if_dl.h>
#include <net/bpf.h>
#define ETH_P_ARP 0x0806
#endif
#endif
using namespace std;
ArpPinger::ArpPinger()
: interfaces()
{
}
bool ArpPinger::GetOption(int option, void* value)
{
switch (option)
{
case OPT_TIMEOUT:
*reinterpret_cast<unsigned long*>(value) = timeout;
return true;
default:
return false;
}
}
bool ArpPinger::SetOption(int option, void* value)
{
switch (option)
{
case OPT_TIMEOUT:
timeout = *reinterpret_cast<unsigned long*>(value);
return true;
default:
return false;
}
}
bool ArpPinger::IsPassive()
{
return false;
}
ArpPinger::~ArpPinger()
{
if (interfaces.size() != 0)
{
for (auto& iface : interfaces)
{
delete iface;
}
}
}
void ArpPinger::Scan(Host* host)
{
prepareHost(host);
if (host->reason != AR_InProgress)
{
return;
}
unordered_map<unsigned int, Host*> hostmap = {
{ reinterpret_cast<ArpScanData*>(host->data)->ipaddr, host }
};
unordered_set<Interface*> ifaces = {
reinterpret_cast<ArpScanData*>(host->data)->iface
};
thread thd(&ArpPinger::sniffReplies, this, ifaces, hostmap);
sendRequest(host);
thd.join();
if (host->reason == AR_InProgress)
{
host->reason = AR_TimedOut;
}
}
void ArpPinger::Scan(Hosts* hosts)
{
unordered_map<unsigned int, Host*> hostmap;
unordered_set<Interface*> ifaces;
for (auto& host : *hosts)
{
prepareHost(host);
if (host->reason != AR_InProgress)
{
continue;
}
hostmap[reinterpret_cast<ArpScanData*>(host->data)->ipaddr] = host;
ifaces.emplace(reinterpret_cast<ArpScanData*>(host->data)->iface);
}
thread thd(&ArpPinger::sniffReplies, this, ifaces, hostmap);
for (auto host : *hosts)
{
if (host->reason != AR_InProgress)
{
continue;
}
sendRequest(host);
}
thd.join();
for (auto host : *hosts)
{
if (host->reason == AR_InProgress)
{
host->reason = AR_TimedOut;
}
}
}
void ArpPinger::loadInterfaces()
{
if (interfaces.size() != 0)
{
return;
}
log(DBG, "Fetching list of interfaces...");
#if Windows
// allocate 1 structure and call GetAdaptersInfo in order to get the number
// of interfaces to allocate for; this is the official way to do it...
auto ads = new IP_ADAPTER_INFO;
unsigned long adLen = sizeof(IP_ADAPTER_INFO);
if (GetAdaptersInfo(ads, &adLen) == ERROR_BUFFER_OVERFLOW)
{
delete ads;
ads = new IP_ADAPTER_INFO[adLen / sizeof(IP_ADAPTER_INFO) + 1];
// call again, this time with enough space
GetAdaptersInfo(ads, &adLen);
}
// iterate through interfaces
for (auto ad = ads; ad != nullptr; ad = ad->Next)
{
// skip over non-ethernet or non-point-to-point interfaces,
// and those which are not connected, or are otherwise
// in a state where they don't have IPv4 connectivity
if ((ad->Type != MIB_IF_TYPE_ETHERNET && ad->Type != MIB_IF_TYPE_PPP) || string(ad->IpAddressList.IpAddress.String) == "0.0.0.0")
{
continue;
}
// copy info, convert IP addresses stored as string
auto inf = new Interface();
inf->adapter = string(ad->AdapterName, MAX_ADAPTER_NAME_LENGTH + 4);
inf->description = string(ad->Description, MAX_ADAPTER_DESCRIPTION_LENGTH + 4);
memcpy(inf->macaddr, ad->Address, sizeof(inf->macaddr));
inet_pton(AF_INET, ad->IpAddressList.IpAddress.String, &inf->ipaddr);
inet_pton(AF_INET, ad->IpAddressList.IpMask.String, &inf->ipmask);
inet_pton(AF_INET, ad->GatewayList.IpAddress.String, &inf->ipgate);
interfaces.push_back(inf);
}
// clean-up
delete[] ads;
#elif Unix
// get the available interfaces
struct ifaddrs* ads;
getifaddrs(&ads);
// iterate through interfaces
unordered_map<string, tuple<int, unsigned char*>> macs;
for (auto ad = ads; ad != nullptr; ad = ad->ifa_next)
{
// check AF_PACKET/LINKs to save the interface numbers and MAC addresses for later
#ifdef AF_PACKET
// Linux
if (ad->ifa_addr != nullptr && ad->ifa_addr->sa_family == AF_PACKET)
{
auto sll = reinterpret_cast<struct sockaddr_ll*>(ad->ifa_addr);
macs[ad->ifa_name] = make_tuple(sll->sll_ifindex, sll->sll_addr);
continue;
}
#endif
#ifdef AF_LINK
// BSD
if (ad->ifa_addr != nullptr && ad->ifa_addr->sa_family == AF_LINK)
{
auto sdl = reinterpret_cast<struct sockaddr_dl*>(ad->ifa_addr);
macs[ad->ifa_name] = make_tuple(sdl->sdl_index, reinterpret_cast<unsigned char*>(sdl->sdl_data + sdl->sdl_nlen));
continue;
}
#endif
// skip loopback interfaces and those without IPv4 connectivity
if (ad->ifa_addr == nullptr || ad->ifa_addr->sa_family != AF_INET || (ad->ifa_flags & IFF_UP) != IFF_UP || (ad->ifa_flags & IFF_LOOPBACK) == IFF_LOOPBACK)
{
continue;
}
// copy info
auto inf = new Interface();
inf->adapter = string(ad->ifa_name);
inf->description = string(ad->ifa_name);
inf->ipaddr = (reinterpret_cast<struct sockaddr_in*>(ad->ifa_addr))->sin_addr.s_addr;
inf->ipmask = (reinterpret_cast<struct sockaddr_in*>(ad->ifa_netmask))->sin_addr.s_addr;
inf->ipgate = (reinterpret_cast<struct sockaddr_in*>(ad->
#ifdef AF_PACKET
ifa_ifu.ifu_broadaddr
#endif
#ifdef AF_LINK
ifa_broadaddr
#endif
))->sin_addr.s_addr;
// since only the broadcast address is specified, the gateway address
// should be determinable based on the netmask and broadcast address.
// this may not be entirely accurate, but enough for our purposes.
inf->ipgate = htonl(ntohl(inf->ipgate) & ntohl(inf->ipmask));
interfaces.push_back(inf);
}
// copy over temporarily stored interface numbers and MAC addresses
for (auto& inf : interfaces)
{
auto it = macs.find(inf->adapter);
if (it != macs.end())
{
auto tpl = (*it).second;
inf->ifnum = get<0>(tpl);
memcpy(inf->macaddr, get<1>(tpl), sizeof(inf->macaddr));
}
}
// clean-up
freeifaddrs(ads);
#endif
log(DBG, "Found " + to_string(interfaces.size()) + " interfaces.");
}
bool ArpPinger::isIpOnIface(unsigned int ip, Interface* inf)
{
// convert to host byte order
unsigned int iph = ntohl(ip);
unsigned int msk = ntohl(inf->ipmask);
unsigned int net = ntohl(inf->ipgate == 0 ? inf->ipaddr : inf->ipgate);
// do the range check
unsigned int low = net & msk;
unsigned int high = low | ~msk;
return iph >= low && iph <= high;
}
void ArpPinger::prepareHost(Host* host)
{
// get interfaces
if (interfaces.size() == 0)
{
loadInterfaces();
}
// parse address
unsigned int addr;
inet_pton(AF_INET, host->address.c_str(), &addr);
// check which interfaces' range is this address in
Interface* iface = nullptr;
for (auto& inf : interfaces)
{
if (isIpOnIface(addr, inf))
{
iface = inf;
break;
}
}
if (iface == nullptr)
{
host->reason = AR_ScanFailed;
log(VRB, "Host '" + host->address + "' is not local to any of the interfaces.");
return;
}
log(DBG, "Host '" + host->address + "' is local to '" + iface->adapter + "'.");
auto data = new ArpScanData();
host->data = data;
data->ipaddr = addr;
data->iface = iface;
host->reason = AR_InProgress;
}
void ArpPinger::sendRequest(Host* host)
{
if (host->reason != AR_InProgress || host->data == nullptr)
{
return;
}
auto data = reinterpret_cast<ArpScanData*>(host->data);
log(DBG, "Sending payload to arp://" + host->address + "...");
#if Windows
// open winpcap to the found interface
pcap_t *pcap;
char errbuf[PCAP_ERRBUF_SIZE];
if ((pcap = pcap_open(string("rpcap://\\Device\\NPF_" + data->iface->adapter).c_str(), 100, PCAP_OPENFLAG_PROMISCUOUS, 10, NULL, errbuf)) == NULL)
{
host->reason = AR_ScanFailed;
log(ERR, "Failed to open PCAP device: " + data->iface->adapter);
delete data;
return;
}
#elif Linux
// prepare the structures pointing to the interface
struct sockaddr_ll dev;
memset(&dev, 0, sizeof(dev));
dev.sll_ifindex = data->iface->ifnum;
dev.sll_family = AF_PACKET;
dev.sll_halen = 6;
memcpy(dev.sll_addr, data->iface->macaddr, dev.sll_halen);
// create raw socket
auto sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (sock < 0)
{
// root is required for raw sockets
host->reason = AR_ScanFailed;
log(ERR, "Failed to open socket with PF_PACKET/SOCK_RAW: " + getNetErrStr());
delete data;
return;
}
// set it to non-blocking
unsigned long mode = 1;
ioctl(sock, FIONBIO, &mode);
#elif BSD
// find and open the next available Berkeley Packet Filter device
int bpf = 0;
for (int i = 0; i < 1000; i++)
{
bpf = open(("/dev/bpf" + to_string(i)).c_str(), O_RDWR);
if (bpf != -1)
{
break;
}
}
if (bpf < 0)
{
host->reason = AR_ScanFailed;
log(ERR, "Failed to allocate a BPF device.");
delete data;
return;
}
// bind device to the desired interface
struct ifreq bif;
strcpy(bif.ifr_name, data->iface->adapter.c_str());
if (ioctl(bpf, BIOCSETIF, &bif) > 0)
{
host->reason = AR_ScanFailed;
log(ERR, "Failed to bind BPF device to interface '" + data->iface->adapter + "': " + getNetErrStr());
close(bpf);
delete data;
return;
}
#endif
// construct the payload
auto pktLen = max(int(sizeof(EthHeader) + sizeof(ArpHeader)), 60);
auto pkt = new char[pktLen];
memset(pkt, 0, pktLen);
// first the ethernet frame
auto ethPkt = reinterpret_cast<EthHeader*>(pkt);
ethPkt->typ = htons(0x0806); // ARP
memset(ethPkt->dst, 0xFF, sizeof(ethPkt->dst)); // FF:FF:FF:FF:FF:FF is broadcast
memcpy(ethPkt->src, data->iface->macaddr, sizeof(ethPkt->src));
// then the ARP request
auto arpPkt = reinterpret_cast<ArpHeader*>(pkt + sizeof(*ethPkt));
arpPkt->htype = htons(1); // Ethernet
arpPkt->ptype = htons(0x0800); // IP
arpPkt->hlen = 6; // MAC address is 6 bytes
arpPkt->plen = 4; // IP address is 4 bytes
arpPkt->opcode = htons(ARP_OP_REQUEST); // request info
memcpy(arpPkt->srcmac, data->iface->macaddr, sizeof(arpPkt->srcmac));
memcpy(arpPkt->srcip, &data->iface->ipaddr, sizeof(arpPkt->srcip));
memset(arpPkt->dstmac, 0xFF, sizeof(arpPkt->dstmac));
memcpy(arpPkt->dstip, &data->ipaddr, sizeof(arpPkt->dstip));
// send the packet, then clean-up
host->date = chrono::system_clock::now();
#if Windows
auto res = pcap_sendpacket(pcap, reinterpret_cast<const unsigned char*>(pkt), pktLen);
if (res != 0)
{
host->reason = AR_ScanFailed;
log(ERR, "Failed to send packet through PCAP: " + string(pcap_geterr(pcap)));
}
pcap_close(pcap);
#elif Linux
auto res = sendto(sock, pkt, pktLen, 0, reinterpret_cast<struct sockaddr*>(&dev), sizeof(dev));
if (res <= 0)
{
host->reason = AR_ScanFailed;
log(ERR, "Failed to send packet through socket: " + getNetErrStr());
}
close(sock);
#elif BSD
auto res = write(bpf, pkt, pktLen);
if (res <= 0)
{
host->reason = AR_ScanFailed;
log(ERR, "Failed to send packet through BPF: " + getNetErrStr());
}
close(bpf);
#endif
delete[] pkt;
delete data;
}
void ArpPinger::sniffReplies(unordered_set<Interface*> ifaces, unordered_map<unsigned int, Host*> hosts)
{
if (ifaces.size() == 0 || hosts.size() == 0)
{
return;
}
#if Windows
// iterate through the interfaces and setup a winpcap for all of them
vector<pcap_t*> pcaps;
for (auto& iface : ifaces)
{
// open winpcap to the interface
pcap_t *pcap;
char errbuf[PCAP_ERRBUF_SIZE];
if ((pcap = pcap_open(string("rpcap://\\Device\\NPF_" + iface->adapter).c_str(), 60, PCAP_OPENFLAG_PROMISCUOUS, 10, NULL, errbuf)) == NULL)
{
log(ERR, "Failed to open PCAP for interface '" + iface->adapter + "': " + string(pcap_geterr(pcap)));
continue;
}
// compile the code to filter packets
struct bpf_program bfcode;
if (pcap_compile(pcap, &bfcode, "arp", 1, iface->ipmask) < 0)
{
log(ERR, "Failed to compile filter for PCAP for interface '" + iface->adapter + "': " + string(pcap_geterr(pcap)));
continue;
}
// attach compiled code to instance
if (pcap_setfilter(pcap, &bfcode) < 0)
{
log(ERR, "Failed to attach filter to PCAP for interface '" + iface->adapter + "': " + string(pcap_geterr(pcap)));
continue;
}
pcaps.push_back(pcap);
}
if (pcaps.size() == 0)
{
log(ERR, "Failed to open any PCAP devices.");
return;
}
// iterate through the received packets on all interfaces until timeout
auto res = 0;
struct pcap_pkthdr* header;
const unsigned char* data;
auto start = chrono::steady_clock::now();
while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start).count() < static_cast<long long>(timeout))
{
for (auto& pcap : pcaps)
{
// capture packet from interface
res = pcap_next_ex(pcap, &header, &data);
// check if a valid packet has been captured
if (res <= 0 || header->caplen < sizeof(EthHeader) + sizeof(ArpHeader))
{
continue;
}
// skip ethernet frame and parse ARP packet
auto arpPkt = reinterpret_cast<ArpHeader*>(const_cast<unsigned char*>(data) + sizeof(EthHeader));
if (ntohs(arpPkt->opcode) != ARP_OP_REPLY)
{
continue;
}
// when reply packet is found, mark its host object as alive
auto it = hosts.find(*reinterpret_cast<unsigned int*>(&arpPkt->srcip));
if (it != hosts.end())
{
auto serv = (*it).second;
serv->alive = true;
serv->reason = AR_ReplyReceived;
log(DBG, "Got reply from arp://" + serv->address + "...");
}
}
}
// clean-up
for (auto& pcap : pcaps)
{
pcap_close(pcap);
}
#elif Linux
// open universal listening socket
int sock;
if ((sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) == -1)
{
log(ERR, "Failed to open socket with AF_PACKET/SOCK_RAW/ETH_P_ALL: " + getNetErrStr());
return;
}
// set it to non-blocking
unsigned long mode = 1;
ioctl(sock, FIONBIO, &mode);
// attach filter code to instance
auto bfcode = new struct sock_filter[4];
bfcode[0] = // ldh [12] ; skip 12 bytes
BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 12);
bfcode[1] = // jeq #0x806 jt 2 jf 3 ; if Eth type is ARP goto 2 else 3
BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ETH_P_ARP, 0, 1);
bfcode[2] = // ret #262144 ; return packet [when ARP]
BPF_STMT(BPF_RET + BPF_K, sizeof(struct EthHeader) + sizeof(struct ArpHeader));
bfcode[3] = // ret #0 ; return null
BPF_STMT(BPF_RET + BPF_K, 0);
struct sock_fprog bfprog;
bfprog.filter = bfcode;
bfprog.len = 4;
if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &bfprog, sizeof(bfprog)) == -1)
{
close(sock);
delete[] bfcode;
log(ERR, "Failed to compile and attach filter to socket: " + getNetErrStr());
return;
}
// iterate through the received packets on all interfaces until timeout
auto res = 0;
auto data = new unsigned char[60];
auto start = chrono::steady_clock::now();
while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start).count() < static_cast<long long>(timeout))
{
// capture packet from interface
res = recv(sock, data, 60, 0);
// check if a valid packet has been captured
if (res < int(sizeof(struct EthHeader) + sizeof(struct ArpHeader)))
{
continue;
}
// skip ethernet frame and parse ARP packet
auto arpPkt = reinterpret_cast<struct ArpHeader*>(data + sizeof(struct EthHeader));
if (ntohs(arpPkt->opcode) != ARP_OP_REPLY)
{
continue;
}
// when reply packet is found, mark its host object as alive
auto it = hosts.find(*reinterpret_cast<unsigned int*>(&arpPkt->srcip));
if (it != hosts.end())
{
auto serv = (*it).second;
serv->alive = true;
serv->reason = AR_ReplyReceived;
log(DBG, "Got reply from arp://" + serv->address + "...");
}
}
// clean-up
close(sock);
delete[] data;
delete[] bfcode;
#elif BSD
// set up filter code for bpf
// [see linux one above for comments]
auto bfcode = new struct bpf_insn[4];
bfcode[0] = BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 12);
bfcode[1] = BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ETH_P_ARP, 0, 1);
bfcode[2] = BPF_STMT(BPF_RET + BPF_K, sizeof(struct EthHeader) + sizeof(struct ArpHeader));
bfcode[3] = BPF_STMT(BPF_RET + BPF_K, 0);
// iterate through the interfaces and setup a bpf for all of them
vector<int> bpfs;
for (auto& iface : ifaces)
{
// find and open the next available Berkeley Packet Filter device
int bpf = 0;
for (int i = 0; i < 1000; i++)
{
bpf = open(("/dev/bpf" + to_string(i)).c_str(), O_RDWR);
if (bpf != -1)
{
break;
}
}
if (bpf < 0)
{
log(ERR, "Failed to allocate a BPF device for interface '" + iface->adapter + "'.");
continue;
}
// bind device to the desired interface
struct ifreq bif;
strcpy(bif.ifr_name, iface->adapter.c_str());
if (ioctl(bpf, BIOCSETIF, &bif) > 0)
{
close(bpf);
log(ERR, "Failed to bind BPF device to interface '" + iface->adapter + "': " + getNetErrStr());
continue;
}
// enable immediate return mode
int en = 1;
ioctl(bpf, BIOCIMMEDIATE, &en);
// set it to non-blocking
unsigned long mode = 1;
ioctl(bpf, FIONBIO, &mode);
// attach filter code to instance
struct bpf_program bfprog;
bfprog.bf_insns = bfcode;
bfprog.bf_len = 4;
if (ioctl(bpf, BIOCSETF, &bfprog) < 0)
{
close(bpf);
log(ERR, "Failed to compile and attach filter to BPF device for interface '" + iface->adapter + "': " + getNetErrStr());
continue;
}
bpfs.push_back(bpf);
}
if (bpfs.size() == 0)
{
delete[] bfcode;
log(ERR, "Failed to open any BPF devices.");
return;
}
// iterate through the received packets on all interfaces until timeout
auto res = 0;
auto start = chrono::steady_clock::now();
while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start).count() < static_cast<long long>(timeout))
{
for (auto& bpf : bpfs)
{
// request buffer length
int blen = 1;
if (ioctl(bpf, BIOCGBLEN, &blen) == -1)
{
continue;
}
// allocate buffer and capture packets
auto data = new unsigned char[blen];
res = read(bpf, data, blen);
// check if read was successful
if (res <= 0)
{
delete[] data;
continue;
}
// iterate through captured packets
auto pkt = reinterpret_cast<unsigned char*>(data);
while (pkt < data + res)
{
// extract packet
auto bh = reinterpret_cast<struct bpf_hdr*>(pkt);
// check if a valid packet has been captured
if (bh->bh_caplen < int(sizeof(struct EthHeader) + sizeof(struct ArpHeader)))
{
pkt += BPF_WORDALIGN(bh->bh_hdrlen + bh->bh_caplen);
continue;
}
// skip ethernet frame and parse ARP packet
auto arpPkt = reinterpret_cast<struct ArpHeader*>(pkt + bh->bh_hdrlen + sizeof(struct EthHeader));
if (ntohs(arpPkt->opcode) != ARP_OP_REPLY)
{
pkt += BPF_WORDALIGN(bh->bh_hdrlen + bh->bh_caplen);
continue;
}
// when reply packet is found, mark its host object as alive
auto it = hosts.find(*reinterpret_cast<unsigned int*>(&arpPkt->srcip));
if (it != hosts.end())
{
auto serv = (*it).second;
serv->alive = true;
serv->reason = AR_ReplyReceived;
log(DBG, "Got reply from arp://" + serv->address + "...");
}
// advance to next packet
pkt += BPF_WORDALIGN(bh->bh_hdrlen + bh->bh_caplen);
}
delete[] data;
}
}
// clean-up
for (auto& bpf : bpfs)
{
close(bpf);
}
delete[] bfcode;
#endif
}