时间:2022-05-25 09:42:27 | 栏目:C代码 | 点击:次
本文实例为大家分享了C语言实现linux网卡检测的精简代码,供大家参考,具体内容如下
万能的网络,通过getifaddrs可以大大减少编码量,获得 C语言实现linux网卡检测-改进版 同样的效果。
#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; }