#include <stdlib.h>
#include <stdio.h>
//包含pcap
#include <pcap.h>
#define MAX_PRINT 80
#define MAX_LINE 16
void ProcessPacket(u_char *,
const struct pcap_pkthdr *, const u_char *);
void main(int argc, char **argv) {
pcap_t *fp;
char error[PCAP_ERRBUF_SIZE];
char *device=NULL;
char filter_app[] = "port 80";
char *filter=NULL;
int i=0;
struct bpf_program fcode;
bpf_u_int32 SubNet,NetMask;
for(i=1;i<argc;i+=2){
switch (argv[i] [1])
{
case 'i'://设备
{
if(!strcmp("auto",argv[2]))
{
device=pcap_lookupdev(error);
}
};
break;
}
}
if (device != NULL){
if ( (fp= pcap_open_live(device, 1514, 1, 20, error) ) == NULL)
{
fprintf(stderr,"/nUnable to open the adapter./n");
return;
}
}
if(filter!=NULL){
//obtain the subnet
//得到子网
if(device!=NULL){
if(pcap_lookupnet(device, &SubNet, &NetMask, error)<0){
fprintf(stderr,"/nUnable to obtain the netmask./n");
return;
}
}
//如果device为空,设其为c类网
else NetMask=0xffffff; //If reading from file, we suppose to be in a C class network
//compile the filter
//编译过滤器
if(pcap_compile(fp, &fcode, filter_app, 1, NetMask)<0){
fprintf(stderr,"/nError compiling filter: wrong syntax./n");
return;
}
//set the filter
//设置过滤器
if(pcap_setfilter(fp, &fcode)<0){
fprintf(stderr,"/nError setting the filter/n");
return;
}
}
//start the capture
//开始截包
pcap_loop(fp, 10, ProcessPacket, NULL);
}
void ProcessPacket(u_char *temp1,
const struct pcap_pkthdr *header, const u_char *pkt_data)
{
u_int i=0;
// 打印包头时间戳和包长度
printf("%ld:%ld (%ld)/n", header->ts.tv_sec, header->ts.tv_usec, header->len);
while ( (i<MAX_PRINT) && (i<header->len) )
{
i++;
printf("%x ", pkt_data[i-1]);
if ( (i%MAX_LINE) == 0) printf("/n");
}
printf("/n/n");
}