2 * A tail-like command working on pcap files
4 * (c) 2012 Martin Mares <mj@ucw.cz>
7 #define _LARGEFILE_SOURCE
15 uint16_t major, minor;
17 uint32_t time_accuracy;
25 uint32_t captured_len;
29 int main(int argc, char **argv)
32 fprintf(stderr, "Usage: pcap-tail <num-packets> <file>\n");
36 uint64_t num = atoi(argv[1]);
37 uint64_t *ring = malloc(num * sizeof(uint64_t));
39 fprintf(stderr, "Out of memory\n");
43 FILE *in = fopen(argv[2], "r");
45 fprintf(stderr, "Cannot open %s: %m\n", argv[2]);
49 struct pcap_header hdr;
50 if (fread(&hdr, sizeof(hdr), 1, in) < 1) {
51 fprintf(stderr, "Cannot read header\n");
54 if (hdr.magic != 0xa1b2c3d4) {
55 fprintf(stderr, "Bad (black?) magic\n");
59 struct pcap_packet pkt;
63 uint64_t pos = ftell(in);
64 if (fread(&pkt, sizeof(pkt), 1, in) < 1)
66 // printf("@%d len=%d\n", (int)pos, pkt.captured_len);
68 ring_pos = (ring_pos + 1) % num;
69 fseek(in, pkt.captured_len, SEEK_CUR);
73 fwrite(&hdr, sizeof(hdr), 1, stdout);
75 fseek(in, ring[ring_pos], SEEK_SET);
77 fseek(in, ring[0], SEEK_SET);
82 while ((n = fread(buf, 1, sizeof(buf), in)) > 0)
83 fwrite(buf, 1, n, stdout);