Search For

TCP SOCKET(DATE AND TIME)

Flag Hide Line Nos
Flagging a Snippet, takes the snippet to Moderator Attention;


0
SERVER:
#include"netinet/in.h"
#include"sys/socket.h"#include"stdio.h"
#include"string.h"
#include"time.h"
main( )
{
struct sockaddr_in sa;
struct sockaddr_in cli;int sockfd,conntfd;int len,ch;char str[100];
time_t tick;
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0)
{
printf("error in socket\n");
exit(0);
}
else printf("Socket opened");
bzero(&sa,sizeof(sa));
sa.sin_port=htons(5600);
sa.sin_addr.s_addr=htonl(0);
if(bind(sockfd,(struct sockaddr*)&sa,sizeof(sa))<0)
{
printf("Error in binding\n");
}
else
printf("Binded Successfully");
listen(sockfd,50);
for(;;)
{
len=sizeof(ch);
conntfd=accept(sockfd,(struct sockaddr*)&cli,&len);
printf("Accepted");
tick=time(NULL);
snprintf(str,sizeof(str),"%s",ctime(&tick));
printf("%s",str);write(conntfd,str,100);
}
}



CLIENT:
#include"netinet/in.h"
#include"sys/socket.h"
#include"stdio.h"
main()
{
struct sockaddr_in sa,cli;
int n,sockfd;
int len;char buff[100];
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0){ printf("\nError in Socket");
exit(0);
}
else printf("\nSocket is Opened");
bzero(&sa,sizeof(sa));
sa.sin_family=AF_INET;
sa.sin_port=htons(5600);
if(connect(sockfd,(struct sockaddr*)&sa,sizeof(sa))<0)
{
printf("\nError in connection failed");
exit(0);
}
else
printf("\nconnected successfully");
if(n=read(sockfd,buff,sizeof(buff))<0)
{
printf("\nError in Reading");
exit(0);
}
else
{printf("\nMessage Read %s",buff);
}}


SERVER SIDE:
[shanthi@linuxserver ~]$ cc tcpcd.c
[shanthi@linuxserver ~]$ cc tcpcd.c -o ll
[shanthi@linuxserver ~]$ ./ll
Socket is Openedconnected successfully
Message Read Fri Sep 24 15:16:26 2010
[shanthi@linuxserver ~]$
CLIENT SIDE:
[shanthi@linuxserver ~]$ cc tcpd.c
[shanthi@linuxserver ~]$ cc tcpd.c -o kk
[shanthi@linuxserver ~]$ ./kk
SocketOpenedBinded SuccessfullyAccepted
Fri Sep 24 15:16:26 2010
Vote! You feel this code is working like charm ? Go a head Login and Press up arrow.
Didn't work ?, press down arrow and let us know the error in comments

Comments