Saturday 13 February 2016

Simple Server-Client TCP Socket Program | Linux Socket Programming (Computer Networks)

Simple Server-Client TCP Socket Program | Linux Socket Programming (Computer Networks)
Description:    A basic TCP/IP based program to print a line. Client sends the “Hello. This is the client” message to the server and the server prints the message sent by the client.    

C TCP Server Code

#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>

int main(int argc, char**argv)
{
   int listenfd,connfd,n;
   struct sockaddr_in servaddr,cliaddr;
   socklen_t clilen;
   pid_t childpid;
   char mesg[1000];

   listenfd=socket(AF_INET,SOCK_STREAM,0);

   bzero(&servaddr,sizeof(servaddr));
   servaddr.sin_family = AF_INET;
   servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
   servaddr.sin_port=htons(8899);
   bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr));

   listen(listenfd,1024);

   clilen=sizeof(cliaddr);
   connfd = accept(listenfd,(struct sockaddr *)&cliaddr, &clilen);

   close (listenfd);

   n = recvfrom(connfd,mesg,1000,0,(struct sockaddr *)&cliaddr, &clilen);
   mesg[n] = '\0';
           
   printf("%s\n",mesg);
      
   close(connfd);
  
}


C TCP Client Code

#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>

int main(int argc, char**argv)
{
   int sockfd,n;
   struct sockaddr_in servaddr,cliaddr;
   char sendline[1000];
   char recvline[1000];

   sockfd=socket(AF_INET,SOCK_STREAM,0);

   bzero(&servaddr,sizeof(servaddr));
   servaddr.sin_family = AF_INET;
   servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
   servaddr.sin_port=htons(8899);

   connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));

   strcpy(sendline,"Hello. This is the client");
   sendto(sockfd,sendline,strlen(sendline),0,(struct sockaddr *)&servaddr,sizeof(servaddr));
    
}


No comments

Post a Comment

Recent Posts