萬能的網絡,通過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_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 \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; }