[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Q:How can I determine if an if is up in C/C++ only?





Isaac Aaron wrote:

> I have this question:
> How can I determine if a network interface is up in C/C++ only?

Share && Enjoy:

/*
   ifstat - a small stupid utility to test net interfaces status
   Copyright (C) 2000  Gilad Ben-Yossef

   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.

*/

#include <errno.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <sys/types.h>
#include <sys/socket.h>


int main(int argc, char* argv[]) {

   int sock;
   struct ifreq ifr;
   short flags;

   if(argc != 2) {
     perror("Usage: ifstate ifname : ");
     exit(1);
   }

   /* "Open hailing frequencies. Jim" */

   if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
     perror("Can't get socket : ");
     exit(2);
   }

   /* "Hailing frequencies open, Captain." */


   strcpy(ifr.ifr_name, argv[1]);
   if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) {
     perror(IOCTL failed : ");
     close(sock);
     exit(3);		
   }

   flags = ifr.ifr_flags;

   if (flags & IFF_UP) {
     printf("Interface %s is up.\n", argv[1]);
   } else {
     printf("Interface %s is down.\n", argv[1]);
   }

   close(sock);

   return 0;
}


-- 
Gilad Ben-Yossef <gilad@benyossef.com>
http://benyossef.com :: +972(54)756701
"Anything that can go wrong, will go wrong, while interrupts are disabled. "
	-- Murphey's law of kernel programing.


=================================================================
To unsubscribe, send mail to linux-il-request@linux.org.il with
the word "unsubscribe" in the message body, e.g., run the command
echo unsubscribe | mail linux-il-request@linux.org.il