http://blog.csdn.net/htttw/article/details/7521053
#include <stdio.h>
#include <pcap.h>
#include <time.h>
#include <stdlib.h>
void getPacket(u_char* arg,const struct pcap_pkthdr* pkthdr,const u_char*packet)
{
int *id = (int *)arg;
printf("id: %d\n",++(*id));
printf("packet length:%d\n",pkthdr->len);
printf("number of bytes:%d\n",pkthdr->caplen);
printf("recived time:%s",ctime((const timer_t*)&pkthdr->ts.tv_sec));
int i=0;
for(i=0;i<pkthdr->len;++i)
{
printf(" %02x",packet[i]);
if((i+1)%16==0){
printf("\n");
}
}
printf("\r\n\r\n");
}
int main(void)
{
// printf("Hello World!\n");
char errBuf[PCAP_ERRBUF_SIZE], *devStr;
devStr = pcap_lookupdev(errBuf);
if(devStr){
printf("success:device %s\n",devStr);
}else{
printf("error:%s\n",errBuf);
}
//open a device ,wait until a packet arrives
pcap_t * device = pcap_open_live(devStr,65535,1,0,errBuf);
if(!device){
printf("error :pcap_open_live(): %s\n",errBuf);
exit(1);
}
struct bpf_program filter;
pcap_compile(device,&filter,"src port 80",1,0);
pcap_setfilter(device,&filter);
int id=0;
pcap_loop(device,-1,getPacket,(u_char*)&id);
//wait a packet to arrive
/* struct pcap_pkthdr packet;
const u_char* pktStr = pcap_next(device,&packet);
if(!pktStr){
printf("did not capture a packet \n");
exit(1);
}
printf("packet length : %d\n",packet.len);
printf("number of bytes: %d\n",packet.caplen);
printf("recived time: %s\n",ctime((const time_t*)&packet.ts.tv_sec));
*/
pcap_close(device);
return 0;
}