ARPSpoofing教程(三) - 捕获数据包

时间:2022-02-14 23:56:25
   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\n",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\n",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)\n",d->description);
  28:      }
  29:      if(count==1) {
  30:          printf("No interface found! Make sure WinPcap is isntalled\n");
  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\n");
  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...\n",d->description);
  56:          
  57:          pcap_freealldevs(alldevs);
  58:          //开始捕获 
  59:          pcap_loop(adhandle,0,packet_handler,NULL);
  60:   
  61:      }
  62:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

试验结果:

ARPSpoofing教程(三) - 捕获数据包