如何在FreeBSD中枚举C或C ++中的网络设备或接口列表?
我想要一个类似" ue0"," ath0"," wlan0"的列表。
我一直在查看ifconfig(1)代码,但根本不清楚任务执行的位置。
我很乐意接受一个回答,指向手册页的指针,或指向ifconfig中相应行的链接。我可能错过了它。
答案 0 :(得分:4)
getifaddrs
API获取接口地址。 man 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;
}
输出:
lo: IP 127.0.0.1, BROADCAST 0.0.0.0
eth0: IP 192.168.1.9, BROADCAST 192.168.1.255