libpcap

简单使用

简单使用

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
#include <iostream>
#include "pcap.h"
#include "time.h"
#include <sstream>
#include <iomanip>
#include "string.h"
using namespace std;
void callback(u_char *arg,const struct pcap_pkthdr *pkthdr,const u_char * packet){
int *id=(int *)arg;
cout<<"id:";cout<<dec<<++(*id);cout<<endl;
cout<<"Packet length:";cout<<dec<<pkthdr->len;cout<<endl;
cout<<"Number of bytes:";cout<<dec<<pkthdr->caplen;cout<<endl;
cout<<"Recieved time:";cout<<ctime((const time_t *)&pkthdr->ts.tv_sec);cout<<endl;
//print packet
int i;
for(i=0; i<pkthdr->len; ++i) {
//printf(" %02x", packet[i]);
cout<<hex<<setw(2)<<setfill('0')<<(int)packet[i];
cout<<" ";
if( (i + 1) % 16 == 0 )
cout<<endl;
}
cout<<endl;
cout<<endl;
}
void capture_packet(pcap_t *handle){
struct pcap_pkthdr packet;
int id = 0;
//capture the packet
pcap_loop(handle,-1,callback,(u_char*)&id);
}
int main(){
//setting the device
char *dev,errbuf[PCAP_ERRBUF_SIZE];//store the error message
dev=pcap_lookupdev(errbuf);//look the default device
if(dev==NULL){
cout<<"Couldn't find default device!"<<endl;
cout<<errbuf<<endl;
}else{
cout<<"dev:"<<dev<<endl;
}
//openning the device for sniffing
pcap_t *handle;
handle=pcap_open_live(dev,BUFSIZ,1,1000,errbuf);
if(handle==NULL){
cout<<"Couldn't open device!"<<endl;
cout<<errbuf<<endl;
}//need the sudo
struct bpf_program filter;//The compiled filter expression
char filter_app[1000];//The filter expression
cout<<"Please input the regulation of filter:"<<endl;
cin.getline(filter_app,1000);
bpf_u_int32 mask;//the netmask of our sniffing device
bpf_u_int32 net;//the ip of our sniffing device
struct pcap_pkthdr header;//the general information about the packet
const u_char *packet;
if(pcap_lookupnet(dev,&net,&mask,errbuf)==-1){
cout<<"Couldn't get netmask for device:"<<dev<<endl;
net=0;
mask=0;
}
if(pcap_compile(handle,&filter,filter_app,0,net)==-1){
cout<<"Couldn't parse filter "<<filter_app<<":"<<pcap_geterr(handle)<<endl;
}
if(pcap_setfilter(handle,&filter)==-1){
cout<<"Couldn't install filter "<<filter_app<<":"<<pcap_geterr(handle)<<endl;
}
//packet=pcap_next(handle,&header);
//cout<<header.length;
capture_packet(handle);
pcap_close(handle);
}