c语言获取linux接口信息
时间: 2023-09-23 18:13:24 浏览: 155
要获取Linux接口信息,您可以使用以下方法之一:
1. 使用ifconfig命令:ifconfig命令可用于显示网络接口的详细信息,例如IP地址、MAC地址等。您可以在C程序中使用system()函数来调用ifconfig命令,并将其输出读取到一个字符串中。
2. 使用ioctl系统调用:ioctl系统调用可用于与设备进行通信,并获取设备的状态信息。您可以使用SIOCGIFCONF命令来获取所有接口的信息,或使用SIOCGIFADDR命令来获取特定接口的IP地址信息。以下是一个使用ioctl系统调用的示例程序:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <arpa/inet.h>
int main()
{
int fd;
struct ifconf ifc;
struct ifreq *ifr;
char buf[1024];
// 创建socket
fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) {
perror("socket");
return -1;
}
// 获取接口列表
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = buf;
if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) {
perror("ioctl");
return -1;
}
// 遍历接口列表
ifr = ifc.ifc_req;
for (int i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++) {
// 获取接口名称
char *name = ifr[i].ifr_name;
printf("Interface: %s\n", name);
// 获取接口地址
struct sockaddr_in *addr = (struct sockaddr_in *)&ifr[i].ifr_addr;
char ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &addr->sin_addr, ip, sizeof(ip));
printf("IP Address: %s\n", ip);
}
close(fd);
return 0;
}
```
阅读全文
相关推荐


















