/* Simple TCP client example */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 
#include <unistd.h>

void error(char *msg)
{
  perror(msg);
  exit(1);
}

#define MAXIN  1024
#define MAXOUT 4096

int main(int argc, char *argv[])
{
    int sockfd, portno, n;
    struct sockaddr_in serv_addr;
    struct hostent *server;

    char inbuf[MAXIN];
    char outbuf[MAXOUT];

    if (argc < 3) {
       fprintf(stderr,"usage %s hostname port\n", argv[0]);
       exit(0);
    }
    portno = atoi(argv[2]);

    /* Get host entry associated with a hostname or IP address */
    server = gethostbyname(argv[1]); 
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(1);
    }

    /* Construct an address for remote server */
    memset((char *) &serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, 
	  (char *)&serv_addr.sin_addr.s_addr,
	  server->h_length);
    serv_addr.sin_port = htons(portno);

    /* Create a TCP socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        error("ERROR opening socket");
    }

    /* Connect to server on port */
    if (connect(sockfd, 
		(struct sockaddr *) &serv_addr, 
		sizeof(serv_addr)) < 0) 
        error("ERROR connecting");

    printf("Connected to %s:%d\n",server->h_name,portno);

    /* Get character stream to send */
    printf("enter message: ");
    memset(inbuf,0,MAXIN);
    fgets(inbuf,MAXIN,stdin);

    /* Write char stream to socket */
    n = write(sockfd,inbuf,strlen(inbuf));
    if (n < 0) error("ERROR writing to socket");
    
    /* Read response from the scoket */
    memset(outbuf,0,MAXOUT);
    n = read(sockfd,outbuf,MAXOUT-1);
    if (n < 0) error("ERROR reading from socket");

    printf("%s\n",outbuf);
    close(sockfd);
    return 0;
}