#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

#define PACKSIZE 1024
#define PORT 1536

int main(int argc, char **argv)
{
	struct sockaddr_in saddr;
	char buff[PACKSIZE];
	int s, ret, fromlen;
	fd_set fds;

	if( (s = socket(PF_INET, SOCK_DGRAM, 0)) == -1 )
	{
		perror("socket()");
		exit(errno);
	}

	memset(&saddr, 0, sizeof(saddr));
	saddr.sin_addr.s_addr = INADDR_ANY;
	saddr.sin_port = htons((u_short) PORT);
	saddr.sin_family = AF_INET;
	if( bind(s, (struct sockaddr *)&saddr, sizeof(saddr)) == -1 )
	{
		perror("bind()");
		exit(errno);
	}

	for(;;)
	{
		FD_ZERO(&fds);
		FD_SET(s, &fds);

		if( select(s + 1, &fds, NULL, NULL, NULL) == -1 )
		{
			if( errno == EINTR )
				continue;
			perror("select()");
			exit(errno);
		}

		if( FD_ISSET(s, &fds) )
		{
			fromlen = 0;
			ret = recvfrom(s, buff, PACKSIZE, 0, NULL, &fromlen);
			if( ret != PACKSIZE )
			{
				perror("recvfrom()");
				exit(errno);
			}
			if( ret == PACKSIZE )
			{
				if( write(STDOUT_FILENO, buff, PACKSIZE) != PACKSIZE )
				{
					perror("write()");
					exit(errno);
				}
			}
		}
	}

	return 0;
}

