cleanpcap / mypcap.c /
23ada98 7 years ago
1 contributor
70 lines | 2.209kb
#include <stdint.h>
#include <pcap.h>
#include "mypcap.h"

typedef struct pcap_hdr_s {
        uint32_t magic_number;   // magic number 
        uint16_t version_major;  // major version number 
        uint16_t version_minor;  // minor version number 
        int32_t  thiszone;       // GMT to local correction 
        uint32_t sigfigs;        // accuracy of timestamps 
        uint32_t snaplen;        // max length of captured packets, in octets 
        uint32_t network;        // data link type 
} pcap_hdr_t;

typedef struct pcaprec_hdr_s {
        uint32_t ts_sec;         /* timestamp seconds */
        uint32_t ts_usec;        /* timestamp microseconds */
        uint32_t incl_len;       /* number of octets of packet saved in file */
        uint32_t orig_len;       /* actual length of packet */
} pcaprec_hdr_t;

//Big Endian
//~ const pcap_hdr_t cst_pcap_global_hdr = {
	//~ magic_number: 0xD4C3B2A1,
	//~ version_major: 0x0200,
	//~ version_minor: 0x0400,
	//~ thiszone: 0x00000000,
	//~ sigfigs: 0x00000000,
	//~ snaplen: 0xFFFF0000,
	//~ network: 0x01000000,
//~ };
//Little Endian
const pcap_hdr_t cst_pcap_global_hdr = {
	magic_number: 0xA1B2C3D4,
	version_major: 0x0002,
	version_minor: 0x0004,
	thiszone: 0x00000000,
	sigfigs: 0x00000000,
	snaplen: 0x0000FFFF,
	network: DLT_EN10MB,
};

FILE *mypcap_open(const char*filename, const char *mode) {
	FILE *temp = fopen(filename,mode);
	pcap_hdr_t temphdr;
	size_t rw_bytes = fread(&temphdr,1,sizeof(pcap_hdr_t),temp);
	uint8_t *ptr=(uint8_t*)&cst_pcap_global_hdr;
	if( 0 == rw_bytes ) {
		rw_bytes = fwrite(ptr,1,sizeof(pcap_hdr_t),temp);
		mypcap_flush(temp);
	}
	return temp;
}
int mypcap_close(FILE *handle) {
	return fclose(handle);
}
int mypcap_flush(FILE *handle) {
	return fflush(handle);
}
int mypcap_dump(FILE *handle,const struct pcap_pkthdr* header,const u_char* packet) {
	fseek(handle,0,SEEK_END);
	pcaprec_hdr_t temphdr;
	temphdr.ts_sec = header->ts.tv_sec;
	temphdr.ts_usec = header->ts.tv_usec;
	temphdr.incl_len = header->caplen;
	temphdr.orig_len = header->len;
	size_t rw_bytes = fwrite(&temphdr,1,sizeof(pcaprec_hdr_t),handle);
	rw_bytes += fwrite((uint8_t*)packet,1,header->caplen,handle);
	return (int)rw_bytes;
}