winpcap编程-2

来源:互联网 发布:oracle 分组排序SQL 编辑:程序博客网 时间:2024/05/17 09:32

    在winpcap-1中,已经配置好环境,并且写了一个获得所有网卡接口的程序.现在我们再用它来捕获原始的数据包:

#include "stdafx.h"
#define HAVE_REMOTE
#include <pcap.h>

#pragma comment(lib, "wpcap.lib");
#pragma comment(lib, "ws2_32.lib");

void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);

int _tmain(int argc, _TCHAR* argv[])
{
 pcap_if_t *AllDev,*d;
 CHAR ErrBuff[PCAP_ERRBUF_SIZE];
 pcap_t *AdHandle;

 if (pcap_findalldevs(&AllDev, ErrBuff) != 0)
  {
   printf("Error %s\n",ErrBuff);
   return 0;
  } 

 d = AllDev;          //第一个网卡正是我需要的

 if ((AdHandle = pcap_open(d->name,
                        65536,
         PCAP_OPENFLAG_PROMISCUOUS,  //混杂模式
         1000,
         NULL,
         ErrBuff)) == NULL)
  {
   pcap_freealldevs(AllDev);
   return 0;
  }
 pcap_freealldevs(AllDev);

 pcap_loop(AdHandle, 0, packet_handler, NULL);

 return 0;
}

void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
 printf("有数据包\n");

}

  这些数据包都是链路层上的,以太网帧,先看下以太网帧的格式:

typedef struct _ether_header
{
 u_int8_t  ether_dhost[6];      /* destination eth addr */
 u_int8_t  ether_shost[6];      /* source ether addr    */
 u_int16_t ether_type;          /* packet type ID field */
}ether_header,*pether_header;

    类型字段指明下面的数据包类型,0x0800是IP数据报,0x0806 ARP数据包,0x03035 RARP数据包

    IP数据报的格式:

 

typedef struct ip_address{

 u_char byte1;

 u_char byte2;

 u_char byte3;

 u_char byte4;

};

typedef struct _ip_header{

 u_char  ver_ihl;        // Version (4 bits) + Internet header length (4 bits)

 u_char  tos;            // Type of service

 u_short tlen;           // Total length

 u_short identification; // Identification

 u_short flags_fo;       // Flags (3 bits) + Fragment offset (13 bits)

 u_char  ttl;            // Time to live

 u_char  proto;          // Protocol

 u_short crc;            // Header checksum

 ip_address  saddr;      // Source address

 ip_address  daddr;      // Destination address

 u_int   op_pad;         // Option + Padding

}_ip_header,*p_ip_header;

void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
 USHORT type;

 pether_header eh = (pether_header)pkt_data;
 
 type = ntohs(eh->ether_type);
 switch(type)
  {
   case 0x800:           //IP数据包
    {
     break;
    }
   case 0x806:
    {
     break;
    }
   case 0x8035:
    {
     break;
    }
   default:
    {
     
     break;
    }
  }

 
}

 

原创粉丝点击