#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
 
int main(int argc, char **argv)
{
  struct sockaddr_in sock_addr;
  int sockfd;
  
  fprintf(stdout,"Client: creating socket\n");
  sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
 
  if (sockfd == -1) {
    perror("socket()");
    exit(1);
  }
 
  fprintf(stdout,"Client: preparing server address\n");
  memset(&sock_addr, 0, sizeof(sock_addr));
  sock_addr.sin_family = AF_INET;
  sock_addr.sin_port = htons(1234);
  if (inet_pton(AF_INET, " localhost", &sock_addr.sin_addr) < 0) {
    perror("inet_pton()");
    close(sockfd);
    exit(1);
  }
 
  fprintf(stdout,"Client: connecting to the server\n");
  if (connect(sockfd, (const void *)&sock_addr, sizeof(sock_addr)) == -1) {
    perror("connect()");
    close(sockfd);
    exit(1);
  }
 
  char buffer[128];

  fprintf(stdout,"Client: writing to the socked\n");
  sprintf(buffer,"hello there");
  if (write(sockfd, buffer, 1+strlen(buffer))  == -1) {
    perror("write()");
    close(sockfd);
    exit(1);
  }

  fprintf(stdout,"Client: reading from the socked\n");
  if (read(sockfd, buffer, 128)  == -1) {
    perror("read()");
    close(sockfd);
    exit(1);
  }
  fprintf(stdout,"Client: received reply: '%s'\n",buffer);
 
 
  fprintf(stdout,"Client: shutting down socket\n");
  if (shutdown(sockfd, SHUT_RDWR) == -1) {
    perror("shutdown()");
    close(sockfd);
    exit(1);
  }
 
  close(sockfd);
  exit(0);
}
