#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#if defined(SUNOS) || defined(SVR4)
#include <sys/sockio.h>
#endif
#ifdef SVR4
#include <sys/stropts.h>
#endif
#include <sys/time.h>
#include <net/if.h>
#include <netinet/in.h>
#ifndef NO_UNISTD
#include <unistd.h>
#endif
#include <syslog.h>
#include <errno.h>
#include <assert.h>
#include "getif.h"
#include "report.h"
#ifdef __bsdi__
#define BSD 43
#endif
static struct ifreq ifreq[10];
static struct ifconf ifconf;
static int nmatch(u_char *ca, u_char *cb);
struct ifreq *
getif(int s, struct in_addr *addrp)
{
int maxmatch;
int len, m, incr;
struct ifreq *ifrq, *ifrmax;
struct sockaddr_in *sip;
char *p;
if (!addrp)
return (struct ifreq *) 0;
if (ifconf.ifc_len == 0) {
#ifdef SVR4
struct strioctl ioc;
ioc.ic_cmd = SIOCGIFCONF;
ioc.ic_timout = 0;
ioc.ic_len = sizeof(ifreq);
ioc.ic_dp = (char *) ifreq;
m = ioctl(s, I_STR, (char *) &ioc);
ifconf.ifc_len = ioc.ic_len;
ifconf.ifc_req = ifreq;
#else
ifconf.ifc_len = sizeof(ifreq);
ifconf.ifc_req = ifreq;
m = ioctl(s, SIOCGIFCONF, (caddr_t) & ifconf);
#endif
if ((m < 0) || (ifconf.ifc_len <= 0)) {
report(LOG_ERR, "ioctl SIOCGIFCONF");
return (struct ifreq *) 0;
}
}
maxmatch = 7;
ifrmax = (struct ifreq *) 0;
p = (char *) ifreq;
len = ifconf.ifc_len;
while (len > 0) {
ifrq = (struct ifreq *) p;
sip = (struct sockaddr_in *) &ifrq->ifr_addr;
m = nmatch((u_char *)addrp, (u_char *)&(sip->sin_addr));
if (m > maxmatch) {
maxmatch = m;
ifrmax = ifrq;
}
#ifndef IFNAMSIZ
incr = sizeof(*ifrq);
#else
incr = ifrq->ifr_addr.sa_len + IFNAMSIZ;
#endif
p += incr;
len -= incr;
}
return ifrmax;
}
static int
nmatch(u_char *ca, u_char *cb)
{
u_int m = 0;
u_int n = 4;
while (n && (*ca == *cb)) {
ca++;
cb++;
m += 8;
n--;
}
if (n) {
n = 0x80;
while (n && ((*ca & n) == (*cb & n))) {
m++;
n >>= 1;
}
}
return (m);
}