DISPLAYING DATE AND TIME USING UDP
By karthick
, in
DISPLAYING DATE AND TIME USING UDP
,
3 Comments
Server program
#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
#include
<sys/socket.h>
#include
<sys/types.h>
#include
<netinet/in.h>
#include
<time.h>
int
main()
{
int
sfd,r,bi,port;
char
buff[1024];
struct
sockaddr_in servaddr,cliaddr;
socklen_t
clilen;
sfd=socket(AF_INET,SOCK_DGRAM,0);
if(sfd==-1)
{
perror("Socket");
return
0;
}
printf("\n
Enter the port no:");
scanf("%d",&port);
printf("The
port no is:%d\n",port);
servaddr.sin_family
= AF_INET;
servaddr.sin_port
= htons(port);
servaddr.sin_addr.s_addr
= INADDR_ANY;
bi=bind(sfd,(struct
sockaddr*)&servaddr,sizeof(servaddr));
if(bi==-1)
{
perror("Bind()");
return
0;
}
clilen
= sizeof(cliaddr);
r=recvfrom(sfd,buff,sizeof(buff),0,(struct
sockaddr*)&cliaddr,&clilen);
buff[r]=0;
time_t
ticks;
ticks
= time(NULL);
snprintf(buff,sizeof(buff),"%24s\r\n",ctime(&ticks));
sendto(sfd,buff,sizeof(buff),0,(struct
sockaddr*)&cliaddr,sizeof(cliaddr));
exit(0);
return
0;
}
Client program
#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
#include
<sys/socket.h>
#include
<sys/types.h>
#include
<netinet/in.h>
int
main()
{
int
listenfd,port,r;
char
buff[1024];
struct
sockaddr_in servaddr,cliaddr;
socklen_t
servlen;
listenfd
= socket(AF_INET,SOCK_DGRAM,0);
if(listenfd==-1)
{
perror("Socket");
return
0;
}
printf("\n
Enter the port no:");
scanf("%d",&port);
printf("The
port no is:%d",port);
servaddr.sin_family
= AF_INET;
servaddr.sin_port
= htons(port);
servaddr.sin_addr.s_addr
= INADDR_ANY;
sendto(listenfd,buff,sizeof(buff),0,(struct
sockaddr*)&servaddr,sizeof(servaddr));
r=recvfrom(listenfd,buff,sizeof(buff),0,(struct
sockaddr*)&servaddr,&servlen);
buff[r]=0;
printf("\n
The time received from the server:%s\n",buff);
exit(0);
return
0;
}
OUTPUT
SERVER
[11ca013@mcalinux
network]$ cc 3udpser.c
[11ca013@mcalinux
network]$ ./a.out
Enter the port no:8686
The
port no is:8686
CLIENT
[11ca013@mcalinux
network]$ cc 3udpcli.c
[11ca013@mcalinux
network]$ ./a.out
Enter
the port no:8686
The
port no is:8686
The time received from the server: Thu Feb 14
14:16:44 2013
Thank you sir.
r,bi ?