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
|
class Sniffer{
public:
Sniffer():handle(NULL),cap_exp(""),net_if("any"),exp_compiled(false){}
~Sniffer(){
if(handle){
pcap_freecode(&filter_code);
}
if(exp_compiled){
pcap_close(handle);
}
}
string help(){
string h("avaliable net_interface:");
pcap_if_t* alldev=NULL;
if(0==pcap_findalldevs(&alldev, errbuf)){
for(pcap_if_t * dev =alldev;NULL!=dev;dev=dev->next){
h+=dev->name;
h+=" ";
}
pcap_freealldevs(alldev);
}
char * default_if=pcap_lookupdev(errbuf);
if(default_if){
h+=" default interface:";
h+=default_if;
}
return h;
}
string err(){
return pcap_geterr(handle);
}
bool configure(const string & net_interface,const string & exp){
if(net_interface!="")
net_if=net_interface;
cap_exp=exp;
if(0!=pcap_lookupnet(net_if.data(),&netp,&maskp,errbuf)){
return false;
}
handle=pcap_create(net_if.data(),errbuf);
if(NULL==handle){
return false;
}
if(0!=pcap_activate(handle)){
return false;
}
//ignore:?
//pcap_set_snaplen
//pcap_set_promisc
//pcap_set_rfmon
//pcap_set_timeout
//pcap_set_buffer_size
//pcap_set_tstamp_type
//only cap ethernet packet
if(DLT_EN10MB!=pcap_datalink(handle)){
return false;
}
if (0!=pcap_compile(handle, &filter_code, cap_exp.data(), 0, maskp)) {
return false;
}
exp_compiled=true;
if (0!=pcap_setfilter(handle, &filter_code)) {
return false;
}
}
bool loop(int pkg_num=-1){
typedef void (*pcap_handler)(u_char *user, const struct pcap_pkthdr *h,
const u_char *bytes);
pcap_loop(handle,pkg_num,&(Sniffer::pcap_callback),(u_char*)this);
}
static void pcap_callback(u_char *user, const struct pcap_pkthdr *h,
const u_char *bytes){
Sniffer * p_this=(Sniffer*) user;
p_this->dispatch(h,bytes);
}
private:
void dispatch(const struct pcap_pkthdr *h, const u_char *bytes){
got_packet(NULL,h,bytes);
}
private:
pcap_t *handle; // packet capture handle
string net_if; //e.g. "eth0"
string cap_exp; //e.g "tcp and dst port 80"
bool exp_compiled;
struct bpf_program filter_code; // compiled filter program (expression)
bpf_u_int32 netp;
bpf_u_int32 maskp;
char errbuf[PCAP_ERRBUF_SIZE];
};
|