Linux下C语言获取网卡信息(IPv4)

本文介绍了如何在Linux环境下使用C语言获取网卡的IPv4地址和MAC地址信息。通过结合和系统调用,可以克服单独使用或的局限性,实现完整获取网络接口详情。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Linux下C语言获取网卡信息(IPv4)

  1. getifaddrsfreeifaddrs
  2. ioctl

getifaddrsfreeifaddrs

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来释放该链表

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值