1: #include"pcap.h"
2: //每次捕获到数据包时,libpcap都会自动调用这个回调函数
3: void packet_handler(u_char *param,const pcap_pkthdr*header,const u_char *ptk_data){
4:
5: char timestr[16];
6: //将时间戳转换成可识别的格式
7: time_t local_tv_sec=header->ts.tv_sec;
8: tm *ltime=localtime(&local_tv_sec);
9: //strftime(timestr,sizeof(timestr),"%H:%M:%S",ltime);
10: strftime( timestr, sizeof timestr, "%H:%M:%S", ltime);
11: printf("%s,%.6d len:%d ",timestr,header->ts.tv_usec,header->len);
12: }
13: int main(){
14: pcap_if_t *alldevs;
15: pcap_t *adhandle;
16: char errbuf[PCAP_ERRBUF_SIZE];
17:
18: if(pcap_findalldevs_ex(PCAP_SRC_IF_STRING,NULL,&alldevs,errbuf)==-1){
19: fprintf(stderr,"Error in pcap_findalldevs: %s ",errbuf);
20: exit(1);
21: }
22:
23: //print device list
24: int count=1;
25: for(pcap_if_t *d=alldevs;d!=NULL;d=d->next){
26: printf("%d. %s",count++,d->name);
27: printf("(%s) ",d->description);
28: }
29: if(count==1) {
30: printf("No interface found! Make sure WinPcap is isntalled ");
31: return -1;
32: }
33: int num;
34: printf("Enter the interface number:(1-%d): ",count);
35: scanf("%d",&num);
36: if(num<1||num>count){
37: printf("Out Of Range ");
38: pcap_freealldevs(alldevs);
39: return -1;
40: }
41: pcap_if_t *d=alldevs;
42: // 跳转到选中的适配器
43: for(int i=0;i<num;i++,d=d->next){
44: // 设备名
45: // 65535保证能捕获到不同数据链路层上的每个数据包的全部内容
46: // 混杂模式
47: // 读取超时时间
48: // 远程机器验证
49: // 错误缓冲池
50: adhandle=pcap_open(d->name,65536,PCAP_OPENFLAG_PROMISCUOUS,1000,NULL,errbuf);
51: if(adhandle==NULL){
52: fprintf(stderr,"Unable to open the adapter %s",d->name);
53: return -1;
54: }
55: printf("Listening on %s... ",d->description);
56:
57: pcap_freealldevs(alldevs);
58: //开始捕获
59: pcap_loop(adhandle,0,packet_handler,NULL);
60:
61: }
62: }
试验结果: