/***********************************************************************
* Code listing from "Advanced Linux Programming," by CodeSourcery LLC  *
* Copyright (C) 2001 by New Riders Publishing                          *
* See COPYRIGHT for license information.                               *
***********************************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include "debug.h"

void write_text (int socket_fd, const char* text)
{
  /* Write the number of bytes in the string, including
     NUL-termination.  */
  int length = strlen (text) + 1;
  errlog(write (socket_fd, &length, sizeof (length)));
	
  /* Write the string.  */
  errlog(write (socket_fd, text, length));
}

int main (int argc, char* const argv[])
{
  int socket_fd;
  struct sockaddr_in name;
  struct hostent* hostinfo;

  /* Create the socket.  */
  socket_fd = socket (PF_INET, SOCK_STREAM, 0);
	errlog(socket_fd);
  
	/* Store the server's name in the socket address.  */
  name.sin_family = AF_INET;
	
  /* Convert from strings to numbers.  */
  hostinfo = gethostbyname ("127.0.0.1");
  errorlog(hostinfo,NULL);

	name.sin_addr = *((struct in_addr *) hostinfo->h_addr);
  name.sin_port = htons (9999);

	errlog(connect (socket_fd, &name, sizeof (struct sockaddr_in)));
	
  /* Retrieve the server's home page.  */
  write_text(socket_fd, argv[1]);

  return 0;
}
