-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpcap-sample.c
69 lines (62 loc) · 1.29 KB
/
pcap-sample.c
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <inttypes.h>
#include <pcap.h>
#include <err.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <getopt.h>
#include "pcap-tools.h"
const char *progname = 0;
/*
* Sample every Nth packet
*/
void
usage(void)
{
fprintf(stderr, "usage: %s -n rate < pcap-in > pcap-out\n", progname);
exit(1);
}
int
main(int argc, char *argv[])
{
pcap_t *in = NULL;
pcap_dumper_t *out = NULL;
struct pcap_pkthdr hdr;
const u_char *data;
int i;
uint64_t samplerate = 0;
uint64_t incount = 0;
uint64_t outcount = 0;
progname = argv[0];
while ((i = getopt(argc, argv, "n:")) != -1) {
switch (i) {
case 'n':
samplerate = strtoul(optarg, 0, 10);
break;
case '?':
default:
usage();
}
}
argc -= optind;
argv += optind;
in = my_pcap_open_offline("-");
out = pcap_dump_open(in, "-");
if (NULL == out) {
perror("stdout");
exit(1);
}
while ((data = pcap_next(in, &hdr))) {
if (0 != (incount++ % samplerate))
continue;
pcap_dump((void *) out, &hdr, data);
outcount++;
}
my_pcap_close_offline(in);
pcap_dump_close(out);
fprintf(stderr, "%s: Read %" PRIu64 ", Wrote %" PRIu64 " packets\n", progname, incount, outcount);
exit(0);
}