pcap文件格式

最近项目中需要对网络数据包进行分析。这篇文章是在这里转的。

pcap文件格式

 
pcap文件格式是bpf保存原始数据包的格式,很多软件都在使用,比如tcpdump、wireshark等等,
了解pcap格式可以加深对原始数据包的了解,自己也可以手工构造任意的数据包进行测试。
 
pcap文件的格式为:
  文件头    24字节
  数据包头 + 数据包  数据包头为16字节,后面紧跟数据包
  数据包头 + 数据包  ......
 
pcap.h里定义了文件头的格式
struct pcap_file_header {
        bpf_u_int32 magic;
        u_short version_major;
        u_short version_minor;
        bpf_int32 thiszone;     /* gmt to local correction */
        bpf_u_int32 sigfigs;    /* accuracy of timestamps */
        bpf_u_int32 snaplen;    /* max length saved portion of each pkt */
        bpf_u_int32 linktype;   /* data link type (LINKTYPE_*) */
};
看一下各字段的含义:
 magic:   4字节 pcap文件标识 目前为“d4 c3 b2 a1”
 major:   2字节 主版本号     #define PCAP_VERSION_MAJOR 2
 minor:   2字节 次版本号     #define PCAP_VERSION_MINOR 4
 thiszone:4字节 时区修正     并未使用,目前全为0
 sigfigs: 4字节 精确时间戳   并未使用,目前全为0
 snaplen: 4字节 抓包最大长度 如果要抓全,设为0x0000ffff(65535),
          tcpdump -s 0就是设置这个参数,缺省为68字节
 linktype:4字节 链路类型    一般都是1:ethernet
 
|    magic    |major  | minor |   thiszone  |   sigfigs   |   snaplen   |  linktype   |
| d4 c3 b2 a1 | 02 00 | 04 00 | 00 00 00 00 | 00 00 00 00 | ff ff 00 00 | 01 00 00 00 |
 
数据包头的格式
struct pcap_pkthdr {
        struct timeval ts;      /* time stamp */
        bpf_u_int32 caplen;     /* length of portion present */
        bpf_u_int32 len;        /* length this packet (off wire) */
};
struct timeval {
        long            tv_sec;         /* seconds (XXX should be time_t) */
        suseconds_t     tv_usec;        /* and microseconds */
};
 ts:    8字节 抓包时间 4字节表示秒数,4字节表示微秒数
 caplen:4字节 保存下来的包长度(最多是snaplen,比如68字节)
 len:   4字节 数据包的真实长度,如果文件中保存的不是完整数据包,可能比caplen大
 
了解了pcap文件格式,就可以自己手工构造任意数据包了,可以以录好的包为基础,
用十六进制编辑器打开进行修改。
发布了24 篇原创文章 · 获赞 17 · 访问量 18万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章