route utils: Recognize IFT_CARP link layer address
[dragonfly.git] / usr.sbin / arp / arp.c
1 /*
2  * Copyright (c) 1984, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Sun Microsystems, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * @(#) Copyright (c) 1984, 1993 The Regents of the University of California.  All rights reserved.
37  * @(#)from: arp.c      8.2 (Berkeley) 1/2/94
38  * $FreeBSD: src/usr.sbin/arp/arp.c,v 1.22.2.12 2003/04/16 10:02:37 ru Exp $
39  * $DragonFly: src/usr.sbin/arp/arp.c,v 1.11 2008/02/03 00:41:44 swildner Exp $
40  */
41
42 /*
43  * arp - display, set, and delete arp table entries
44  */
45
46
47 #include <sys/param.h>
48 #include <sys/file.h>
49 #include <sys/socket.h>
50 #include <sys/sockio.h>
51 #include <sys/sysctl.h>
52 #include <sys/ioctl.h>
53 #include <sys/time.h>
54
55 #include <net/if.h>
56 #include <net/if_dl.h>
57 #include <net/if_types.h>
58 #include <net/route.h>
59
60 #include <netinet/in.h>
61 #include <netinet/if_ether.h>
62
63 #include <arpa/inet.h>
64
65 #include <ctype.h>
66 #include <err.h>
67 #include <errno.h>
68 #include <netdb.h>
69 #include <nlist.h>
70 #include <paths.h>
71 #include <stdio.h>
72 #include <stdlib.h>
73 #include <string.h>
74 #include <unistd.h>
75
76 void search(u_long addr, void (*action)(struct sockaddr_dl *sdl,
77         struct sockaddr_inarp *sin, struct rt_msghdr *rtm));
78 void print_entry(struct sockaddr_dl *sdl,
79         struct sockaddr_inarp *addr, struct rt_msghdr *rtm);
80 void nuke_entry(struct sockaddr_dl *sdl,
81         struct sockaddr_inarp *addr, struct rt_msghdr *rtm);
82 int delete(char *host, char *info);
83 void usage(void);
84 int set(int argc, char **argv);
85 int get(char *host);
86 int file(char *name);
87 void getsocket(void);
88 int my_ether_aton(char *a, struct ether_addr *n);
89 int rtmsg(int cmd);
90 int get_ether_addr(u_int32_t ipaddr, struct ether_addr *hwaddr);
91
92 static int pid;
93 static int nflag;       /* no reverse dns lookups */
94 static int aflag;       /* do it for all entries */
95 static int cpuflag = -1;
96 static int s = -1;
97
98 struct  sockaddr_in so_mask;
99 struct  sockaddr_inarp blank_sin, sin_m;
100 struct  sockaddr_dl blank_sdl, sdl_m;
101 int     expire_time, flags, doing_proxy, proxy_only, found_entry;
102 struct  {
103         struct  rt_msghdr m_rtm;
104         char    m_space[512];
105 }       m_rtmsg;
106
107 /* which function we're supposed to do */
108 #define F_GET           1
109 #define F_SET           2
110 #define F_FILESET       3
111 #define F_REPLACE       4
112 #define F_DELETE        5
113
114 #define ROUNDUP(a) \
115         ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
116 #define SETFUNC(f)      { if (func) usage(); func = (f); }
117
118 int
119 main(int argc, char **argv)
120 {
121         int ch, func = 0;
122         int rtn = 0;
123
124         pid = getpid();
125         while ((ch = getopt(argc, argv, "ac:ndfsS")) != -1)
126                 switch((char)ch) {
127                 case 'a':
128                         aflag = 1;
129                         break;
130                 case 'c':
131                         cpuflag = strtol(optarg, NULL, 0);
132                         break;
133                 case 'd':
134                         SETFUNC(F_DELETE);
135                         break;
136                 case 'n':
137                         nflag = 1;
138                         break;
139                 case 'S':
140                         SETFUNC(F_REPLACE);
141                         break;
142                 case 's':
143                         SETFUNC(F_SET);
144                         break;
145                 case 'f' :
146                         SETFUNC(F_FILESET);
147                         break;
148                 case '?':
149                 default:
150                         usage();
151                 }
152         argc -= optind;
153         argv += optind;
154
155         bzero(&so_mask, sizeof(so_mask));
156         so_mask.sin_len = 8;
157         so_mask.sin_addr.s_addr = 0xffffffff;
158         bzero(&blank_sin, sizeof(blank_sin));
159         blank_sin.sin_len = sizeof(blank_sin);
160         blank_sin.sin_family = AF_INET;
161         bzero(&blank_sdl, sizeof(blank_sdl));
162         blank_sdl.sdl_len = sizeof(blank_sdl);
163         blank_sdl.sdl_family = AF_LINK;
164
165         if (!func)
166                 func = F_GET;
167         switch (func) {
168         case F_GET:
169                 if (aflag) {
170                         if (argc != 0)
171                                 usage();
172                         search(0, print_entry);
173                 } else {
174                         if (argc != 1)
175                                 usage();
176                         get(argv[0]);
177                 }
178                 break;
179         case F_SET:
180         case F_REPLACE:
181                 if (argc < 2 || argc > 6)
182                         usage();
183                 if (func == F_REPLACE)
184                         delete(argv[0], NULL);
185                 rtn = set(argc, argv) ? 1 : 0;
186                 break;
187         case F_DELETE:
188                 if (aflag) {
189                         if (argc != 0)
190                                 usage();
191                         search(0, nuke_entry);
192                 } else {
193                         if (argc < 1 || argc > 2)
194                                 usage();
195                         rtn = delete(argv[0], argv[1]);
196                 }
197                 break;
198         case F_FILESET:
199                 if (argc != 1)
200                         usage();
201                 rtn = file(argv[0]);
202                 break;
203         }
204
205         return(rtn);
206 }
207
208 /*
209  * Process a file to set standard arp entries
210  */
211 int
212 file(char *name)
213 {
214         FILE *fp;
215         int i, retval;
216         char line[100], arg[5][50], *args[5], *p;
217
218         if ((fp = fopen(name, "r")) == NULL)
219                 errx(1, "cannot open %s", name);
220         args[0] = &arg[0][0];
221         args[1] = &arg[1][0];
222         args[2] = &arg[2][0];
223         args[3] = &arg[3][0];
224         args[4] = &arg[4][0];
225         retval = 0;
226         while(fgets(line, 100, fp) != NULL) {
227                 if ((p = strchr(line, '#')) != NULL)
228                         *p = '\0';
229                 for (p = line; isblank(*p); p++);
230                 if (*p == '\n' || *p == '\0')
231                         continue;
232                 i = sscanf(p, "%49s %49s %49s %49s %49s", arg[0], arg[1],
233                     arg[2], arg[3], arg[4]);
234                 if (i < 2) {
235                         warnx("bad line: %s", line);
236                         retval = 1;
237                         continue;
238                 }
239                 if (set(i, args))
240                         retval = 1;
241         }
242         fclose(fp);
243         return(retval);
244 }
245
246 void
247 getsocket(void)
248 {
249         if (s < 0) {
250                 s = socket(PF_ROUTE, SOCK_RAW, 0);
251                 if (s < 0)
252                         err(1, "socket");
253         }
254 }
255
256 /*
257  * Set an individual arp entry
258  */
259 int
260 set(int argc, char **argv)
261 {
262         struct hostent *hp;
263         struct sockaddr_inarp *addr = &sin_m;
264         struct sockaddr_dl *sdl;
265         struct rt_msghdr *rtm = &(m_rtmsg.m_rtm);
266         struct ether_addr *ea;
267         char *host = argv[0], *eaddr = argv[1];
268
269         getsocket();
270         argc -= 2;
271         argv += 2;
272         sdl_m = blank_sdl;
273         sin_m = blank_sin;
274         addr->sin_addr.s_addr = inet_addr(host);
275         if (addr->sin_addr.s_addr == INADDR_NONE) {
276                 if (!(hp = gethostbyname(host))) {
277                         warnx("%s: %s", host, hstrerror(h_errno));
278                         return(1);
279                 }
280                 bcopy((char *)hp->h_addr, (char *)&addr->sin_addr,
281                     sizeof(addr->sin_addr));
282         }
283         doing_proxy = flags = proxy_only = expire_time = 0;
284         while (argc-- > 0) {
285                 if (strncmp(argv[0], "temp", 4) == 0) {
286                         struct timeval tv;
287                         gettimeofday(&tv, 0);
288                         expire_time = tv.tv_sec + 20 * 60;
289                 }
290                 else if (strncmp(argv[0], "pub", 3) == 0) {
291                         flags |= RTF_ANNOUNCE;
292                         doing_proxy = 1;
293                         if (argc && strncmp(argv[1], "only", 3) == 0) {
294                                 proxy_only = 1;
295                                 sin_m.sin_other = SIN_PROXY;
296                                 argc--; argv++;
297                         }
298                 } else if (strncmp(argv[0], "trail", 5) == 0) {
299                         printf("%s: Sending trailers is no longer supported\n",
300                                 host);
301                 }
302                 argv++;
303         }
304         ea = (struct ether_addr *)LLADDR(&sdl_m);
305         if (doing_proxy && !strcmp(eaddr, "auto")) {
306                 if (!get_ether_addr(addr->sin_addr.s_addr, ea)) {
307                         printf("no interface found for %s\n",
308                                inet_ntoa(addr->sin_addr));
309                         return(1);
310                 }
311                 sdl_m.sdl_alen = ETHER_ADDR_LEN;
312         } else {
313                 if (my_ether_aton(eaddr, ea) == 0)
314                         sdl_m.sdl_alen = ETHER_ADDR_LEN;
315         }
316 tryagain:
317         if (rtmsg(RTM_GET) < 0) {
318                 warn("%s", host);
319                 return(1);
320         }
321         addr = (struct sockaddr_inarp *)(rtm + 1);
322         sdl = (struct sockaddr_dl *)(ROUNDUP(addr->sin_len) + (char *)addr);
323         if (addr->sin_addr.s_addr == sin_m.sin_addr.s_addr) {
324                 if (sdl->sdl_family == AF_LINK &&
325                     (rtm->rtm_flags & RTF_LLINFO) &&
326                     !(rtm->rtm_flags & RTF_GATEWAY)) switch (sdl->sdl_type) {
327                 case IFT_ETHER: case IFT_FDDI: case IFT_ISO88023:
328                 case IFT_ISO88024: case IFT_ISO88025: case IFT_L2VLAN:
329                 case IFT_CARP:
330                         goto overwrite;
331                 }
332                 if (doing_proxy == 0) {
333                         printf("set: can only proxy for %s\n", host);
334                         return(1);
335                 }
336                 if (sin_m.sin_other & SIN_PROXY) {
337                         printf("set: proxy entry exists for non 802 device\n");
338                         return(1);
339                 }
340                 sin_m.sin_other = SIN_PROXY;
341                 proxy_only = 1;
342                 goto tryagain;
343         }
344 overwrite:
345         if (sdl->sdl_family != AF_LINK) {
346                 printf("cannot intuit interface index and type for %s\n", host);
347                 return(1);
348         }
349         sdl_m.sdl_type = sdl->sdl_type;
350         sdl_m.sdl_index = sdl->sdl_index;
351         return(rtmsg(RTM_ADD));
352 }
353
354 /*
355  * Display an individual arp entry
356  */
357 int
358 get(char *host)
359 {
360         struct hostent *hp;
361         struct sockaddr_inarp *addr = &sin_m;
362
363         sin_m = blank_sin;
364         addr->sin_addr.s_addr = inet_addr(host);
365         if (addr->sin_addr.s_addr == INADDR_NONE) {
366                 if (!(hp = gethostbyname(host)))
367                         errx(1, "%s: %s", host, hstrerror(h_errno));
368                 bcopy((char *)hp->h_addr, (char *)&addr->sin_addr,
369                     sizeof(addr->sin_addr));
370         }
371         search(addr->sin_addr.s_addr, print_entry);
372         if (found_entry == 0) {
373                 printf("%s (%s) -- no entry\n",
374                     host, inet_ntoa(addr->sin_addr));
375                 return(1);
376         }
377         return(0);
378 }
379
380 /*
381  * Delete an arp entry
382  */
383 int
384 delete(char *host, char *info)
385 {
386         struct hostent *hp;
387         struct sockaddr_inarp *addr = &sin_m;
388         struct rt_msghdr *rtm = &m_rtmsg.m_rtm;
389         struct sockaddr_dl *sdl;
390
391         getsocket();
392         sin_m = blank_sin;
393         if (info) {
394                 if (strncmp(info, "pub", 3) == 0)
395                         sin_m.sin_other = SIN_PROXY;
396                 else
397                         usage();
398         }
399         addr->sin_addr.s_addr = inet_addr(host);
400         if (addr->sin_addr.s_addr == INADDR_NONE) {
401                 if (!(hp = gethostbyname(host))) {
402                         warnx("%s: %s", host, hstrerror(h_errno));
403                         return(1);
404                 }
405                 bcopy((char *)hp->h_addr, (char *)&addr->sin_addr,
406                     sizeof(addr->sin_addr));
407         }
408 tryagain:
409         if (rtmsg(RTM_GET) < 0) {
410                 warn("%s", host);
411                 return(1);
412         }
413         addr = (struct sockaddr_inarp *)(rtm + 1);
414         sdl = (struct sockaddr_dl *)(ROUNDUP(addr->sin_len) + (char *)addr);
415         if (addr->sin_addr.s_addr == sin_m.sin_addr.s_addr) {
416                 if (sdl->sdl_family == AF_LINK &&
417                     (rtm->rtm_flags & RTF_LLINFO) &&
418                     !(rtm->rtm_flags & RTF_GATEWAY)) switch (sdl->sdl_type) {
419                 case IFT_ETHER: case IFT_FDDI: case IFT_ISO88023:
420                 case IFT_ISO88024: case IFT_ISO88025: case IFT_L2VLAN:
421                 case IFT_CARP:
422                         goto delete;
423                 }
424         }
425         if (sin_m.sin_other & SIN_PROXY) {
426                 fprintf(stderr, "delete: can't locate %s\n",host);
427                 return(1);
428         } else {
429                 sin_m.sin_other = SIN_PROXY;
430                 goto tryagain;
431         }
432 delete:
433         if (sdl->sdl_family != AF_LINK) {
434                 printf("cannot locate %s\n", host);
435                 return(1);
436         }
437         if (aflag && (rtm->rtm_flags & RTF_STATIC)) {
438                 sdl->sdl_alen = 0;
439                 sdl->sdl_slen = 0;
440                 if (rtmsg(RTM_CHANGE) == 0) {
441                         printf("%s (%s) cleared\n", 
442                                 host, inet_ntoa(addr->sin_addr));
443                         return(0);
444                 }
445         } else {
446                 if (rtmsg(RTM_DELETE) == 0) {
447                         printf("%s (%s) deleted\n", 
448                                 host, inet_ntoa(addr->sin_addr));
449                         return(0);
450                 }
451         }
452         return(1);
453 }
454
455 /*
456  * Search the arp table and do some action on matching entries
457  */
458 void
459 search(u_long addr, void (*action)(struct sockaddr_dl *sdl,
460         struct sockaddr_inarp *sin, struct rt_msghdr *rtm))
461 {
462         int mib[7];
463         int miblen;
464         size_t needed;
465         char *lim, *buf, *next;
466         struct rt_msghdr *rtm;
467         struct sockaddr_inarp *sin2;
468         struct sockaddr_dl *sdl;
469
470         mib[0] = CTL_NET;
471         mib[1] = PF_ROUTE;
472         mib[2] = 0;
473         mib[3] = AF_INET;
474         mib[4] = NET_RT_FLAGS;
475         mib[5] = RTF_LLINFO;
476         if (cpuflag >= 0) {
477             mib[6] = cpuflag;
478             miblen = 7;
479         } else {
480             miblen = 6;
481         }
482         if (sysctl(mib, miblen, NULL, &needed, NULL, 0) < 0)
483                 errx(1, "route-sysctl-estimate");
484         if ((buf = malloc(needed)) == NULL)
485                 errx(1, "malloc");
486         if (sysctl(mib, miblen, buf, &needed, NULL, 0) < 0)
487                 errx(1, "actual retrieval of routing table");
488         lim = buf + needed;
489         for (next = buf; next < lim; next += rtm->rtm_msglen) {
490                 rtm = (struct rt_msghdr *)next;
491                 sin2 = (struct sockaddr_inarp *)(rtm + 1);
492                 sdl = (struct sockaddr_dl *)((char *)sin2 + ROUNDUP(sin2->sin_len));
493                 if (addr) {
494                         if (addr != sin2->sin_addr.s_addr)
495                                 continue;
496                         found_entry = 1;
497                 }
498                 (*action)(sdl, sin2, rtm);
499         }
500         free(buf);
501 }
502
503 /*
504  * Display an arp entry
505  */
506 void
507 print_entry(struct sockaddr_dl *sdl,
508         struct sockaddr_inarp *addr, struct rt_msghdr *rtm)
509 {
510         const char *host;
511         struct hostent *hp;
512         char ifname[IF_NAMESIZE];
513
514         if (nflag == 0)
515                 hp = gethostbyaddr(&(addr->sin_addr), sizeof(addr->sin_addr),
516                     AF_INET);
517         else
518                 hp = 0;
519         if (hp)
520                 host = hp->h_name;
521         else {
522                 host = "?";
523                 if (h_errno == TRY_AGAIN)
524                         nflag = 1;
525         }
526         printf("%s (%s) at ", host, inet_ntoa(addr->sin_addr));
527         if (sdl->sdl_alen)
528                 printf("%s", ether_ntoa((struct ether_addr *)LLADDR(sdl)));
529         else
530                 printf("(incomplete)");
531         if (if_indextoname(sdl->sdl_index, ifname) != NULL)
532                 printf(" on %s", ifname);
533         if (rtm->rtm_rmx.rmx_expire == 0)
534                 printf(" permanent");
535         if (addr->sin_other & SIN_PROXY)
536                 printf(" published (proxy only)");
537         if (rtm->rtm_addrs & RTA_NETMASK) {
538                 addr = (struct sockaddr_inarp *)
539                         (ROUNDUP(sdl->sdl_len) + (char *)sdl);
540                 if (addr->sin_addr.s_addr == 0xffffffff)
541                         printf(" published");
542                 if (addr->sin_len != 8)
543                         printf("(weird)");
544         }
545         switch(sdl->sdl_type) {
546             case IFT_ETHER:
547                 printf(" [ethernet]");
548                 break;
549             case IFT_L2VLAN:
550                 printf(" [vlan]");
551                 break;
552             case IFT_CARP:
553                 printf(" [carp]");
554             default:
555                 break;
556         }
557                 
558         printf("\n");
559
560 }
561
562 /*
563  * Nuke an arp entry
564  */
565 void
566 nuke_entry(struct sockaddr_dl *sdl __unused,
567         struct sockaddr_inarp *addr, struct rt_msghdr *rtm __unused)
568 {
569         char ip[20];
570
571         snprintf(ip, sizeof(ip), "%s", inet_ntoa(addr->sin_addr));
572         delete(ip, NULL);
573 }
574
575 int
576 my_ether_aton(char *a, struct ether_addr *n)
577 {
578         struct ether_addr *ea;
579
580         if ((ea = ether_aton(a)) == NULL) {
581                 warnx("invalid Ethernet address '%s'", a);
582                 return(1);
583         }
584         *n = *ea;
585         return(0);
586 }
587
588 void
589 usage(void)
590 {
591         fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
592                 "usage: arp [-n] [-c cpu] hostname",
593                 "       arp [-n] [-c cpu] -a",
594                 "       arp -d hostname [pub]",
595                 "       arp -d -a",
596                 "       arp -s hostname ether_addr [temp] [pub [only]]",
597                 "       arp -S hostname ether_addr [temp] [pub [only]]",
598                 "       arp -f filename");
599         exit(1);
600 }
601
602 int
603 rtmsg(int cmd)
604 {
605         static int seq;
606         int rlen;
607         struct rt_msghdr *rtm = &m_rtmsg.m_rtm;
608         char *cp = m_rtmsg.m_space;
609         int l;
610
611         errno = 0;
612         if (cmd == RTM_DELETE || cmd == RTM_CHANGE)
613                 goto doit;
614         bzero((char *)&m_rtmsg, sizeof(m_rtmsg));
615         rtm->rtm_flags = flags;
616         rtm->rtm_version = RTM_VERSION;
617
618         switch (cmd) {
619         default:
620                 errx(1, "internal wrong cmd");
621         case RTM_ADD:
622                 rtm->rtm_addrs |= RTA_GATEWAY;
623                 rtm->rtm_rmx.rmx_expire = expire_time;
624                 rtm->rtm_inits = RTV_EXPIRE;
625                 rtm->rtm_flags |= (RTF_HOST | RTF_STATIC);
626                 sin_m.sin_other = 0;
627                 if (doing_proxy) {
628                         if (proxy_only)
629                                 sin_m.sin_other = SIN_PROXY;
630                         else {
631                                 rtm->rtm_addrs |= RTA_NETMASK;
632                                 rtm->rtm_flags &= ~RTF_HOST;
633                         }
634                 }
635                 /* FALLTHROUGH */
636         case RTM_GET:
637                 rtm->rtm_addrs |= RTA_DST;
638         }
639 #define NEXTADDR(w, s) \
640         if (rtm->rtm_addrs & (w)) { \
641                 bcopy((char *)&s, cp, sizeof(s)); cp += ROUNDUP(sizeof(s));}
642
643         NEXTADDR(RTA_DST, sin_m);
644         NEXTADDR(RTA_GATEWAY, sdl_m);
645         NEXTADDR(RTA_NETMASK, so_mask);
646
647         rtm->rtm_msglen = cp - (char *)&m_rtmsg;
648 doit:
649         l = rtm->rtm_msglen;
650         rtm->rtm_seq = ++seq;
651         rtm->rtm_type = cmd;
652         if ((rlen = write(s, (char *)&m_rtmsg, l)) < 0) {
653                 if (errno != ESRCH || (cmd != RTM_DELETE && cmd != RTM_CHANGE)) {
654                         warn("writing to routing socket");
655                         return(-1);
656                 }
657         }
658         do {
659                 l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg));
660         } while (l > 0 && (rtm->rtm_seq != seq || rtm->rtm_pid != pid));
661         if (l < 0)
662                 warn("read from routing socket");
663         return(0);
664 }
665
666 /*
667  * get_ether_addr - get the hardware address of an interface on the
668  * the same subnet as ipaddr.
669  */
670 #define MAX_IFS         32
671
672 int
673 get_ether_addr(u_int32_t ipaddr, struct ether_addr *hwaddr)
674 {
675         struct ifreq *ifr, *ifend, *ifp;
676         u_int32_t ina, mask;
677         struct sockaddr_dl *dla;
678         struct ifreq ifreq;
679         struct ifconf ifc;
680         struct ifreq ifs[MAX_IFS];
681         int sock;
682
683         sock = socket(AF_INET, SOCK_DGRAM, 0);
684         if (sock < 0)
685                 err(1, "socket");
686
687         ifc.ifc_len = sizeof(ifs);
688         ifc.ifc_req = ifs;
689         if (ioctl(sock, SIOCGIFCONF, &ifc) < 0) {
690                 warnx("ioctl(SIOCGIFCONF)");
691                 close(sock);
692                 return(0);
693         }
694
695         /*
696         * Scan through looking for an interface with an Internet
697         * address on the same subnet as `ipaddr'.
698         */
699         ifend = (struct ifreq *) (ifc.ifc_buf + ifc.ifc_len);
700         for (ifr = ifc.ifc_req; ifr < ifend; ) {
701                 if (ifr->ifr_addr.sa_family == AF_INET) {
702                         ina = ((struct sockaddr_in *) 
703                                 &ifr->ifr_addr)->sin_addr.s_addr;
704                         strncpy(ifreq.ifr_name, ifr->ifr_name, 
705                                 sizeof(ifreq.ifr_name));
706                         /*
707                          * Check that the interface is up,
708                          * and not point-to-point or loopback.
709                          */
710                         if (ioctl(sock, SIOCGIFFLAGS, &ifreq) < 0)
711                                 continue;
712                         if ((ifreq.ifr_flags &
713                              (IFF_UP|IFF_BROADCAST|IFF_POINTOPOINT|
714                                         IFF_LOOPBACK|IFF_NOARP))
715                              != (IFF_UP|IFF_BROADCAST))
716                                 goto nextif;
717                         /*
718                          * Get its netmask and check that it's on 
719                          * the right subnet.
720                          */
721                         if (ioctl(sock, SIOCGIFNETMASK, &ifreq) < 0)
722                                 continue;
723                         mask = ((struct sockaddr_in *)
724                                 &ifreq.ifr_addr)->sin_addr.s_addr;
725                         if ((ipaddr & mask) != (ina & mask))
726                                 goto nextif;
727                         break;
728                 }
729 nextif:
730                 ifr = (struct ifreq *) ((char *)&ifr->ifr_addr
731                     + MAX(ifr->ifr_addr.sa_len, sizeof(ifr->ifr_addr)));
732         }
733
734         if (ifr >= ifend) {
735                 close(sock);
736                 return(0);
737         }
738
739         /*
740         * Now scan through again looking for a link-level address
741         * for this interface.
742         */
743         ifp = ifr;
744         for (ifr = ifc.ifc_req; ifr < ifend; ) {
745                 if (strcmp(ifp->ifr_name, ifr->ifr_name) == 0
746                     && ifr->ifr_addr.sa_family == AF_LINK) {
747                         /*
748                          * Found the link-level address - copy it out
749                          */
750                         dla = (struct sockaddr_dl *) &ifr->ifr_addr;
751                         memcpy(hwaddr,  LLADDR(dla), dla->sdl_alen);
752                         close (sock);
753                         printf("using interface %s for proxy with address ",
754                                 ifp->ifr_name);
755                         printf("%s\n", ether_ntoa(hwaddr));
756                         return(dla->sdl_alen);
757                 }
758                 ifr = (struct ifreq *) ((char *)&ifr->ifr_addr
759                     + MAX(ifr->ifr_addr.sa_len, sizeof(ifr->ifr_addr)));
760         }
761         return(0);
762 }