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;
}

你可能感兴趣的:(C语言实现linux网卡检测-代码精简版)