hexagram/examples/pcapread.c
2018-12-16 11:37:04 -06:00

76 lines
1.3 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <inttypes.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <hexagram/pcapng.h>
static void usage(int argc, char **argv, const char *message, ...) {
if (message) {
va_list args;
va_start(args, message);
vfprintf(stderr, message, args);
va_end(args);
}
fprintf(stderr, "usage: %s [file.pcapng]\n", argv[0]);
exit(1);
}
static int handle_block(int fd, uint32_t type, size_t len) {
printf("Read block type %08"PRIx32" len %zu\n",
type, len);
if (lseek(fd, len, SEEK_CUR) < 0) {
perror("lseek()");
goto error_io;
}
return 0;
error_io:
return -1;
}
int main(int argc, char **argv) {
int fd, error;
if (argc == 1) {
fd = fileno(stdin);
} else if (argc == 2) {
if ((fd = open(argv[1], O_RDONLY)) < 0) {
perror("open()");
goto error_open;
}
} else {
usage(argc, argv, NULL);
}
if (hexagram_pcapng_stream_read(fd, handle_block, &error) < 0) {
perror("hexagram_pcapng_stream_read()");
goto error_io;
}
if (argc == 2) {
close(fd);
}
return 0;
error_io:
if (argc == 2) {
close(fd);
}
error_open:
return 1;
}