/* small utility to find whether a network interface is up 
   give it in its first argument the name of the interface (e.g. 'eth0')
   compile: gcc -Wall isifup.c -o isifup 

   23/02/2002 - fixed tiny bug (argv[1] instead of argv[0] in call to usage())
   				and added <string.h>

   author: mulix@actcom.co.il, based on various stuff, most notably ifconfig. 
*/

#include <sys/ioctl.h>
#include <net/if.h>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

static int skfd;

void usage(const char* prog)
{
     printf("%s [interface_name]\n", prog);
     exit(EXIT_FAILURE);
}

int IsInterfaceUp(const char * if_name)
{
     
     struct ifreq req;
     
     if (!if_name || strlen(if_name)> IFNAMSIZ -1) 
	  return 0;
     
     strcpy(req.ifr_name, if_name);
     if (ioctl(skfd, SIOCGIFFLAGS, &req)<0){
	  perror("ioctl");
	  return 0;
     }
     
     
     if (req.ifr_flags & IFF_UP) 
	  return 1;
     
     return 0;
}

int FindInterface(const char * if_name)
{
     char buf[4096];
     struct ifconf ifc;
     struct ifreq* ifr;
     int  i;
     
     ifc.ifc_len = sizeof(buf);
     ifc.ifc_buf = buf;
     if (ioctl(skfd, SIOCGIFCONF, &ifc) < 0)
     {
	  perror("ioctl");
	  return 0;
     }
     ifr = ifc.ifc_req;
     for (i = ifc.ifc_len / sizeof (struct ifreq); --i >= 0; ifr++)
	  if (strcmp(ifr->ifr_name, if_name) == 0 && IsInterfaceUp(if_name)) 
	       break;
     
     if (i<0) 
	  return 0;

     return 1;
}

int main(int argc, char ** argv)
{
  if ((skfd = socket(AF_INET, SOCK_DGRAM, 0))< 0) {
       perror("socket");
       close (skfd);
       exit(EXIT_FAILURE);
  }
  
  if ((argc < 2)) {
       usage(argv[0]);
  } else {
       if (FindInterface(argv[1])) {
	    printf("Yes...'%s' interface found!\n", argv[1]);
       } else {
	    printf("Nope...  '%s' interface not found!\n", argv[1]);
       }
  }
  close (skfd);
  return EXIT_SUCCESS;
}

  
      



  

		     
	  
	    
      

  
  
