Site hosted by Angelfire.com: Build your free website today!

#include<stdio.h>

#include<sys/types.h>

#include<sys/socket.h>

#include<netinet/in.h>

#include<netdb.h>

#define MAXLINE 4096

 

void error(char*);

/*The the Expression that will be sent for the server will be stored in

 sendline*/

char sendline[MAXLINE];

char c;

 

/*The structure in which the result is stored*/

struct {

            int result;

       }reply;

 

  int counter = 0;

  int main(int argc, char** argv) {

 

  /*this struct is used for geting the name of the server and converting it

   to an IP address using gethostbyname*/

  struct hostent *hp;

 

  /*The socket trough which the server will commmunicate with client*/

  int sockfd;

 

  /*the stucture for the addressof the Server*/

  struct sockaddr_in servaddr;

 

  /*we have <Executable> <Host Name> <Port Number>*/

  if(argc!=3)

 

  error("usage: a.out <Host Name> <Port Number>\n");

 

  /*we will store the IP address in hp by converting the host Name*/

  /*if the host name that is given is not valid ==> (hp==Null exit from the

    program*/

  if((hp = gethostbyname(argv[1]))==NULL)

     error("host name error");

 

  /*Create the socket */

  /*Verify if it is created ==> (sockfd>0) else print a message and exit*/

  if((sockfd = socket(AF_INET, SOCK_STREAM,0))<0)

  error("unable to open a socket\n");

 

  /*Allocate the space for the address struct*/

  bzero(&servaddr, sizeof(servaddr));

 

  /*Fill the struct*/

  servaddr.sin_family = AF_INET;

  servaddr.sin_port   = htons(atoi(argv[2]));

 

  /*copy the IP address from hp to sevaddr struct*/

  bcopy(hp->h_addr,&servaddr.sin_addr,hp->h_length);

 

  /*Connecting the Host to the Server*/

  /*verify if the connection is established ==> the value returned by

    connect>0 else print message and exit*/

  if (connect(sockfd, (struct sockaddr *)&servaddr,sizeof(servaddr))<0)

     error("connect error\n");

 

  /*Getting the Expression*/

    c =getchar();

    while(c!='\n')

     {

      sendline[counter]= c;

      counter++;

      c=getchar();

     }

 

   /*Sending the Expression to the Server*/

   send(sockfd, (char*)&sendline, sizeof(sendline),0);

 

   /*Receiving the reply from the Server*/

   recv(sockfd, (char*)&reply, sizeof(reply),0);

 

   printf("\n*****************************\n");

   printf("\nThe result: %d\n", reply.result);

   printf("\n*****************************\n");

}

 

 

 void error (char* str){

    printf("%s",str);

    exit(1);

}