/* Print all native ATM frames */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netnatm/natm.h>
#include <stdio.h>
#include <time.h>
#include <errno.h>

main(argc, argv)
	int argc;
	char *argv[];
{
	struct sockaddr_natm snatm;
	u_char buf[1024*16];
	struct timeval tv;
	struct tm *t;
	time_t clk;
	int s, i, cc;

	if (argc != 4) {
		fprintf(stderr, "usage: %s ifname vpi vci\n", argv[0]);
		exit(1);
	}

	if ((s = socket(AF_NATM, SOCK_STREAM, PROTO_NATMAAL5)) < 0) {
		perror("socket");
		exit(1);
	}

	bzero(&snatm, sizeof(snatm));
	snatm.snatm_len = sizeof(snatm);
	snatm.snatm_family = AF_NATM;
	snprintf(snatm.snatm_if, IFNAMSIZ, "%s", argv[1]);
	snatm.snatm_vpi = atoi(argv[2]);
	snatm.snatm_vci = atoi(argv[3]);

	if (connect(s, (struct sockaddr *)&snatm, sizeof(snatm)) < 0) {
		perror("connect");
		exit(1);
	}

	snatm.snatm_if[IFNAMSIZ - 1] = '\0';
	printf("Waiting for frames on %s from %d/%d\n",
	       snatm.snatm_if, snatm.snatm_vpi, snatm.snatm_vci);

	for (;;) {
		cc = read(s, (char *)buf, sizeof(buf));
		if (cc < 0) {
			perror("read");
			exit(1);
		}
		if (cc == 0) {
			fprintf(stderr, "closed ?\n");
			exit(1);
		}
		(void) gettimeofday(&tv, NULL);
		clk = (time_t)tv.tv_sec;
		t = localtime(&clk);
		printf("%02d:%02d:%02d.%06u ",
		       t->tm_hour,
		       t->tm_min,
		       t->tm_sec,
		       (u_int)tv.tv_usec);
		printf("%d bytes:", cc);
		for (i = 0; i < cc; i++) {
			if ((i & 15) == 0)
				printf("\n\t");
			else if ((i & 1) == 0)
				printf(" ");
			printf("%02x", buf[i]);
		}
		printf("\n");
	}
}
