libpcap 发表于 2020-04-05 | 分类于 网络安全 | 阅读数 简单使用 简单使用123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172#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);}