1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | #include <stdlib.h> #include <stdio.h> #include <sys/unistd.h> #include <pcap/pcap.h> typedef struct pcap_log_t pcap_log_t; struct pcap_log_t { pcap_t* pd; pcap_dumper_t* pdumper; }; pcap_log_t* pcap_log_init() { char path[256]; pcap_log_t* pcap = (pcap_log_t*)malloc(sizeof(*pcap)); memset(pcap, 0, sizeof(*pcap)); pcap->pd = pcap_open_dead(/* DLT_RAW */ 1, 65535 /* snaplen */); sprintf(path, "/tmp/pcap_%d.pcap", gettid()); pcap->pdumper = pcap_dump_open(pcap->pd, path); return pcap; } void pcap_log_write(pcap_log_t* pcap, char* packet, int len) { struct pcap_pkthdr hdr; hdr.ts.tv_sec = 0; hdr.ts.tv_usec = 0; hdr.caplen = len; hdr.len = len; pcap_dump((u_char*)pcap->pdumper, &hdr, (const u_char*)packet); pcap_dump_flush(pcap->pdumper); } void pcap_log_fini(pcap_log_t* pcap) { pcap_dump_close(pcap->pdumper); pcap_close(pcap->pd); free(pcap); } int main() { pcap_log_t* pcap = pcap_log_init(); /* while (...) { // packet is raw data from mac layer pcap_log_write(pcap, packet, len); } */ pcap_log_fini(pcap); return 0; } |
refer to:
https://blog.csdn.net/u014260236/article/details/51035484/