Linux下C语言获取网卡信息(IPv4)
getifaddrs
、freeifaddrs
ioctl
getifaddrs
、freeifaddrs
getifaddr
==> get interface address
它将创建一个描述本地网络接口的链表
#include <sys/types.h>
#include <ifaddrs.h>
int getifaddrs(struct ifaddrs **ifap);
The getifaddrs() function creates a linked list of structures describing the network interfaces of the local system, and stores the address of the first item of the list in *ifap.
这里涉及了一个结构体:ifaddrs
,即interface address
,是一个链表结构,声明如下:
struct ifaddrs
{
struct ifaddrs *ifa_next; /* Pointer to the next structure. */
char *ifa_name; /* Name of this network interface. */
unsigned int ifa_flags; /* Flags as from SIOCGIFFLAGS ioctl. */
struct sockaddr *ifa_addr; /* Network address of this interface. */
struct sockaddr *ifa_netmask; /* Netmask of this interface. */
union
{
struct sockaddr *ifu_broadaddr; /* Broadcast address of this interface. */
struct sockaddr *ifu_dstaddr; /* Point-to-point destination address. */
} ifa_ifu;
#define ifa_broadaddr ifa_ifu.ifu_broadaddr
#define ifa_dstaddr ifa_ifu.ifu_dstaddr
void *ifa_data; /* Address-specific data (may be unused). */
};
其中,ifa_name
存储了网络接口的名字——即网卡的名字
使用freeifaddrs
来释放该链表