Expt 10 Time Server
Expt 10 Time Server
Aim: Client sends a time request to the server, server sends its system time back to the client.
Description:
A concurrent server handles multiple clients at the same time. The simplest technique for a
concurrent server is to call the Unix fork function, i.e; creating one child process for each client.
The current time and date is obtained by the library function time which returns the number of
seconds since the Unix Epoch: 00:00:00 January 1, 1970, UTC (Coordinated Universal Time). ctime
is a function that converts this integer value into a human readable string.
Algorithm:
Client
Server
3. while (1)
Client
#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
#include<stdlib.h>
if(argc != 3)
{
fprintf(stderr, "Usage: ./client IPaddress_of_server port\n");
exit(1);
}
bzero((char*)&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(atoi(argv[2]));
Server
#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
#include<stdlib.h>
#include<time.h>
time_t curtime;
struct sockaddr_in servaddr, cliaddr;
int len = sizeof(cliaddr);
if(argc != 2)
{
fprintf(stderr, "Usage: ./server port\n");
exit(1);
}
bzero((char*)&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(atoi(argv[1]));
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
while(1)
{
if((n = recvfrom(sock_fd,buffer , sizeof(buffer), 0, (struct sockaddr *)&cliaddr, &len)) == -1)
{
perror("size not received:");
exit(1);
}
childpid = fork();
if(childpid == 0)
{
time(&curtime);
sprintf( buffer, "= %s", ctime(&curtime));
n = sendto(sock_fd, buffer, sizeof(buffer),0, (struct sockaddr*)&cliaddr, sizeof(cliaddr));
if( n < 0)
{
perror("error in sending");
exit(1);
}
exit(1);
}
}
Output
server
client