feature: support packet dump to pcap
This commit is contained in:
73
src/packet/packet_dump.cpp
Normal file
73
src/packet/packet_dump.cpp
Normal file
@@ -0,0 +1,73 @@
|
||||
#include <stdio.h>
|
||||
#include <errno.h>
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <sys/time.h>
|
||||
|
||||
#include "log.h"
|
||||
#include "packet_dump.h"
|
||||
|
||||
#define PACKET_DUMP_LOG_ERROR(format, ...) LOG_ERROR("packet dump", format, ##__VA_ARGS__)
|
||||
|
||||
struct pcap_pkt_hdr
|
||||
{
|
||||
unsigned int tv_sec; // time stamp
|
||||
unsigned int tv_usec; // time stamp
|
||||
unsigned int caplen; // length of portion present
|
||||
unsigned int len; // length this packet (off wire)
|
||||
};
|
||||
|
||||
struct pcap_file_hdr
|
||||
{
|
||||
unsigned int magic;
|
||||
unsigned short version_major;
|
||||
unsigned short version_minor;
|
||||
unsigned int thiszone; // gmt to local correction
|
||||
unsigned int sigfigs; // accuracy of timestamps
|
||||
unsigned int snaplen; // max length saved portion of each pkt
|
||||
unsigned int linktype; // data link type (LINKTYPE_*)
|
||||
};
|
||||
|
||||
// return 0: success
|
||||
// return -1: failed
|
||||
int packet_dump(const char *file, const char *data, uint16_t len)
|
||||
{
|
||||
struct pcap_pkt_hdr pkt_hdr = {0};
|
||||
struct pcap_file_hdr file_hdr = {
|
||||
.magic = 0xA1B2C3D4,
|
||||
.version_major = 0x0002,
|
||||
.version_minor = 0x0004,
|
||||
.thiszone = 0,
|
||||
.sigfigs = 0,
|
||||
.snaplen = 0xFFFF,
|
||||
.linktype = 1};
|
||||
|
||||
if (file == NULL || data == NULL || len == 0)
|
||||
{
|
||||
PACKET_DUMP_LOG_ERROR("invalid parameter, file: %p, data: %p, len: %d", file, data, len);
|
||||
return -1;
|
||||
}
|
||||
|
||||
FILE *fp = fopen(file, "w+");
|
||||
if (fp == NULL)
|
||||
{
|
||||
PACKET_DUMP_LOG_ERROR("fopen %s failed, %s", file, strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
|
||||
struct timeval ts = {0};
|
||||
gettimeofday(&ts, NULL);
|
||||
|
||||
pkt_hdr.tv_sec = ts.tv_sec;
|
||||
pkt_hdr.tv_usec = ts.tv_usec;
|
||||
pkt_hdr.caplen = len;
|
||||
pkt_hdr.len = len;
|
||||
|
||||
fwrite(&file_hdr, sizeof(struct pcap_file_hdr), 1, fp);
|
||||
fwrite(&pkt_hdr, sizeof(struct pcap_pkt_hdr), 1, fp);
|
||||
fwrite(data, 1, len, fp);
|
||||
fflush(fp);
|
||||
fclose(fp);
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user