2 * getif.c : get an interface structure
4 * $FreeBSD: src/libexec/bootpd/getif.c,v 1.7 1999/08/28 00:09:18 peter Exp $
8 #include <sys/socket.h>
11 #if defined(SUNOS) || defined(SVR4)
12 #include <sys/sockio.h>
15 #include <sys/stropts.h>
18 #include <sys/time.h> /* for struct timeval in net/if.h */
19 #include <net/if.h> /* for struct ifreq */
20 #include <netinet/in.h>
36 static struct ifreq ifreq[10]; /* Holds interface configuration */
37 static struct ifconf ifconf; /* points to ifreq */
42 * Return a pointer to the interface struct for the passed address.
44 * s socket file descriptor
45 * addrp destination address on interface
48 getif(int s, struct in_addr *addrp)
52 struct ifreq *ifrq, *ifrmax;
53 struct sockaddr_in *sip;
56 /* If no address was supplied, just return NULL. */
60 /* Get the interface config if not done already. */
61 if (ifconf.ifc_len == 0) {
64 * SysVr4 returns garbage if you do this the obvious way!
65 * This one took a while to figure out... -gwr
68 ioc.ic_cmd = SIOCGIFCONF;
70 ioc.ic_len = sizeof(ifreq);
71 ioc.ic_dp = (char *) ifreq;
72 m = ioctl(s, I_STR, (char *) &ioc);
73 ifconf.ifc_len = ioc.ic_len;
74 ifconf.ifc_req = ifreq;
76 ifconf.ifc_len = sizeof(ifreq);
77 ifconf.ifc_req = ifreq;
78 m = ioctl(s, SIOCGIFCONF, (caddr_t) & ifconf);
80 if ((m < 0) || (ifconf.ifc_len <= 0)) {
81 report(LOG_ERR, "ioctl SIOCGIFCONF");
85 maxmatch = 7; /* this many bits or less... */
86 ifrmax = NULL; /* ... is not a valid match */
90 ifrq = (struct ifreq *) p;
91 sip = (struct sockaddr_in *) &ifrq->ifr_addr;
92 m = nmatch(addrp, &(sip->sin_addr));
98 /* BSD not defined or earlier than 4.3 */
101 incr = ifrq->ifr_addr.sa_len + IFNAMSIZ;
112 * Return the number of leading bits matching in the
113 * internet addresses supplied.
115 * ca, cb ptrs to IP address, network order
118 nmatch(u_char *ca, u_char *cb)
120 u_int m = 0; /* count of matching bits */
121 u_int n = 4; /* bytes left, then bitmask */
123 /* Count matching bytes. */
124 while (n && (*ca == *cb)) {
130 /* Now count matching bits. */
133 while (n && ((*ca & n) == (*cb & n))) {