前段时间接到一个公司关于解析pacp文件的培训(我是被培训的),在完成了一部分的功能后决定把一些关于pcap文件的了解记录到博客中。
#pragma pack( push, 1) // 为了保证在windows和linux下都能正常编译,放弃使用INT64或者_int_64 typedef short _Int16; typedef long _Int32; typedef char Byte; // Pcap文件头 struct __file_header { _Int32 iMagic; _Int16 iMaVersion; _Int16 iMiVersion; _Int32 iTimezone; _Int32 iSigFlags; _Int32 iSnapLen; _Int32 iLinkType; }; // 数据包头 struct __pkthdr { _Int32 iTimeSecond; _Int32 iTimeSS; _Int32 iPLength; _Int32 iLength; }; #pragma pack( pop)
#include<stdio.h> #include"pcap_header.h" #include<memory.h> #include<stdlib.h> #include<math.h> int main() { struct __pkthdr data; struct __file_header header; FILE* pFile = fopen( "iupsc.pcap", "rb"); if( pFile == 0) { printf( "打开pcap文件失败"); return 0; } fseek( pFile, 0, SEEK_END); long iFileLen = ftell( pFile); fseek( pFile, 0, SEEK_SET); Byte* pBuffer = (Byte*)malloc( iFileLen); fread( (void*)pBuffer, 1, iFileLen, pFile); fclose( pFile); memcpy( (void*)&header, (void*)(pBuffer) , sizeof(struct __file_header)); int iIndex = sizeof(struct __file_header); int iNo = 1; while(iIndex <= iFileLen) { memcpy( (void*)&data, (void*)(pBuffer + iIndex) , sizeof(struct __pkthdr)); char strPath[51]; sprintf( strPath, "export/%d-%d.pcap", iNo++, (int)data.iTimeSecond); strPath[50] = '\0'; FILE* pwFile = fopen( strPath, "wb"); fwrite((void*)&header, 1, sizeof(struct __file_header), pwFile); fwrite( (void*)(pBuffer + iIndex), 1, sizeof(struct __pkthdr) + data.iPLength, pwFile); fclose( pwFile); iIndex += sizeof(struct __pkthdr) + data.iPLength; } free( pBuffer); printf( "成功导出%d个文件", iNo - 1); return 1; }