Make the interface code more portable.

It turns out SIOCGIFINDEX isn't (readily?) available in BSD, but
if_nametoindex() is defined by posix, so use that instead.
This commit is contained in:
Bill Currie 2011-08-16 10:03:43 +09:00
parent 4cec4b9f96
commit 53049e33eb

View file

@ -132,7 +132,7 @@ get_iface_list (int sock)
#ifdef HAVE_GETIFADDRS #ifdef HAVE_GETIFADDRS
struct ifaddrs *ifa_head; struct ifaddrs *ifa_head;
struct ifaddrs *ifa; struct ifaddrs *ifa;
struct ifreq ifreq; int index;
if (getifaddrs (&ifa_head) < 0) if (getifaddrs (&ifa_head) < 0)
goto no_ifaddrs; goto no_ifaddrs;
@ -141,26 +141,20 @@ get_iface_list (int sock)
continue; continue;
if (!ifa->ifa_addr || ifa->ifa_addr->sa_family != AF_INET) if (!ifa->ifa_addr || ifa->ifa_addr->sa_family != AF_INET)
continue; continue;
strncpy (ifreq.ifr_name, ifa->ifa_name, IFNAMSIZ); index = if_nametoindex (ifa->ifa_name);
ifreq.ifr_name[IFNAMSIZ - 1] = 0; if (index > num_ifaces)
ioctl (sock, SIOCGIFINDEX, (char*) &ifreq); num_ifaces = index;
if (ifreq.ifr_ifindex > num_ifaces)
num_ifaces = ifreq.ifr_ifindex;
} }
ifaces = malloc (num_ifaces * sizeof (uint32_t)); ifaces = malloc (num_ifaces * sizeof (uint32_t));
Sys_MaskPrintf (SYS_NET, "%d interfaces\n", num_ifaces); Sys_MaskPrintf (SYS_NET, "%d interfaces\n", num_ifaces);
for (ifa = ifa_head; ifa; ifa = ifa->ifa_next) { for (ifa = ifa_head; ifa; ifa = ifa->ifa_next) {
int index;
struct sockaddr_in *sa; struct sockaddr_in *sa;
if (!ifa->ifa_flags & IFF_UP) if (!ifa->ifa_flags & IFF_UP)
continue; continue;
if (!ifa->ifa_addr || ifa->ifa_addr->sa_family != AF_INET) if (!ifa->ifa_addr || ifa->ifa_addr->sa_family != AF_INET)
continue; continue;
strncpy (ifreq.ifr_name, ifa->ifa_name, IFNAMSIZ); index = if_nametoindex (ifa->ifa_name) - 1;
ifreq.ifr_name[IFNAMSIZ - 1] = 0;
ioctl (sock, SIOCGIFINDEX, (char*) &ifreq);
index = ifreq.ifr_ifindex - 1;
sa = (struct sockaddr_in *) ifa->ifa_addr; sa = (struct sockaddr_in *) ifa->ifa_addr;
memcpy (&ifaces[index], &sa->sin_addr, sizeof (uint32_t)); memcpy (&ifaces[index], &sa->sin_addr, sizeof (uint32_t));
Sys_MaskPrintf (SYS_NET, " %-10s %s\n", ifa->ifa_name, Sys_MaskPrintf (SYS_NET, " %-10s %s\n", ifa->ifa_name,