#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <netinet/in.h>
#include <unistd.h>
#include <netdb.h>
#include <string.h>
#include <fcntl.h>
#include <signal.h>

#define BUFLEN	512

/* init_socket sets up the mother descriptor - creates the socket, sets
 * its options up, binds it, and listens.  */
int	init_socket(int port)
{
   int	s, opt;
   struct sockaddr_in sa;

   /*
    * Should the first argument to socket() be AF_INET or PF_INET?  I don't
    * know.  Take your pick.  PF_INET seems to be more widely adopted, but
    * all implementations I've seen define AF_INET and PF_INET to be
    * synonymous anyway.
    */

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

#if defined(SO_REUSEADDR)
   opt = 1;
   if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0){
      perror("setsockopt REUSEADDR");
      exit(1);
   }
#endif

#if defined(SO_REUSEPORT)
   opt = 1;
   if (setsockopt(s, SOL_SOCKET, SO_REUSEPORT, (char *)&opt, sizeof(opt)) < 0){
      perror ("setsockopt REUSEPORT");
      exit(1);
   }
#endif

   sa.sin_family = AF_INET;
   sa.sin_port = htons(port);
   sa.sin_addr.s_addr = INADDR_ANY;

   if (bind(s, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
      perror("bind");
      close(s);
      exit(1);
   }

   listen(s, 3);
   return(s);
}


int main()
{
   int s, fromlen, len;
   struct sockaddr from;
   char buf[BUFLEN];

   s = init_socket(4991);
   while (1) {
      len = recvfrom(s, buf, BUFLEN, 0, &from, &fromlen);
      buf[len] = '\0';
      puts(buf);
   }
}

