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