This repository has been archived on 2025-09-14. You can view files and clone it, but cannot push or open issues or pull requests.
Files
stellar-stellar/src/packet/packet_dump.cpp

86 lines
2.2 KiB
C++
Raw Normal View History

2024-07-01 15:51:36 +08:00
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <sys/time.h>
#include "log.h"
#include "hexdump.h"
2024-07-01 15:51:36 +08:00
#include "packet_dump.h"
#include "packet_utils.h"
2024-07-01 15:51:36 +08:00
#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_pcap(const struct packet *pkt, const char *file)
2024-07-01 15:51:36 +08:00
{
const char *data = packet_get_raw_data(pkt);
uint16_t len = packet_get_raw_len(pkt);
2024-07-01 15:51:36 +08:00
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;
}
void packet_dump_hex(const struct packet *pkt, int fd)
{
uint16_t len = packet_get_raw_len(pkt);
const char *data = packet_get_raw_data(pkt);
hexdump_to_fd(fd, data, len);
}