我需要获取有关FreeBSD主机(位于VirtualBox上)上所有已连接网络接口的信息。我使用了StackOverflow上的代码段。在Linux上,它运行良好,但是在FreeBSD上,发生了一些奇怪的事情。 这是我使用的代码:
#include <unistd.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <stdio.h>
#include <arpa/inet.h>
int main(void)
{
char buf[8096];
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;
write(2, ifr, ifc.ifc_len);
nInterfaces = ifc.ifc_len / sizeof(struct ifreq);
printf("%d\n", nInterfaces);
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;
}
Linux上的输出是:
3
lo: IP 127.0.0.1, BROADCAST 0.0.0.0
wlxf4f26d1cdfaf: IP 192.168.1.123, BROADCAST 192.168.1.255
vboxnet0: IP 192.168.56.1, BROADCAST 192.168.56.255
在FreeBSD上,输出为:
9
em0: IP 6.3.6.0, BROADCAST 192.168.56.255
�: IP 0.0.0.0
: IP 0.0.0.0
: IP 0.0.0.0
lo0: IP 0.0.0.0
: IP 0.0.0.0
: IP 0.0.0.1
: IP 254.128.0.2
: IP 0.0.0.0
以下是FreeBSD上ifconfig的输出:
em0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
options=81009b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM,VLAN_HWFILTER>
ether 08:00:27:5f:63:c7
inet 192.168.56.101 netmask 0xffffff00 broadcast 192.168.56.255
media: Ethernet autoselect (1000baseT <full-duplex>)
status: active
nd6 options=29<PERFORMNUD,IFDISABLED,AUTO_LINKLOCAL>
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> metric 0 mtu 16384
options=680003<RXCSUM,TXCSUM,LINKSTATE,RXCSUM_IPV6,TXCSUM_IPV6>
inet6 ::1 prefixlen 128
inet6 fe80::1%lo0 prefixlen 64 scopeid 0x2
inet 127.0.0.1 netmask 0xff000000
groups: lo
nd6 options=21<PERFORMNUD,AUTO_LINKLOCAL>