您的位置:首页 > 编程语言

读取cap文件的例子代码

2013-12-24 13:11 253 查看
#include <stdio.h>

#include <pcap.h>

#define P(format, ...) do \

{ \

printf("%s %s %d " format "\n", __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__); \

fflush(stdout); \

} \

while (0);

void PrintHex(const char* Buffer, int Size, FILE* fp = stderr)

{

fprintf(fp, "start: %08X count=%d\n", (unsigned int)Buffer, Size);

fprintf(fp, "Address: 0 1 2 3 4 5 6 7 8 9 A B C D E F\n"

"========================================================= ");

const char* p = NULL;

int i;

int nSpaceCount = (unsigned int)Buffer % 16;

if ( nSpaceCount != 0)

{

fprintf(fp, "\n%08X: ", (unsigned int)Buffer-nSpaceCount);

for (i=0; i<nSpaceCount; i++)

{

fprintf(fp, " ");

}

}

char line[17];

memset(line, 0x20, sizeof(line));

line[sizeof(line)-1] = '\0';

for (i=0, p = Buffer; i<Size; i++, p++)

{

if (((unsigned int)p) % 16 == 0)

{

fprintf(fp, "| [%s]\n%08X: ", line, (unsigned int)p);

}

fprintf(fp, "%02X ", (unsigned char)*p);

if (*p>0x20 && *p<=0x7E)

{

line[(unsigned int)p % 16] = *p;

}

else

{

line[(unsigned int)p % 16] = 0x20;

}

}

nSpaceCount = 16 - (unsigned int)p % 16;

if (nSpaceCount>0)

{

for (i=0; i<nSpaceCount; i++)

{

line[i+(16-nSpaceCount)] = 0x20;

fprintf(fp, " ");

}

fprintf(fp, "| [%s]", line);

}

fprintf(fp, "\n========================================================="

"\nAddress: 0 1 2 3 4 5 6 7 8 9 A B C D E F\n"

);

}

void TimeT2String(time_t Time, char* Buffer, int BufferSize)

{

if (NULL == Buffer || 0 >= BufferSize)

{

return;

}

struct tm* pTM = localtime(&Time);

strftime(Buffer, BufferSize-1, "%Y-%m-%d %H:%M:%S", pTM);

Buffer[BufferSize-1] = '\0';

}

void test()

{

const char* file_path = "F:/TEMP/2008-08-29/cap.cap";

char error[PCAP_ERRBUF_SIZE];

pcap_t* handle = pcap_open_offline(file_path, error);

if (NULL==handle)

{

P("open file error:%s", error);

return;

}

//

struct pcap_pkthdr* pHead;

char* pData;

int nReturnCode;

char time_str[21];

do

{

nReturnCode = pcap_next_ex(handle, &pHead, (const u_char**)&pData);

switch (nReturnCode)

{

case 1:

TimeT2String(pHead->ts.tv_sec, time_str, sizeof(time_str));

P("time=%s.%d,len=%d", time_str, (int)pHead->ts.tv_usec, pHead->len/*-sizeof(struct pcap_pkthdr)*/);

PrintHex(pData, pHead->len);

printf("\n");

break;

case 0:

P("time out");

continue;

break;

case -1:

P("error:%s", pcap_geterr(handle));

goto EndReadFile;

break;

case -2:

P("end of file");

goto EndReadFile;

break;

default:

P("unknown code:%d", nReturnCode);

goto EndReadFile;

break;

}

} while(1);

//

EndReadFile:

pcap_close(handle);

handle = NULL;

}

int main()

{

test();

return 1;

}

/*

g++ -o main.o -c main.cpp -g -Wall -Werror -I"F:\AoTainFaundationLibrary\Library\WinPcap\include"

g++ -o main.exe main.o "F:\AoTainFaundationLibrary\Library\WinPcap\lib\libwpcap.a"

main.exe

pause

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: