
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
//#include "clientserver.h"


#define BUFLEN 512

int main(int argc, char **argv)
{
struct sockaddr_in   si_local, si_remote;
int                  s;
int                  port;
unsigned int         slen;
char                 buf[BUFLEN];


slen     =   sizeof(si_remote);
if(argc!=2)
{
fprintf(stderr, "Usage: %s <port number>\n", argv[0]);
exit(EXIT_FAILURE);
}

port=atoi(argv[1]);
if(port<1024)
{
fprintf(stderr, "Usage: %s <port number>\n", argv[0]);
fprintf(stderr, "\twhere <port number> shall be > 1023\n");
exit(EXIT_FAILURE);
}


if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
{
perror("socket");
exit(EXIT_FAILURE);
}



memset((char *) &si_local, 0, sizeof(si_local));
si_local.sin_family       =  AF_INET;
si_local.sin_port         =  htons(port);
si_local.sin_addr.s_addr  =  htonl(INADDR_ANY);
if (bind(s, (const struct sockaddr *)&si_local, sizeof(si_local))==-1)
{
perror("bind");
exit(EXIT_FAILURE);
}


    
    while(1)
    {    
        
        memset(buf, 0, sizeof(char)*BUFLEN);


        if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *)&si_remote, &slen)==-1)
        {
            perror("recvfrom()");
            exit(EXIT_FAILURE);
        }

        if(strstr(buf, ".quit.")!=NULL)
        {
            printf("\".quit.\" Received \n");
            printf("Exiting\n");
            break;
        }
        else
    
        {
            printf("Received packet from %s:%d\n", inet_ntoa(si_remote.sin_addr),
                                ntohs(si_remote.sin_port));
            printf("Data: %s\n", buf);
        }
    }



close(s);
return 0;
}



