/* daytimetcpcli.c - From Stevens, Network Programming Vol. 1
                     with minor changes.
		     Compile with
		          % gcc -o client daytimetcpcli.c
                     Run with
		          % client [hostname [portid]]
		     We use the localhost and port 5000 by default.
 */

#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>  /* basic system data types */
#include <sys/socket.h> /* basic socket definitions */
#include <sys/time.h>   /* timeval{} for select() */
#include <time.h>       /* timespec{} for pselect() */
#include <netinet/in.h> /* sockaddr_in{} and other Internet defns */
#include <netdb.h>      /* needed by gethostbyname */
#include <arpa/inet.h>  /* needed by inet_ntoa */

int
main(int argc, char **argv)
{
  int			sockfd;
  int                   n;
  char			recvline[128 + 1];
  struct sockaddr_in	servaddr;
  unsigned short        port;
  char *                hostname;
  struct hostent *      hp;

  hostname = (argc > 1) ? argv[1] : "localhost"; 
  port = (argc > 2) ? atoi(argv[2]) : 5000;
  if ( (hp = gethostbyname(hostname) ) == 0) {
    perror("gethostbyname");
    exit(0);
  }

  if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    perror("socket");
    exit(1);
  }

  bzero((char *)&servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_port   = htons(port);

  memcpy(&servaddr.sin_addr, hp->h_addr, hp->h_length);
  if (servaddr.sin_addr.s_addr <= 0) {
    perror("bad address after gethostbyname");
    exit(1);
  }
  
  if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
    perror("connect");
    exit(1);
  }
  
  while ( (n = read(sockfd, recvline, sizeof(recvline)-1)) > 0) {
    recvline[n] = 0;	/* null terminate */
    if (fputs(recvline, stdout) == EOF) {
      perror("fputs");
      exit(1);
    }
  }
  if (n < 0) {
    perror("read");
    exit(1);
  }
  exit(0);
}
