/*      Project Group : Muhammad Rashid Mahfooz, Salman Zubair, Syed Shahzad Ali
 *                      CS742 COMPUTER COMMUNICATION NETWORKS
 *                      Wichita State University
 *                      Wichita Kansas
 *
 *      Created:        September 18, 2001
 *
 *      Program:        This is a server program which recieves a request
 * 			form the client and provides the current date and  
 *			time to the client's request
 *
 *      Modified:       September 19, 2001
 */     

/* Included Header Files */
#include	<time.h>
#include	<sys/types.h>	/* basic system data types */
#include	<sys/socket.h>	/* basic socket definitions */
#include	<sys/time.h>	/* timeval{} for select() */
#include	<time.h>	/* timespec{} for pselect() */
#include	<netinet/in.h>	/* sockaddr_in{} and other Internet defns */
#include	<arpa/inet.h>	/* inet(3) functions */
#include	<errno.h>
#include	<fcntl.h>	/* for nonblocking */
#include	<netdb.h>
#include	<signal.h>
#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>
#include	<sys/stat.h>	/* for S_xxx file mode constants */
#include	<sys/uio.h>	/* for iovec{} and readv/writev */
#include	<unistd.h>
#include	<sys/wait.h>
#include	<sys/un.h>	/* for Unix domain sockets */

/* Macros used by program */
#define MAXLINE		4096	/* max text line length */
#define LISTENQ		1024	/* 2nd argument to listen() */
#define SA		struct sockaddr
#define PORT_NO 5914		/* port number */

/* Mian Function */
int main(int argc, char **argv)
{
	int		listenfd, connfd;
	socklen_t			len;
	struct sockaddr_in	servaddr, cliaddr;
	char				buff[MAXLINE];
	time_t				ticks;

	if( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
	{
		perror("Socket cannot be created");
		exit(1);
	}
	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(PORT_NO);	/* daytime server */

	bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

	if( (listen(listenfd, LISTENQ) == -1) )
	{
		perror("error in listen function");
		exit(1);
	}

	for ( ; ; ) 
	{
		len = sizeof(cliaddr);
		connfd = accept(listenfd, (SA *) &cliaddr, &len);
		printf("connection from %s, port %d\n",
			   inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff)),
			   ntohs(cliaddr.sin_port));

        	ticks = time(NULL);
        	snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
        	write(connfd, buff, strlen(buff));

		close(connfd);
	}
}
/* end of main () */
