简单的抓包程序,演示程序(抓取特定的ARP包)
编程环境:Winpcap VS2008
代码:
#include "stdafx.h"
#include "pcap.h"
#define LINE_LEN 16
#define Number 10
#pragma comment(lib,"wpcap.lib")
int _tmain(int argc, _TCHAR* argv[])
{
pcap_if_t *alldevs,*d;
pcap_t *fp;
struct bpf_program fcode;
u_int inum,i = 0;
char errbuf[PCAP_ERRBUF_SIZE];
int res;
struct pcap_pkthdr *header;
const u_char *pkt_data;
int temp = 0;
u_int netmask;
if(pcap_findalldevs(&alldevs,errbuf) == -1){
printf("Error in found dev");
system("pause");
return -1;
}
//print the list
for(d = alldevs;d ; d= d->next){
printf("%d.%s",++i,d->name);
if(d->description){
printf("(%s)\nt",d->description);
}
else{
printf("No description available\n");
}
}
if(i == 0){
printf("\n No interface found! Make sure WinPcap is installed.\n");
return -1;
}
printf("Enter the interface number(1-%d):",i);
scanf_s("%d",&inum);
if(inum <1 || inum >i){
printf("\ninterface number out o range.\n");
pcap_freealldevs(alldevs);
return -1;
}
for(d = alldevs,i = 0; i < inum - 1; d = d->next , i++);
fp = pcap_open_live(d->name,
100,
1,
100,
errbuf);
if(fp == NULL ){
printf("\nError in opening adapter\n");
return -1;
}
netmask = 0xffffff;
if(pcap_compile(fp,&fcode,"arp",1,netmask) < 0){
printf("\nUnable to compile the packet filter,Check the syntax.\n");
system("pause");
return -1;
}
if(pcap_setfilter(fp,&fcode) < 0){
printf("\nError setting teh filter.\n");
pcap_close(fp);
system("pause");
return -1;
}
while((res = pcap_next_ex(fp,&header , &pkt_data)) >= 0){
if(res == 0)
continue;
printf("%ld:%ld(%ld)\n",header->ts.tv_sec,header->ts.tv_usec,header->len);
for(i = 1; (i < header->caplen + 1) ; i++){
printf("%.2x ",pkt_data[i - 1]);
if((i % LINE_LEN) == 0) printf("\n");
}
printf("\n\n");
if(temp ++ > Number )
break;
}
if(res == -1){
printf("Error reading the packets: %s",pcap_geterr(fp));
return -1;
}
pcap_close(fp);
system("pause");
//return 0;
}