#include "pcap.h"
#include <winsock2.h>
#pragma comment(lib,"Ws2_32.lib")
#pragma comment(lib,"wpcap.lib")
void main(){
pcap_if_t *alldevs;
pcap_if_t *p;
pcap_t *devHandle;//适配器句柄
struct pcap_pkthdr *packetHeader;//与数据包捕获有关的一个Header
const unsigned char *packetData;//数据包内容的指针
char errbuf[PCAP_ERRBUF_SIZE];
if(pcap_findalldevs(&alldevs,errbuf)==-1){//检索所有适配器
fprintf(stderr,"error:%s\n",errbuf);
exit(1);
}
if(alldevs==NULL){
printf("no devs\n");
return;
}
int i=0;
for(p=alldevs;p;p=p->next){
printf("%d:%s\n",++i,p->name);
printf("%s\n",p->description);
}
int choose;
printf("Input the index of the chosen adapter:\n");
scanf("%d",&choose);
if(choose<1||choose>i){
pcap_freealldevs(alldevs);//释放适配器列表
return;
}
p=alldevs;
for(i=0;i<choose;i++)
p=p->next;
char err[PCAP_ERRBUF_SIZE];
devHandle=pcap_open_live(p->name,65535,1,1000,err);//获取捕获网络数据包的数据包捕获描述符 现用pcap_open
if(devHandle==NULL){
fprintf(stderr,"\nUnable to open the adapter\n",p->name);
pcap_freealldevs(alldevs);
return;
}
printf("\nCapture session started on adapter %s\n",p->name);
pcap_freealldevs(alldevs);
int ret;
while((ret=pcap_next_ex(devHandle,&packetHeader,&packetData))>=0){//开始抓包,pcap_dispatch(...)阻塞,pcap_loop(...)非阻塞
if(ret==0)
continue;
printf("length of packet:%d\n",packetHeader->len);
//printf("addr:%s\n",inet_ntoa(((sockaddr_in *)(p->addresses->addr))->sin_addr));
//printf("net mask:%s\n",inet_ntoa(((sockaddr_in *)(p->addresses->netmask))->sin_addr));
//printf("broad addr:%s\n",inet_ntoa(((sockaddr_in *)(p->addresses->broadaddr))->sin_addr));
//printf("dest addr:%s\n",inet_ntoa(((sockaddr_in *)(p->addresses->dstaddr))->sin_addr));
}
if(ret==-1){
printf("Error reading the packet:%s\n",pcap_geterr(devHandle));
return;
}
return;
}