2010-07-06 20 views

ответ

7

Предлагаю высокотехнологичный метод, который очень мало кто знает: чтение документации.

человек PCAP говорит нам, что есть на самом деле два различных варианта длины:

 
       caplen a bpf_u_int32 giving the number of bytes of the packet that are 
        available from the capture 

       len a bpf_u_int32 giving the length of the packet, in bytes (which 
        might be more than the number of bytes available from the cap- 
        ture, if the length of the packet is larger than the maximum num- 
        ber of bytes to capture) 

Пример в C:

 
/* Grab a packet */ 
       packet = pcap_next(handle, &header); 
       if (packet == NULL) { /* End of file */ 
         break; 
       } 
       printf ("Got a packet with length of [%d] \n", 
            header.len); 

Еще один в Python с pcapy library:

 
import pcapy 

reader = pcapy.open_offline("packets.pcap") 

while True: 
    try: 
     (header, payload) = reader.next() 
     print "Got a packet of length %d" % header.getlen() 
    except pcapy.PcapError: 
     break 

0

Эти два примера ниже работают нормально:

  • с использованием C, WinPcap
  • с помощью питона, SCAPY

(WinPcap) (компилятор CL, Microsoft VC) Я написал эту функцию (в C), чтобы получить размер пакета и он отлично работает , Не забудьте включить pcap.h и установить HAVE_REMOTE в компилятор препроцессоре

u_int getpkt_size(char * pcapfile){ 

pcap_t *indesc; 
char errbuf[PCAP_ERRBUF_SIZE]; 
char source[PCAP_BUF_SIZE]; 
u_int res; 
struct pcap_pkthdr *pktheader; 
u_char *pktdata; 
u_int pktsize=0; 



/* Create the source string according to the new WinPcap syntax */ 
if (pcap_createsrcstr(source,   // variable that will keep the source string 
         PCAP_SRC_FILE, // we want to open a file 
         NULL,   // remote host 
         NULL,   // port on the remote host 
         pcapfile,  // name of the file we want to open 
         errbuf   // error buffer 
         ) != 0) 
{ 
    fprintf(stderr,"\nError creating a source string\n"); 
    return 0; 
} 

/* Open the capture file */ 
if ((indesc= pcap_open(source, 65536, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errbuf)) == NULL) 
{ 
    fprintf(stderr,"\nUnable to open the file %s.\n", source); 
    return 0; 
} 


/* get the first packet*/ 

    res=pcap_next_ex(indesc, &pktheader, &pktdata); 

    if (res !=1){ 
     printf("\nError Reading PCAP File"); 
        return 0; 
      } 



/* Get the packet size*/ 
pktsize=pktheader->len; 

/* Close the input file */ 
pcap_close(indesc); 

return pktsize; 

} 

Другим wroking Пример в Python с использованием замечательного SCAPY

from scapy.all import * 

    pkts=rdpcap("data.pcap",1) # reading only 1 packet from the file 
    OnePkt=pkts[0] 
    print len(OnePkt) # prints the length of the packet 
+0

Почему нет ntohs для (pktheader-> len)? –

Смежные вопросы