/* pppmon/src/pppstat.c
 *
 * Description:
 * Get stats from pppmon and display it. Just for testing, really...
 *
 * This software is in the public domain.
 *
 * Please send all bug reports, requests for information, etc. to:
 *   Calle Karlsson
 *   KaSH Software AB
 *   calle@kash.se
 * 
 * History:
 * 950525 ckn Initial coding
 * EndHistory.
 */


#include "pppmon.h"


static int ConnectTo (char * HostName, char * Service, char * Protocol);

int
main (int argc, char ** argv)
{
   int fd;
   char * HostName = "localhost";
   DclPPPMonitorMsg PMP [1];
   struct tm * tm;

   if ((fd = ConnectTo (HostName, "pppmon", "tcp")) < 0)
   {
      printf ("Couldn't connect to %s\n", HostName);
      exit (1);
   }

   while (read (fd, PMP, sizeof (PMP)) == sizeof (PMP))
   {
      if (! PMP->Up)
      {
         printf ("[Link down]\n");
         continue;
      }
      
      tm = localtime (& PMP->Up);
      
      printf ("Up since %02d%02d%02d.%02d%02d%02d: %7.2f bps\n",
              tm->tm_year, tm->tm_mon, tm->tm_mday,
              tm->tm_hour, tm->tm_min, tm->tm_sec,
              (PMP->RBytes+PMP->SBytes) * 1000 / (float) PMP->TimeSpent);
   }

   close (fd);
   exit (0);
}


static int
ConnectTo (char * HostName, char * Service, char * Protocol)
{
   struct servent * sp;
   struct hostent * hp;
   struct sockaddr_in Addr [1];
   int fd;
   
   if (! (sp = getservbyname (Service, Protocol)))
   {
      perror ("getservbyname");
      return -1;
   }

   if ((fd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
   {
      perror ("socket");
      return -1;
   }

   if (hp = gethostbyname (HostName))
      memcpy (& Addr->sin_addr, hp->h_addr, hp->h_length);
   else
   {
      unsigned long f;
      
      if ((f = inet_addr (HostName)) < 0)
      {
         printf ("Unknown host (%s)\n", HostName);
         return(-1);
      }
      memcpy (& Addr->sin_addr, & f, sizeof (f));
   }
   Addr->sin_family = AF_INET;
   Addr->sin_port = ntohs (sp->s_port);
   
   if (connect (fd, (struct sockaddr *) Addr, sizeof (Addr)) < 0)
   {
      perror ("connect");
      return (-1);
   }

   return fd;
}
