pcap文件解析

本文介绍了如何直接读取和解析pcap文件,避免了将pcap包转换为txt格式的过程。通过理解pcap文件的结构体并在读取时注意字节顺序的转换,如使用ntohs()函数,可以正确解析TCP和UDP协议的数据包。作者分享了实践经验和代码示例,并展示了读取结果。此外,推荐了一个MFC教程链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看了很久终于搞清楚怎么解析pcap文件啦~以前的一个版本是我把pcap包保存成.txt,删除冗余项,然后再依照格式读入,输出相应格式。后来,我发现其他同学都是用.pcap格式直接读入的,然后我就不懂了,直接读入的pcap文件格式应该是什么样子的?根据实战经验,应该就是网上各种教程解析的那种格式,根据那种格式按字节读入就可以啦!下面上代码:

这个是pcap.h 里面定义了pcap文件的主要结构体。

#include<afx.h>
#include<stdio.h>
#include<direct.h>
#include<iostream>
#include<cstring>
using namespace std;
#include<stdlib.h>
#include<math.h>
#include <winsock2.h>
#pragma  comment(lib,"ws2_32.lib")
typedef long int32;
typedef unsigned long u_int32;
typedef unsigned short u_int16;
typedef unsigned char u_int8;
//pcap文件头结构
typedef struct pcap_file_header{
	u_int32 magic;//标识位
	u_int16 version_major;//主版本号
	u_int16 version_minor;//副版本号
	int32 thiszone;//区域时间
	u_int32 sigfigs;//精确时间戳
	u_int32 snaplen;//数据包最大长度
	u_int32 linktype;//链路层类型
}pcapFileHeader;
//packet数据包头文件
typedef struct pcap_packet_header{
	int32 sec;//秒计时时间戳
	int32 microsec;//微秒计时时间戳
	u_int32 caplen;//数据包长度,即所捕获的数据包保存在pcap文件中的实际长度
	u_int32 len;//数据包实际长度,即所捕获的数据包的真实长度
}pcapPacketHeader;
//捕获的以太网帧头
typedef struct ehternet_header{
	u_int8 dstMac[6];//目的Mac地址
	u_int8 srcMac[6];//源Mac地址
	u_int16 type;//帧类型
}ehternetHeader;
//IP数据报头
typedef struct ip_header{
	u_int8 ver_hlen;//版本+报头长度
	u_int8 typeOfService;//服务类型
	u_int16 totalLen;//总长度
	u_int16 id;//标识
	u_int16 flag_Segment;//标志+片偏移
	u_int8 ttl;//生存期
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值