Thursday, May 28, 2009

Basic socket programming (TCP)

Sockets are end points on a machine for communication.

Below code demonstatres connection oriented program (TCP).

Client:
#include following libraries stdio.h, sys/socket.h, sys/types.h, netinet/in.h, netdb.h
int main(int argc,char **argv)
{
  int sockfd,newsockfd;  // socket descriptors 
  struct sockaddr_in serv_addr;
  struct hostent *he;
  char a[50],a1[50];
  sockfd=socket(AF_INET,SOCK_STREAM,0); // creates a socket
  if(sockfd<0)
  {
   printf("Socket failed");
   exit(0);
  }
// Use either green or yellow code, if you want to give server name as command line argument use the green one. 
  if((he=gethostbyname(argv[2]))==NULL)  // gets the ip address
  {
  printf("gethost error");
  exit(1);
  }
  serv_addr.sin_family=AF_INET;
  serv_addr.sin_addr.s_addr=inet_addr("127.127.127.1");
  memcpy(&(serv_addr.sin_addr),he->h_addr,he->h_length);
  serv_addr.sin_port=htons(atoi(argv[1])); 
  if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)
  {
   printf("\nConnection failed");
   exit(0);
  }
  printf("\nEnter a Message");
  scanf("%s",&a);
  write(sockfd,a,50);
  read(sockfd,a1,50);
  printf("\nClient received Message %s",a1);
  close(sockfd); // closing the socket descriptor
}


Server: 
#include following libraries stdio.h, sys/socket.h, sys/types.h, netinet/in.h
int main(int argc,char **argv)
{
  int sockfd,newsockfd,clilen;
  struct sockaddr_in serv_addr,cli_addr;
  char a[50];
  sockfd=socket(AF_INET,SOCK_STREAM,0);
  if(sockfd<0)
  {
   printf("\nSocket failed!");
   exit(0);
  }
  serv_addr.sin_family=AF_INET;
  serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
  serv_addr.sin_port=htons(atoi(argv[1]));
  if(bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)
  {
   printf("\nBind failed");
   exit(1);
  }
  if(listen(sockfd,5)<0)
  {
   printf("\nListen fails");
   exit(0);
  }
  clilen=sizeof(cli_addr);
  newsockfd=accept(sockfd,(struct sockaddr *)&cli_addr,&clilen);
  read(newsockfd,a,80);
  printf("Server received %s",a);
  write(newsockfd,"Server received message",26);
  close(newsockfd);
  close(sockfd);
}


compilation:
client :   gcc -o client client.c
server :   gcc -o server server.c

Execution:
server : ./server (portno)
client : ./client (portno) (servername)

Communication between client and server.


Client side:
client creates a socket and sends a request to server

Server side:
  1. Server creates a socket and waiting for a request.
  2. when request arrives to server socket then it creates a new socket and forward the request to that new socket. 
  3. Further communication is goes on in between client's socket and server's new socket.

No comments: