C language linux network card detection compact version

  • 2020-06-07 04:59:08
  • OfStack

The example of this paper is to share the C language linux network card detection code for your reference, the specific content is as follows

Universal network, getifaddrs can greatly reduce the amount of coding, C language to achieve the same effect of linux network card detection - improved version.


#include <stdlib.h>
#include <stdio.h>
#include <string.h>
 
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <ifaddrs.h>
#include <arpa/inet.h> 
 
 
int c_ifaddrs_netlink_status(const char *if_name )
{
 struct ifaddrs *ifa = NULL, *ifList; 
 
 if (getifaddrs(&ifList) < 0)
 {
 return -1;
 }
 
 for (ifa = ifList; ifa != NULL; ifa = ifa->ifa_next) 
 {
 if(ifa->ifa_addr->sa_family == AF_INET) 
 {
  if(strcmp(ifa->ifa_name, if_name) ==0)
  {
  if(!(ifa->ifa_flags & IFF_UP))
  {
   printf("DEVICE_DOWN\r\n");
   freeifaddrs(ifList);
   return 1;
  }
 
  if(!(ifa->ifa_flags & IFF_RUNNING))
  {
   printf("DEVICE_UNPLUGGED\r\n");
   freeifaddrs(ifList);
   return 2;
  }
 
  printf("DEVICE_LINKED\r\n");
  freeifaddrs(ifList);
  return 3;
  }
 } 
 } 
 
 printf(stderr, "DEVICE_NONE\r\n");
 freeifaddrs(ifList);
 return 0;
}
 
int main(int argc, char* argv[])
{
 int i=0;
 if(argc != 2)
 {
 fprintf(stderr, "usage: %s <ethname>\r\n", argv[0]);
 return -1;
 }
 
 i = c_ifaddrs_netlink_status(argv[1]);
 
 fprintf(stderr,"c_ifaddrs_netlink_status if_status = %d\n", i );
 return 0;
}

Related articles: