Merge from vendor branch OPENSSH:
[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.4 2004/06/19 20:38:22 joerg 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 #include <net/iso88025.h>
60
61 #include <netinet/in.h>
62 #include <netinet/if_ether.h>
63
64 #include <arpa/inet.h>
65
66 #include <ctype.h>
67 #include <err.h>
68 #include <errno.h>
69 #include <netdb.h>
70 #include <nlist.h>
71 #include <paths.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <strings.h>
75 #include <unistd.h>
76
77 void search(u_long addr, void (*action)(struct sockaddr_dl *sdl,
78         struct sockaddr_inarp *sin, struct rt_msghdr *rtm));
79 void print_entry(struct sockaddr_dl *sdl,
80         struct sockaddr_inarp *addr, struct rt_msghdr *rtm);
81 void nuke_entry(struct sockaddr_dl *sdl,
82         struct sockaddr_inarp *addr, struct rt_msghdr *rtm);
83 int delete(char *host, char *info);
84 void usage(void);
85 int set(int argc, char **argv);
86 int get(char *host);
87 int file(char *name);
88 void getsocket(void);
89 int my_ether_aton(char *a, struct ether_addr *n);
90 int rtmsg(int cmd);
91 int get_ether_addr(u_int32_t ipaddr, struct ether_addr *hwaddr);
92
93 static int pid;
94 static int nflag;       /* no reverse dns lookups */
95 static int aflag;       /* do it for all entries */
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, "andfsS")) != -1)
126                 switch((char)ch) {
127                 case 'a':
128                         aflag = 1;
129                         break;
130                 case 'd':
131                         SETFUNC(F_DELETE);
132                         break;
133                 case 'n':
134                         nflag = 1;
135                         break;
136                 case 'S':
137                         SETFUNC(F_REPLACE);
138                         break;
139                 case 's':
140                         SETFUNC(F_SET);
141                         break;
142                 case 'f' :
143                         SETFUNC(F_FILESET);
144                         break;
145                 case '?':
146                 default:
147                         usage();
148                 }
149         argc -= optind;
150         argv += optind;
151
152         bzero(&so_mask, sizeof(so_mask));
153         so_mask.sin_len = 8;
154         so_mask.sin_addr.s_addr = 0xffffffff;
155         bzero(&blank_sin, sizeof(blank_sin));
156         blank_sin.sin_len = sizeof(blank_sin);
157         blank_sin.sin_family = AF_INET;
158         bzero(&blank_sdl, sizeof(blank_sdl));
159         blank_sdl.sdl_len = sizeof(blank_sdl);
160         blank_sdl.sdl_family = AF_LINK;
161
162         if (!func)
163                 func = F_GET;
164         switch (func) {
165         case F_GET:
166                 if (aflag) {
167                         if (argc != 0)
168                                 usage();
169                         search(0, print_entry);
170                 } else {
171                         if (argc != 1)
172                                 usage();
173                         get(argv[0]);
174                 }
175                 break;
176         case F_SET:
177         case F_REPLACE:
178                 if (argc < 2 || argc > 6)
179                         usage();
180                 if (func == F_REPLACE)
181                         (void) delete(argv[0], NULL);
182                 rtn = set(argc, argv) ? 1 : 0;
183                 break;
184         case F_DELETE:
185                 if (aflag) {
186                         if (argc != 0)
187                                 usage();
188                         search(0, nuke_entry);
189                 } else {
190                         if (argc < 1 || argc > 2)
191                                 usage();
192                         rtn = delete(argv[0], argv[1]);
193                 }
194                 break;
195         case F_FILESET:
196                 if (argc != 1)
197                         usage();
198                 rtn = file(argv[0]);
199                 break;
200         }
201
202         return(rtn);
203 }
204
205 /*
206  * Process a file to set standard arp entries
207  */
208 int
209 file(char *name)
210 {
211         FILE *fp;
212         int i, retval;
213         char line[100], arg[5][50], *args[5], *p;
214
215         if ((fp = fopen(name, "r")) == NULL)
216                 errx(1, "cannot open %s", name);
217         args[0] = &arg[0][0];
218         args[1] = &arg[1][0];
219         args[2] = &arg[2][0];
220         args[3] = &arg[3][0];
221         args[4] = &arg[4][0];
222         retval = 0;
223         while(fgets(line, 100, fp) != NULL) {
224                 if ((p = strchr(line, '#')) != NULL)
225                         *p = '\0';
226                 for (p = line; isblank(*p); p++);
227                 if (*p == '\n' || *p == '\0')
228                         continue;
229                 i = sscanf(p, "%49s %49s %49s %49s %49s", arg[0], arg[1],
230                     arg[2], arg[3], arg[4]);
231                 if (i < 2) {
232                         warnx("bad line: %s", line);
233                         retval = 1;
234                         continue;
235                 }
236                 if (set(i, args))
237                         retval = 1;
238         }
239         fclose(fp);
240         return(retval);
241 }
242
243 void
244 getsocket(void)
245 {
246         if (s < 0) {
247                 s = socket(PF_ROUTE, SOCK_RAW, 0);
248                 if (s < 0)
249                         err(1, "socket");
250         }
251 }
252
253 /*
254  * Set an individual arp entry
255  */
256 int
257 set(int argc, char **argv)
258 {
259         struct hostent *hp;
260         struct sockaddr_inarp *addr = &sin_m;
261         struct sockaddr_dl *sdl;
262         struct rt_msghdr *rtm = &(m_rtmsg.m_rtm);
263         struct ether_addr *ea;
264         char *host = argv[0], *eaddr = argv[1];
265
266         getsocket();
267         argc -= 2;
268         argv += 2;
269         sdl_m = blank_sdl;
270         sin_m = blank_sin;
271         addr->sin_addr.s_addr = inet_addr(host);
272         if (addr->sin_addr.s_addr == INADDR_NONE) {
273                 if (!(hp = gethostbyname(host))) {
274                         warnx("%s: %s", host, hstrerror(h_errno));
275                         return(1);
276                 }
277                 bcopy((char *)hp->h_addr, (char *)&addr->sin_addr,
278                     sizeof(addr->sin_addr));
279         }
280         doing_proxy = flags = proxy_only = expire_time = 0;
281         while (argc-- > 0) {
282                 if (strncmp(argv[0], "temp", 4) == 0) {
283                         struct timeval tv;
284                         gettimeofday(&tv, 0);
285                         expire_time = tv.tv_sec + 20 * 60;
286                 }
287                 else if (strncmp(argv[0], "pub", 3) == 0) {
288                         flags |= RTF_ANNOUNCE;
289                         doing_proxy = 1;
290                         if (argc && strncmp(argv[1], "only", 3) == 0) {
291                                 proxy_only = 1;
292                                 sin_m.sin_other = SIN_PROXY;
293                                 argc--; argv++;
294                         }
295                 } else if (strncmp(argv[0], "trail", 5) == 0) {
296                         printf("%s: Sending trailers is no longer supported\n",
297                                 host);
298                 }
299                 argv++;
300         }
301         ea = (struct ether_addr *)LLADDR(&sdl_m);
302         if (doing_proxy && !strcmp(eaddr, "auto")) {
303                 if (!get_ether_addr(addr->sin_addr.s_addr, ea)) {
304                         printf("no interface found for %s\n",
305                                inet_ntoa(addr->sin_addr));
306                         return(1);
307                 }
308                 sdl_m.sdl_alen = ETHER_ADDR_LEN;
309         } else {
310                 if (my_ether_aton(eaddr, ea) == 0)
311                         sdl_m.sdl_alen = ETHER_ADDR_LEN;
312         }
313 tryagain:
314         if (rtmsg(RTM_GET) < 0) {
315                 warn("%s", host);
316                 return(1);
317         }
318         addr = (struct sockaddr_inarp *)(rtm + 1);
319         sdl = (struct sockaddr_dl *)(ROUNDUP(addr->sin_len) + (char *)addr);
320         if (addr->sin_addr.s_addr == sin_m.sin_addr.s_addr) {
321                 if (sdl->sdl_family == AF_LINK &&
322                     (rtm->rtm_flags & RTF_LLINFO) &&
323                     !(rtm->rtm_flags & RTF_GATEWAY)) switch (sdl->sdl_type) {
324                 case IFT_ETHER: case IFT_FDDI: case IFT_ISO88023:
325                 case IFT_ISO88024: case IFT_ISO88025: case IFT_L2VLAN:
326                         goto overwrite;
327                 }
328                 if (doing_proxy == 0) {
329                         printf("set: can only proxy for %s\n", host);
330                         return(1);
331                 }
332                 if (sin_m.sin_other & SIN_PROXY) {
333                         printf("set: proxy entry exists for non 802 device\n");
334                         return(1);
335                 }
336                 sin_m.sin_other = SIN_PROXY;
337                 proxy_only = 1;
338                 goto tryagain;
339         }
340 overwrite:
341         if (sdl->sdl_family != AF_LINK) {
342                 printf("cannot intuit interface index and type for %s\n", host);
343                 return(1);
344         }
345         sdl_m.sdl_type = sdl->sdl_type;
346         sdl_m.sdl_index = sdl->sdl_index;
347         return(rtmsg(RTM_ADD));
348 }
349
350 /*
351  * Display an individual arp entry
352  */
353 int
354 get(char *host)
355 {
356         struct hostent *hp;
357         struct sockaddr_inarp *addr = &sin_m;
358
359         sin_m = blank_sin;
360         addr->sin_addr.s_addr = inet_addr(host);
361         if (addr->sin_addr.s_addr == INADDR_NONE) {
362                 if (!(hp = gethostbyname(host)))
363                         errx(1, "%s: %s", host, hstrerror(h_errno));
364                 bcopy((char *)hp->h_addr, (char *)&addr->sin_addr,
365                     sizeof(addr->sin_addr));
366         }
367         search(addr->sin_addr.s_addr, print_entry);
368         if (found_entry == 0) {
369                 printf("%s (%s) -- no entry\n",
370                     host, inet_ntoa(addr->sin_addr));
371                 return(1);
372         }
373         return(0);
374 }
375
376 /*
377  * Delete an arp entry
378  */
379 int
380 delete(char *host, char *info)
381 {
382         struct hostent *hp;
383         struct sockaddr_inarp *addr = &sin_m;
384         struct rt_msghdr *rtm = &m_rtmsg.m_rtm;
385         struct sockaddr_dl *sdl;
386
387         getsocket();
388         sin_m = blank_sin;
389         if (info) {
390                 if (strncmp(info, "pub", 3) == 0)
391                         sin_m.sin_other = SIN_PROXY;
392                 else
393                         usage();
394         }
395         addr->sin_addr.s_addr = inet_addr(host);
396         if (addr->sin_addr.s_addr == INADDR_NONE) {
397                 if (!(hp = gethostbyname(host))) {
398                         warnx("%s: %s", host, hstrerror(h_errno));
399                         return(1);
400                 }
401                 bcopy((char *)hp->h_addr, (char *)&addr->sin_addr,
402                     sizeof(addr->sin_addr));
403         }
404 tryagain:
405         if (rtmsg(RTM_GET) < 0) {
406                 warn("%s", host);
407                 return(1);
408         }
409         addr = (struct sockaddr_inarp *)(rtm + 1);
410         sdl = (struct sockaddr_dl *)(ROUNDUP(addr->sin_len) + (char *)addr);
411         if (addr->sin_addr.s_addr == sin_m.sin_addr.s_addr) {
412                 if (sdl->sdl_family == AF_LINK &&
413                     (rtm->rtm_flags & RTF_LLINFO) &&
414                     !(rtm->rtm_flags & RTF_GATEWAY)) switch (sdl->sdl_type) {
415                 case IFT_ETHER: case IFT_FDDI: case IFT_ISO88023:
416                 case IFT_ISO88024: case IFT_ISO88025: case IFT_L2VLAN:
417                         goto delete;
418                 }
419         }
420         if (sin_m.sin_other & SIN_PROXY) {
421                 fprintf(stderr, "delete: can't locate %s\n",host);
422                 return(1);
423         } else {
424                 sin_m.sin_other = SIN_PROXY;
425                 goto tryagain;
426         }
427 delete:
428         if (sdl->sdl_family != AF_LINK) {
429                 printf("cannot locate %s\n", host);
430                 return(1);
431         }
432         if (rtmsg(RTM_DELETE) == 0) {
433                 printf("%s (%s) deleted\n", host, inet_ntoa(addr->sin_addr));
434                 return(0);
435         }
436         return(1);
437 }
438
439 /*
440  * Search the arp table and do some action on matching entries
441  */
442 void
443 search(u_long addr, void (*action)(struct sockaddr_dl *sdl,
444         struct sockaddr_inarp *sin, struct rt_msghdr *rtm))
445 {
446         int mib[6];
447         size_t needed;
448         char *lim, *buf, *next;
449         struct rt_msghdr *rtm;
450         struct sockaddr_inarp *sin2;
451         struct sockaddr_dl *sdl;
452
453         mib[0] = CTL_NET;
454         mib[1] = PF_ROUTE;
455         mib[2] = 0;
456         mib[3] = AF_INET;
457         mib[4] = NET_RT_FLAGS;
458         mib[5] = RTF_LLINFO;
459         if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
460                 errx(1, "route-sysctl-estimate");
461         if ((buf = malloc(needed)) == NULL)
462                 errx(1, "malloc");
463         if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
464                 errx(1, "actual retrieval of routing table");
465         lim = buf + needed;
466         for (next = buf; next < lim; next += rtm->rtm_msglen) {
467                 rtm = (struct rt_msghdr *)next;
468                 sin2 = (struct sockaddr_inarp *)(rtm + 1);
469                 (char *)sdl = (char *)sin2 + ROUNDUP(sin2->sin_len);
470                 if (addr) {
471                         if (addr != sin2->sin_addr.s_addr)
472                                 continue;
473                         found_entry = 1;
474                 }
475                 (*action)(sdl, sin2, rtm);
476         }
477         free(buf);
478 }
479
480 /*
481  * Display an arp entry
482  */
483 void
484 print_entry(struct sockaddr_dl *sdl,
485         struct sockaddr_inarp *addr, struct rt_msghdr *rtm)
486 {
487         const char *host;
488         struct hostent *hp;
489         struct iso88025_sockaddr_dl_data *trld;
490         char ifname[IF_NAMESIZE];
491         int seg;
492
493         if (nflag == 0)
494                 hp = gethostbyaddr((caddr_t)&(addr->sin_addr),
495                     sizeof(addr->sin_addr), AF_INET);
496         else
497                 hp = 0;
498         if (hp)
499                 host = hp->h_name;
500         else {
501                 host = "?";
502                 if (h_errno == TRY_AGAIN)
503                         nflag = 1;
504         }
505         printf("%s (%s) at ", host, inet_ntoa(addr->sin_addr));
506         if (sdl->sdl_alen)
507                 printf("%s", ether_ntoa((struct ether_addr *)LLADDR(sdl)));
508         else
509                 printf("(incomplete)");
510         if (if_indextoname(sdl->sdl_index, ifname) != NULL)
511                 printf(" on %s", ifname);
512         if (rtm->rtm_rmx.rmx_expire == 0)
513                 printf(" permanent");
514         if (addr->sin_other & SIN_PROXY)
515                 printf(" published (proxy only)");
516         if (rtm->rtm_addrs & RTA_NETMASK) {
517                 addr = (struct sockaddr_inarp *)
518                         (ROUNDUP(sdl->sdl_len) + (char *)sdl);
519                 if (addr->sin_addr.s_addr == 0xffffffff)
520                         printf(" published");
521                 if (addr->sin_len != 8)
522                         printf("(weird)");
523         }
524         switch(sdl->sdl_type) {
525             case IFT_ETHER:
526                 printf(" [ethernet]");
527                 break;
528             case IFT_ISO88025:
529                 printf(" [token-ring]");
530                 trld = SDL_ISO88025(sdl);
531                 if (trld->trld_rcf != 0) {
532                         printf(" rt=%x", ntohs(trld->trld_rcf));
533                         for (seg = 0;
534                              seg < ((TR_RCF_RIFLEN(trld->trld_rcf) - 2 ) / 2);
535                              seg++) 
536                                 printf(":%x", ntohs(*(trld->trld_route[seg])));
537                 }
538                 break;
539             case IFT_L2VLAN:
540                 printf(" [vlan]");
541                 break;
542             default:
543                 break;
544         }
545                 
546         printf("\n");
547
548 }
549
550 /*
551  * Nuke an arp entry
552  */
553 void
554 nuke_entry(struct sockaddr_dl *sdl __unused,
555         struct sockaddr_inarp *addr, struct rt_msghdr *rtm __unused)
556 {
557         char ip[20];
558
559         snprintf(ip, sizeof(ip), "%s", inet_ntoa(addr->sin_addr));
560         delete(ip, NULL);
561 }
562
563 int
564 my_ether_aton(char *a, struct ether_addr *n)
565 {
566         struct ether_addr *ea;
567
568         if ((ea = ether_aton(a)) == NULL) {
569                 warnx("invalid Ethernet address '%s'", a);
570                 return(1);
571         }
572         *n = *ea;
573         return(0);
574 }
575
576 void
577 usage(void)
578 {
579         fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
580                 "usage: arp [-n] hostname",
581                 "       arp [-n] -a",
582                 "       arp -d hostname [pub]",
583                 "       arp -d -a",
584                 "       arp -s hostname ether_addr [temp] [pub]",
585                 "       arp -S hostname ether_addr [temp] [pub]",
586                 "       arp -f filename");
587         exit(1);
588 }
589
590 int
591 rtmsg(int cmd)
592 {
593         static int seq;
594         int rlen;
595         struct rt_msghdr *rtm = &m_rtmsg.m_rtm;
596         char *cp = m_rtmsg.m_space;
597         int l;
598
599         errno = 0;
600         if (cmd == RTM_DELETE)
601                 goto doit;
602         bzero((char *)&m_rtmsg, sizeof(m_rtmsg));
603         rtm->rtm_flags = flags;
604         rtm->rtm_version = RTM_VERSION;
605
606         switch (cmd) {
607         default:
608                 errx(1, "internal wrong cmd");
609         case RTM_ADD:
610                 rtm->rtm_addrs |= RTA_GATEWAY;
611                 rtm->rtm_rmx.rmx_expire = expire_time;
612                 rtm->rtm_inits = RTV_EXPIRE;
613                 rtm->rtm_flags |= (RTF_HOST | RTF_STATIC);
614                 sin_m.sin_other = 0;
615                 if (doing_proxy) {
616                         if (proxy_only)
617                                 sin_m.sin_other = SIN_PROXY;
618                         else {
619                                 rtm->rtm_addrs |= RTA_NETMASK;
620                                 rtm->rtm_flags &= ~RTF_HOST;
621                         }
622                 }
623                 /* FALLTHROUGH */
624         case RTM_GET:
625                 rtm->rtm_addrs |= RTA_DST;
626         }
627 #define NEXTADDR(w, s) \
628         if (rtm->rtm_addrs & (w)) { \
629                 bcopy((char *)&s, cp, sizeof(s)); cp += ROUNDUP(sizeof(s));}
630
631         NEXTADDR(RTA_DST, sin_m);
632         NEXTADDR(RTA_GATEWAY, sdl_m);
633         NEXTADDR(RTA_NETMASK, so_mask);
634
635         rtm->rtm_msglen = cp - (char *)&m_rtmsg;
636 doit:
637         l = rtm->rtm_msglen;
638         rtm->rtm_seq = ++seq;
639         rtm->rtm_type = cmd;
640         if ((rlen = write(s, (char *)&m_rtmsg, l)) < 0) {
641                 if (errno != ESRCH || cmd != RTM_DELETE) {
642                         warn("writing to routing socket");
643                         return(-1);
644                 }
645         }
646         do {
647                 l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg));
648         } while (l > 0 && (rtm->rtm_seq != seq || rtm->rtm_pid != pid));
649         if (l < 0)
650                 warn("read from routing socket");
651         return(0);
652 }
653
654 /*
655  * get_ether_addr - get the hardware address of an interface on the
656  * the same subnet as ipaddr.
657  */
658 #define MAX_IFS         32
659
660 int
661 get_ether_addr(u_int32_t ipaddr, struct ether_addr *hwaddr)
662 {
663         struct ifreq *ifr, *ifend, *ifp;
664         u_int32_t ina, mask;
665         struct sockaddr_dl *dla;
666         struct ifreq ifreq;
667         struct ifconf ifc;
668         struct ifreq ifs[MAX_IFS];
669         int sock;
670
671         sock = socket(AF_INET, SOCK_DGRAM, 0);
672         if (sock < 0)
673                 err(1, "socket");
674
675         ifc.ifc_len = sizeof(ifs);
676         ifc.ifc_req = ifs;
677         if (ioctl(sock, SIOCGIFCONF, &ifc) < 0) {
678                 warnx("ioctl(SIOCGIFCONF)");
679                 close(sock);
680                 return(0);
681         }
682
683         /*
684         * Scan through looking for an interface with an Internet
685         * address on the same subnet as `ipaddr'.
686         */
687         ifend = (struct ifreq *) (ifc.ifc_buf + ifc.ifc_len);
688         for (ifr = ifc.ifc_req; ifr < ifend; ) {
689                 if (ifr->ifr_addr.sa_family == AF_INET) {
690                         ina = ((struct sockaddr_in *) 
691                                 &ifr->ifr_addr)->sin_addr.s_addr;
692                         strncpy(ifreq.ifr_name, ifr->ifr_name, 
693                                 sizeof(ifreq.ifr_name));
694                         /*
695                          * Check that the interface is up,
696                          * and not point-to-point or loopback.
697                          */
698                         if (ioctl(sock, SIOCGIFFLAGS, &ifreq) < 0)
699                                 continue;
700                         if ((ifreq.ifr_flags &
701                              (IFF_UP|IFF_BROADCAST|IFF_POINTOPOINT|
702                                         IFF_LOOPBACK|IFF_NOARP))
703                              != (IFF_UP|IFF_BROADCAST))
704                                 goto nextif;
705                         /*
706                          * Get its netmask and check that it's on 
707                          * the right subnet.
708                          */
709                         if (ioctl(sock, SIOCGIFNETMASK, &ifreq) < 0)
710                                 continue;
711                         mask = ((struct sockaddr_in *)
712                                 &ifreq.ifr_addr)->sin_addr.s_addr;
713                         if ((ipaddr & mask) != (ina & mask))
714                                 goto nextif;
715                         break;
716                 }
717 nextif:
718                 ifr = (struct ifreq *) ((char *)&ifr->ifr_addr
719                     + MAX(ifr->ifr_addr.sa_len, sizeof(ifr->ifr_addr)));
720         }
721
722         if (ifr >= ifend) {
723                 close(sock);
724                 return(0);
725         }
726
727         /*
728         * Now scan through again looking for a link-level address
729         * for this interface.
730         */
731         ifp = ifr;
732         for (ifr = ifc.ifc_req; ifr < ifend; ) {
733                 if (strcmp(ifp->ifr_name, ifr->ifr_name) == 0
734                     && ifr->ifr_addr.sa_family == AF_LINK) {
735                         /*
736                          * Found the link-level address - copy it out
737                          */
738                         dla = (struct sockaddr_dl *) &ifr->ifr_addr;
739                         memcpy(hwaddr,  LLADDR(dla), dla->sdl_alen);
740                         close (sock);
741                         printf("using interface %s for proxy with address ",
742                                 ifp->ifr_name);
743                         printf("%s\n", ether_ntoa(hwaddr));
744                         return(dla->sdl_alen);
745                 }
746                 ifr = (struct ifreq *) ((char *)&ifr->ifr_addr
747                     + MAX(ifr->ifr_addr.sa_len, sizeof(ifr->ifr_addr)));
748         }
749         return(0);
750 }