假如本地已经通过抓包工具保存了pcap格式的数据包文件,通过libpcap的库也能简单地进行离线分析
pcap_t *
pcap_open_offline(const char *fname, char *errbuf)
函数打开保存的数据包文件,用于读取,返回文件描述符
fname参数指定了pcap文件名
errbuf依旧是函数出错的时候返回错误信息
这样直接分析离线数据包文件,然后通过pcap_next读取一个又一个包,最后close掉释放,可以简单如下来写
[lihui@master work]$ cat offline.c
#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>
int main(){
char ebuf[PCAP_ERRBUF_SIZE];
char *pcap_file = “one.pcap”;
pcap_t *p = pcap_open_offline(pcap_file, ebuf);
struct pcap_pkthdr pkthdr;
while (1){
const u_char *pktStr = pcap_next(p, &pkthdr);
if (!pktStr){
printf(“Pcap file parse over !\n”);
exit(1);
}
printf(“Length: %d\n”, pkthdr.len);
}
pcap_close(p);
return 0;
}
[lihui@master work]$ gcc offline.c -lpcap
[lihui@master work]$ ./a.out
Length: 74
Length: 74
Length: 66
Length: 474
Length: 66
Length: 1480
Length: 66
Length: 1359
Length: 66
Length: 487
Length: 773
Length: 432
Length: 1480
Length: 859
Length: 66
Length: 66
Length: 66
Length: 66
Length: 66
Pcap file parse over !