2

大家好,我如何收集 pcap 文件中每个数据包的数据包长度?多谢

4

2 回答 2

7

我建议一种很少有人知道的高科技方法:阅读文档。

man pcap 告诉我们实际上有两种不同的长度可用:

              caplen 一个 bpf_u_int32 给出数据包的字节数
                     可从捕获中获得

              len 一个 bpf_u_int32 给出数据包的长度,以字节为单位(其中
                     可能超过上限可用的字节数
                     ture,如果数据包的长度大于最大数量
                     要捕获的字节数)

C中的一个例子:

/* 抓取一个数据包 */
                数据包 = pcap_next(句柄,&header);
                if (packet == NULL) { /* 文件结束 */
                        休息;
                }
                printf ("得到一个长度为 [%d] \n 的数据包",
                                     header.len);

在 Python 中使用pcapy 库的另一个:

导入 pcapy

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

而真:
    尝试:
        (标题,有效负载)= reader.next()
        print "得到一个长度为 %d 的数据包" % header.getlen()
    除了 pcapy.PcapError:
        休息

于 2010-09-18T16:19:13.833 回答
0

下面的两个例子工作正常:

  • 使用 C、WinPcap
  • 使用python,SCAPY

(WinPcap)(Compiler 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;

}

另一个使用精彩SCAPY的 Python 工作示例

    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
于 2011-11-01T08:12:28.063 回答