capt_get_packet(): check for key press only every 20ms
[iptraf-ng.git] / src / capture-pkt.c
blob1faccec0ddc3657d283b5f3294fe0337429ba66a
1 /* For terms of usage/redistribution/modification see the LICENSE file */
2 /* For authors and contributors see the AUTHORS file */
4 #include "iptraf-ng-compat.h"
6 #include "built-in.h"
7 #include "parse-options.h"
8 #include "ifaces.h"
9 #include "packet.h"
10 #include "capt.h"
12 static const char *const capture_usage[] = {
13 IPTRAF_NAME " capture [-c] <device>",
14 NULL
17 static int cap_nr_pkt = 1, help_opt;
18 static char *ofilename;
20 static struct options capture_options[] = {
21 OPT__HELP(&help_opt),
22 OPT_GROUP(""),
23 OPT_INTEGER('c', "capture", &cap_nr_pkt, "capture <n> packets"),
24 OPT_STRING('o', "output", &ofilename, "file", "save captured packet into <file>"),
25 OPT_END()
28 int cmd_capture(int argc, char **argv)
30 parse_opts(argc, argv, capture_options, capture_usage);
31 argv += optind;
32 if (help_opt || !*argv || argv[1])
33 parse_usage_and_die(capture_usage, capture_options);
35 char *dev = argv[0];
37 struct capt capt;
38 if (capt_init(&capt, dev) == -1)
39 die_errno("Unable to initialize packet capture interface");
41 FILE *fp = NULL;
42 if (ofilename) {
43 fp = fopen(ofilename, "wb");
44 if (!fp)
45 die_errno("fopen");
48 struct pkt_hdr pkt;
49 packet_init(&pkt);
51 int captured = 0;
52 for (;;) {
53 if (capt_get_packet(&capt, &pkt, NULL, NULL) == -1)
54 die_errno("fail to get packet");
56 if (!pkt.pkt_len)
57 continue;
59 printf(".");
60 fflush(stdout);
62 if (fp)
63 fwrite(&pkt, sizeof(pkt), 1, fp);
65 capt_put_packet(&capt, &pkt);
67 if (++captured == cap_nr_pkt)
68 break;
70 printf("\n");
72 packet_destroy(&pkt);
74 if (fp)
75 fclose(fp);
77 capt_destroy(&capt);
79 return 0;