如何在 FreeBSD 中枚举 C 或 C++ 中的网络设备或接口列表?
我想要一个像“ue0”、“ath0”、“wlan0”这样的列表。
我一直在查看 ifconfig(1) 代码,但根本不清楚任务在哪里执行。
我很乐意接受答案、指向手册页的指针或指向 ifconfig 中相应行的链接。我可能只是错过了。
getifaddrs API 获取接口地址。男人 getifaddrs
您还可以使用ioctl来获取网络接口。
代码:
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <stdio.h>
#include <arpa/inet.h>
int main(void)
{
char buf[1024];
struct ifconf ifc;
struct ifreq *ifr;
int sck;
int nInterfaces;
int i;
/* Get a socket handle. */
sck = socket(AF_INET, SOCK_DGRAM, 0);
if(sck < 0)
{
perror("socket");
return 1;
}
/* Query available interfaces. */
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = buf;
if(ioctl(sck, SIOCGIFCONF, &ifc) < 0)
{
perror("ioctl(SIOCGIFCONF)");
return 1;
}
/* Iterate through the list of interfaces. */
ifr = ifc.ifc_req;
nInterfaces = ifc.ifc_len / sizeof(struct ifreq);
for(i = 0; i < nInterfaces; i++)
{
struct ifreq *item = &ifr[i];
/* Show the device name and IP address */
printf("%s: IP %s",
item->ifr_name,
inet_ntoa(((struct sockaddr_in *)&item->ifr_addr)->sin_addr));
/* Get the broadcast address (added by Eric) */
if(ioctl(sck, SIOCGIFBRDADDR, item) >= 0)
printf(", BROADCAST %s", inet_ntoa(((struct sockaddr_in *)&item->ifr_broadaddr)->sin_addr));
printf("\n");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
lo: IP 127.0.0.1, BROADCAST 0.0.0.0
eth0: IP 192.168.1.9, BROADCAST 192.168.1.255
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2663 次 |
| 最近记录: |