/* ifup.c - Copyright (C) 1999 Pat Thoyts <pat@zsplat.freeserve.co.uk>
 *
 * return true (1) if interface is up, 0 if it's down.
 *
 * This is designed to be used from a script to watch for a ppp connection
 * going down.
 */

/*

  Copyright (C) 1999 Pat Thoyts <pat@zsplat.freeserve.co.uk>

  This 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, 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.

*/

static const char rcs_id[] = 
"@(#)$Id: ifup.c,v 1.1 1999/05/05 10:29:51 pat Exp $";

#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <net/if.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#ifdef NEED_BASENAME /* linux string.h defines basename */
const char* basename ( const char* s);
#endif

int
main (int argc, char** argv)
{
  int s, r, up;
  struct ifreq f;

  if (argc < 2 || argv[1] == NULL || argv[1][0] == 0) {
    fprintf(stderr, "usage: %s [-h] <interface name>\n", basename(argv[0]));
    exit(-1);
  }

  if (!strncmp(argv[1], "-h", 3) ||
      !strncmp(argv[1], "-help", 5) ||
      !strncmp(argv[1], "--help", 7)) {
    fprintf(stderr, "usage: %s [-h] <interface name>\n", basename(argv[0]));
    exit(-1);
  }

  s = socket(PF_INET, SOCK_DGRAM, 0);
  if (s < 0) {
    perror("socket");
    exit(-1);
  }

  memset(&f, 0, sizeof(f));
  strncpy(f.ifr_name, argv[1], IFNAMSIZ); /* set the interface */

  r = ioctl(s, SIOCGIFFLAGS, &f);
  if (r < 0) {
    perror("ioctl");
    exit(-1);
  }

  up = (short int)f.ifr_flags & IFF_UP;

  return up;
}

#ifdef NEED_BASENAME
const char*
basename ( const char* s)
{
  char * p;
  p = strrchr(s, '/');
  if (p == NULL)
    return s;
  else
    return p;
}
#endif
