/* Alive.c 
 * Uses the echo service to determine if a remote host is alive or not.
 *
 * Copyright (c) 1997 by Ryan Kirkpatrick (rkirkpat@nag.cs.colorado.edu). 
 *   All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file COPYING.  If not, write to
 * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
 */ 

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <string.h>
#include "ClientLib/client.h"

#ifndef WAIT_TIME
#  define WAIT_TIME 1
#endif

int main(int argc, char* argv[])
{
  char *host = "localhost";
  char *service = "echo";
  int usock;
  fd_set rfds;
  int nfds;
  char buf[15];
  struct timeval tv;
  int retval;

  /* Make sure we have enough parameters. */
  if (argc < 2)
  {
    printf("Usage: alive host\n");
    exit(0);
  }

  /* Get the name of the host to check. */
  host = argv[1];

  /* Create the socket */
  usock = connectUDP(host, service);

  /* Set up the pool of sockets to watch */
  nfds = usock + 1;
  FD_ZERO(&rfds);
  FD_SET(usock,&rfds);

  /* Send the data to the host */
  write(usock, "Are You Alive?", 15);

  /* Wait a couple seconds for data to be returned. */
  tv.tv_sec = WAIT_TIME;
  tv.tv_usec = 0;
  retval = select(nfds, &rfds, (fd_set *)0, (fd_set *)0, &tv);

  /* Check the results */
  if (retval)
  {
    read(usock,buf,15);
    if (strcmp(buf,"Are You Alive?") == 0)
      printf("Alive\n");
    else
      printf("Failed\n");
  }
  else
  {
    printf("Dead\n");
  }

  return 0;
}
