如题, 分享一个在C语言中用libpcap解析pcap文件的小程序. 这个小程序的运行逻辑是检查以太网帧, 如果ether_type显示以太网帧中包含了一个IP报文的话继续对齐进行处理; 接着检查IP报文的协议字段, 如果它的协议字段显示其中包含一个TCP包的话, 则打印数据包的源和目标IP地址, 源和目标端口号, TCP包头的序列号和确认号. 代码如下:
//测试.c
#include <pcap.h>
#include <net/ethernet.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <翻译包.h>
void packetHandler(u_char *userData, const struct pcap_pkthdr* pkthdr, const u_char* packet);
int main() {
pcap_t *descr;
char errbuf[PCAP_ERRBUF_SIZE];
// open capture file for offline processing