/*  Test distributed client program in C++.  */

/*  This program sends a simple packet to the host and port specified on

    the command line.  It waits for a return and then prints the result.*/

#include <iostream>

#include <stdlib.h>

#include <sys/types.h>

#include <windows.h>

#include <winsock.h>

#include <memory.h>

using namespace std;

 

/* size of input buffer */                     

#define       INSIZE  128         

 

void main(int argc, char *argv[])   {

      char tpkt[22] = "tclient test message";  /* message to send to host */

      char servername[80];                     /* pointer to name of server */

      struct hostent *h;                       /* getnamebyhost info returned */

      struct sockaddr_in sa;                   /* socket address */

      int soxdes;                              /* socket descriptor */

      short  portnum;                          /* port number of server */

      int funcstatus;                          /* status from socket funcs */

      int inlen;                               /* length of input message */

      char inbuf[INSIZE];                      /* input message buffer */

      WSADATA wsaData;                         /* Winsock parameters */

 

      WSAStartup( 0x0101, &wsaData);

      /* ask for the server name and port */

      cout << "\nEnter the IP name of the server >";

      cin  >> servername;

      cout << "\nEnter the port number used by the server >";

      cin  >> portnum;

      /* get host address */

      h = gethostbyname(servername);

      if (h == NULL) {

            cout << "gethostbyname error";

            exit(0);

      }

      /*  build socket structure  */

      memcpy((char *)&sa.sin_addr,(char *)h->h_addr, h->h_length);

      sa.sin_family = h->h_addrtype;

      sa.sin_port = htons(portnum);

      /*  allocate an open socket */

      soxdes = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

      if (soxdes == -1) {

            cout << "socket creation error";

            exit(0);

      } else {

            cout << "socket created\n";

      }

      /*  connect to the server */

      if (connect(soxdes, (struct sockaddr *)&sa, sizeof sa) < 0) {

            cout << "connect error";

            exit(0);

      }

      cout << "connected\n" << endl;

      /* send a packet to the server */

      funcstatus = send(soxdes, tpkt, strlen(tpkt)+1, 0 );

      if (funcstatus == -1) {

            cout << "Error sending data to server\n";

            exit(0);

      }

      cout << "packet sent to server\n";

      /* wait for a reply */

      inlen = recv(soxdes, inbuf, INSIZE, 0);

      if (inlen < 0) {

            cout << "Error receiving data from the server\n";

      } else {

            cout << inlen << " byte reply from server" << inbuf;

      }

      WSACleanup();

}