/* udp_o.c -- read packets from the network */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define BUFSIZE 1024
#define UDP_PORT 10094

main(argc, argv)
	int argc;
	char *argv[];
{
	int sock, fromlen, l, i, portno;
	char buf[BUFSIZE], *p;
	struct sockaddr_in from;

	portno = UDP_PORT;

	/* Test arguments */
	if(argc>2){
		fprintf(stderr,"Usage: %s [<portnumber>]\n",argv[0]);
		exit(1);
	}
	if(argc>1)portno = atoi(argv[1]);

	/* Create socket */
	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock<0) {
		perror("opening raw socket");
		exit(1);
	}

	bzero((char *)&from, sizeof from);
	from.sin_family = AF_INET;
	from.sin_addr.s_addr = htonl(INADDR_ANY);
	from.sin_port = htons(portno);
	if (bind(sock, (struct sockaddr *)&from, sizeof from) < 0){
		perror("binding UDP socket");
		exit(1);
	}

	l = 0;
	while(l>-1){
		fromlen = sizeof from;
		l = recvfrom(sock, buf, BUFSIZE, 0, 
			(struct sockaddr *)&from, &fromlen);
		if(l<0){
			perror("udp socket");
			close(sock);
			exit(2);
		}
		fprintf(stdout,"---------->recv %d bytes from port %d host %s\n", l,
				ntohs(from.sin_port),
				(char *)inet_ntoa(from.sin_addr));

		fprintf(stdout,"{%d.%d.%d.%d->%d.%d.%d.%d}\n",buf[12],buf[13],
			buf[14],buf[15],buf[16],buf[17],buf[18],buf[19]);

		for(p=buf+40,i=0;i<(l-40);i++,p++){
			if(isprint(*p))putc(*p,stdout);
			else putc('.',stdout);
		}
				putc('\n',stdout);
		fflush(stdout);
	}

	/* all done, close the socket and exit */
	close(sock);
	exit(0);
}
