一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

C语言实现linux网卡检测精简版

时间:2018-07-06 编辑:猪哥 来源:一聚教程网

本文实例为大家分享了C语言实现linux网卡检测的精简代码,供大家参考,具体内容如下

万能的网络,通过getifaddrs可以大大减少编码量,获得 C语言实现linux网卡检测-改进版 同样的效果。

#include 
#include 
#include 
 
#include 
#include 
#include 
#include 
#include  
 
 
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_DOWNrn");
   freeifaddrs(ifList);
   return 1;
  }
 
  if(!(ifa->ifa_flags & IFF_RUNNING))
  {
   printf("DEVICE_UNPLUGGEDrn");
   freeifaddrs(ifList);
   return 2;
  }
 
  printf("DEVICE_LINKEDrn");
  freeifaddrs(ifList);
  return 3;
  }
 } 
 } 
 
 printf(stderr, "DEVICE_NONErn");
 freeifaddrs(ifList);
 return 0;
}
 
int main(int argc, char* argv[])
{
 int i=0;
 if(argc != 2)
 {
 fprintf(stderr, "usage: %s rn", argv[0]);
 return -1;
 }
 
 i = c_ifaddrs_netlink_status(argv[1]);
 
 fprintf(stderr,"c_ifaddrs_netlink_status if_status = %dn", i );
 return 0;
}

热门栏目