1 /* $NetBSD: getif.c,v 1.5 2002/07/14 00:26:17 wiz Exp $ */
5 __RCSID("$NetBSD: getif.c,v 1.5 2002/07/14 00:26:17 wiz Exp $");
9 * getif.c : get an interface structure
12 #include <sys/types.h>
13 #include <sys/socket.h>
14 #include <sys/ioctl.h>
15 #include <sys/param.h>
17 #if defined(SUNOS) || defined(SVR4)
18 #include <sys/sockio.h>
21 #include <sys/stropts.h>
24 #include <net/if.h> /* for struct ifreq */
25 #include <netinet/in.h>
41 static struct ifreq ifreq
[10]; /* Holds interface configuration */
42 static struct ifconf ifconf
; /* points to ifreq */
44 static int nmatch(u_char
*, u_char
*);
46 /* Return a pointer to the interface struct for the passed address. */
48 getif(int s
, struct in_addr
*addrp
)
49 /* socket file descriptor */
50 /* destination address on interface */
54 struct ifreq
*ifrq
, *ifrmax
;
55 struct sockaddr_in
*sip
;
58 /* If no address was supplied, just return NULL. */
60 return (struct ifreq
*) 0;
62 /* Get the interface config if not done already. */
63 if (ifconf
.ifc_len
== 0) {
66 * SysVr4 returns garbage if you do this the obvious way!
67 * This one took a while to figure out... -gwr
70 ioc
.ic_cmd
= SIOCGIFCONF
;
72 ioc
.ic_len
= sizeof(ifreq
);
73 ioc
.ic_dp
= (char *) ifreq
;
74 m
= ioctl(s
, I_STR
, (char *) &ioc
);
75 ifconf
.ifc_len
= ioc
.ic_len
;
76 ifconf
.ifc_req
= ifreq
;
78 ifconf
.ifc_len
= sizeof(ifreq
);
79 ifconf
.ifc_req
= ifreq
;
80 m
= ioctl(s
, SIOCGIFCONF
, (caddr_t
) & ifconf
);
82 if ((m
< 0) || (ifconf
.ifc_len
<= 0)) {
83 report(LOG_ERR
, "ioctl SIOCGIFCONF");
84 return (struct ifreq
*) 0;
87 maxmatch
= 7; /* this many bits or less... */
88 ifrmax
= (struct ifreq
*) 0;/* ... is not a valid match */
92 ifrq
= (struct ifreq
*) p
;
93 if (ifrq
->ifr_addr
.sa_family
== AF_INET
) {
94 sip
= (struct sockaddr_in
*) &ifrq
->ifr_addr
;
95 m
= nmatch((u_char
*)addrp
, (u_char
*)&(sip
->sin_addr
));
101 /* XXX - Could this be just #ifndef IFNAMSIZ instead? -gwr */
103 /* BSD not defined or earlier than 4.3 */
104 incr
= sizeof(*ifrq
);
106 incr
= ifrq
->ifr_addr
.sa_len
+ IFNAMSIZ
;
117 * Return the number of leading bits matching in the
118 * internet addresses supplied.
121 nmatch(u_char
*ca
, u_char
*cb
)
122 /* ptrs to IP address, network order */
124 u_int m
= 0; /* count of matching bits */
125 u_int n
= 4; /* bytes left, then bitmask */
127 /* Count matching bytes. */
128 while (n
&& (*ca
== *cb
)) {
134 /* Now count matching bits. */
137 while (n
&& ((*ca
& n
) == (*cb
& n
))) {
149 * c-argdecl-indent: 4
150 * c-continued-statement-offset: 4
151 * c-continued-brace-offset: -4