#include <time.h>
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <string.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/uio.h>
#include <sys/ioctl.h>

#define BUFSIZE 1024

main ( argc, argv )
    int argc;
    char **argv;
{
    fd_set readfds;
    struct sockaddr_in addr;
    struct hostent *hp;
    int    udpSock;
    struct timeval to;
    struct sockaddr_in from;
    int    fromlen, res;
    int    i;
    char   buf[BUFSIZE];
    int    buflen;
    char   serverName;
    char   *port=argv[1];

    if ( port == NULL )
    {
        fprintf(stderr, "Usage: us port\n");
        exit(2);
    }

    if ((udpSock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
        perror("socket");
        exit(1);
    }

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

    if (bind(udpSock, &addr, sizeof(addr)) < 0)
    {
        perror("bind");
        close(udpSock);
        exit(1);
    }
    fromlen = sizeof(from);
  
x:
    FD_ZERO(&readfds);
    FD_SET(udpSock, &readfds);
    to.tv_sec = 6;
    to.tv_usec = 0;
    if ((res = select(32, &readfds, 0, 0, 0)) <= 0)
    {
        if (!res)
        {
            exit(9);
        }
        else
        {
            perror("select");
            exit(10);
        }
    }
    
    buflen=recvfrom(udpSock, buf, BUFSIZE, 0, &from, &fromlen);
    if(buflen<0)
    {
        perror("recvfrom");
        exit(11);
    }
  
    printf ( "%d bytes ", buflen );
  
    printf ( "from client " );
    hp = gethostbyaddr((char *) &from.sin_addr.s_addr, sizeof(from.sin_addr.s_addr), AF_INET);
    if (hp != NULL)
    {
        printf ( "%s ", hp->h_name );
    }

    printf ( "(%s) ", inet_ntoa(from.sin_addr) );
  
    if (from.sin_family != AF_INET)
    {
        printf("not af_inet ");
    }
  
    printf ( "port %d ", ntohs(from.sin_port) );
  
    buf[buflen]='\0';
    printf ( "data: %s\n", buf );
    goto x;

}
