/*
 * nantarad client... obtains information from nantarad, and returns 
 * the value obtained to stdout and exit value.
 * on error, returns EXIT_FAILURE on normal failure, and -1 on 
 * more obscure failures.
 *
 * originally a Telnet clone which does little input/output cooking.
 * 2001 Feb 28 Junichi Uekawa <dancer@debian.org>
 * 2001 Mar 4 Junichi Uekawa <dancer@debian.org> reuse for nantaraclient
 * copyright 2001 Junichi Uekawa
 * See GPL version 2 or later for license.
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <pthread.h>

int read_from_tcp(int * sockptr)
{
  int sock = *sockptr;
  char buf [2];
  buf[0]=-1;			/* return -1 on error */
  
  read (sock, buf, 1);
  return buf[0];  
}

int connect_to_host(char * stringaddress, int portnumber )
{
  struct sockaddr_in inet_address;
  struct hostent * hostinfo ;
  int sock;
    
  sock = socket (PF_INET, SOCK_STREAM, 0);
  
  inet_address.sin_family = AF_INET;
  inet_address.sin_port = htons(portnumber);
  hostinfo = gethostbyname(stringaddress);
  if (hostinfo == NULL)
    {
      fprintf(stderr, "Unknown host %s\n", stringaddress);
      return -1 ;      
    }
  inet_address.sin_addr = *(struct in_addr * )hostinfo->h_addr ;

  if (connect (sock,
	       (struct sockaddr *)&inet_address,
	       sizeof (inet_address))<0)
    {
      perror("connect");
      return -1 ;
    }
  return sock;  
}

int main (int ac, char ** av)
{
  int socket ;
  int return_value;
    
  if (ac != 3)
    {
      fprintf(stderr, 
	      "nantaraclient by Junichi Uekawa <dancer@debian.org>\n"
	      "Copyright 2001 Junichi Uekawa\n"
	      "See GNU Public License version 2 or later for license\n"
	      "Please give the network address, and the port number\n");
      exit (EXIT_FAILURE);
    }

  if (-1 == (socket = connect_to_host (av[1], atoi(av[2]))))
    {
      fprintf (stderr, "Connection failed \n");
      exit (EXIT_FAILURE);
    }
  return_value=read_from_tcp(&socket);
  printf ("%i\n", return_value );
  exit (return_value);
}
