fluffy/pcap.c

94 lines
1.6 KiB
C
Raw Normal View History

2011-04-21 16:12:01 -06:00
#include <stdio.h>
#include <sysexits.h>
2011-04-22 12:47:08 -06:00
#include <string.h>
2011-04-21 16:12:01 -06:00
#include "pcap.h"
int
2013-01-29 21:53:17 -07:00
pcap_open_in(struct pcap_file *ctx, FILE * f)
2011-04-21 16:12:01 -06:00
{
2013-01-29 21:53:17 -07:00
struct pcap_file_header h;
if (1 != fread(&h, sizeof(h), 1, f)) {
h.magic = 0;
}
if (MAGIC == h.magic) {
ctx->swap = 0;
} else if (bswap32(MAGIC) == h.magic) {
ctx->swap = 1;
} else {
return -1;
}
if ((h.version_major != 2) || (h.version_minor != 4))
return -1;
if (ctx->swap)
h.snaplen = bswap32(h.snaplen);
if (h.snaplen > MAXFRAME)
return -1;
ctx->f = f;
return 0;
2011-04-21 16:12:01 -06:00
}
int
2013-01-29 21:53:17 -07:00
pcap_open_out(struct pcap_file *ctx, FILE * f)
2011-04-21 16:12:01 -06:00
{
2013-01-29 21:53:17 -07:00
struct pcap_file_header h = { MAGIC, 2, 4, 0, 0, MAXFRAME, 1 };
2011-04-21 16:12:01 -06:00
2013-01-29 21:53:17 -07:00
if (1 != fwrite(&h, sizeof(h), 1, f))
return -1;
ctx->f = f;
ctx->swap = 0;
2011-04-21 16:12:01 -06:00
2013-01-29 21:53:17 -07:00
return 0;
2011-04-21 16:12:01 -06:00
}
int
2011-04-22 12:47:08 -06:00
pcap_read_pkthdr(struct pcap_file *ctx, struct pcap_pkthdr *hdr)
2011-04-21 16:12:01 -06:00
{
2013-01-29 21:53:17 -07:00
if (1 != fread(hdr, sizeof(*hdr), 1, ctx->f)) {
return -1;
}
2011-04-21 16:12:01 -06:00
2013-01-29 21:53:17 -07:00
if (ctx->swap) {
hdr->ts.tv_sec = bswap32(hdr->ts.tv_sec);
hdr->ts.tv_usec = bswap32(hdr->ts.tv_usec);
hdr->caplen = bswap32(hdr->caplen);
hdr->len = bswap32(hdr->len);
}
2011-04-21 16:12:01 -06:00
2013-01-29 21:53:17 -07:00
if (hdr->caplen > MAXFRAME)
return -1;
2011-07-14 18:55:41 -06:00
2013-01-29 21:53:17 -07:00
return 0;
2011-04-21 16:12:01 -06:00
}
int
2011-04-22 12:47:08 -06:00
pcap_write_pkthdr(struct pcap_file *ctx, struct pcap_pkthdr *hdr)
2011-04-21 16:12:01 -06:00
{
2013-01-29 21:53:17 -07:00
if (ctx->swap) {
struct pcap_pkthdr ohdr;
memcpy(&ohdr, hdr, sizeof(ohdr));
hdr->ts.tv_sec = bswap32(hdr->ts.tv_sec);
hdr->ts.tv_usec = bswap32(hdr->ts.tv_usec);
hdr->caplen = bswap32(hdr->caplen);
hdr->len = bswap32(hdr->len);
if (1 != fwrite(&ohdr, sizeof(ohdr), 1, ctx->f))
return -1;
} else {
if (1 != fwrite(hdr, sizeof(*hdr), 1, ctx->f))
return -1;
}
return 0;
2011-04-21 16:12:01 -06:00
}
void
pcap_close(struct pcap_file *ctx)
{
2013-01-29 21:53:17 -07:00
fclose(ctx->f);
2011-04-21 16:12:01 -06:00
}