2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1984, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Sun Microsystems, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * arp - display, set, and delete arp table entries
39 #include <sys/param.h>
41 #include <sys/socket.h>
42 #include <sys/sockio.h>
43 #include <sys/sysctl.h>
44 #include <sys/ioctl.h>
48 #include <net/if_dl.h>
49 #include <net/if_types.h>
50 #include <net/route.h>
52 #include <netinet/in.h>
53 #include <netinet/if_ether.h>
55 #include <arpa/inet.h>
73 typedef void (action_fn)(struct sockaddr_dl *sdl, struct sockaddr_in *s_in,
74 struct rt_msghdr *rtm);
75 static void nuke_entries(uint32_t ifindex, struct in_addr addr);
76 static int print_entries(uint32_t ifindex, struct in_addr addr);
78 static int delete(char *host);
79 static void usage(void) __dead2;
80 static int set(int argc, char **argv);
81 static int get(char *host);
82 static int file(char *name);
83 static struct rt_msghdr *rtmsg(int cmd,
84 struct sockaddr_in *dst, struct sockaddr_dl *sdl);
85 static int get_ether_addr(in_addr_t ipaddr, struct ether_addr *hwaddr);
86 static int set_rtsock(struct sockaddr_in *dst, struct sockaddr_dl *sdl_m,
89 struct if_nameindex *ifnameindex;
91 struct arp_opts opts = {};
93 /* which function we're supposed to do */
100 #define SETFUNC(f) { if (func) usage(); func = (f); }
102 #define ARP_XO_VERSION "1"
105 main(int argc, char *argv[])
110 argc = xo_parse_args(argc, argv);
114 while ((ch = getopt(argc, argv, "andfsSi:")) != -1)
135 opts.rifname = optarg;
147 if (func != F_GET && !(func == F_DELETE && opts.aflag))
148 xo_errx(1, "-i not applicable to this operation");
149 if ((opts.rifindex = if_nametoindex(opts.rifname)) == 0) {
151 xo_errx(1, "interface %s does not exist",
154 xo_err(1, "if_nametoindex(%s)", opts.rifname);
163 xo_set_version(ARP_XO_VERSION);
164 xo_open_container("arp");
165 xo_open_list("arp-cache");
167 struct in_addr all_addrs = {};
168 print_entries(opts.rifindex, all_addrs);
170 xo_close_list("arp-cache");
171 xo_close_container("arp");
181 if (argc < 2 || argc > 6)
183 if (func == F_REPLACE)
184 (void)delete(argv[0]);
185 rtn = set(argc, argv) ? 1 : 0;
191 struct in_addr all_addrs = {};
192 nuke_entries(0, all_addrs);
196 rtn = delete(argv[0]);
206 if (ifnameindex != NULL)
207 if_freenameindex(ifnameindex);
213 * Process a file to set standard arp entries
220 char line[100], arg[5][50], *args[5], *p;
222 if ((fp = fopen(name, "r")) == NULL)
223 xo_err(1, "cannot open %s", name);
224 args[0] = &arg[0][0];
225 args[1] = &arg[1][0];
226 args[2] = &arg[2][0];
227 args[3] = &arg[3][0];
228 args[4] = &arg[4][0];
230 while(fgets(line, sizeof(line), fp) != NULL) {
231 if ((p = strchr(line, '#')) != NULL)
233 for (p = line; isblank(*p); p++);
234 if (*p == '\n' || *p == '\0')
236 i = sscanf(p, "%49s %49s %49s %49s %49s", arg[0], arg[1],
237 arg[2], arg[3], arg[4]);
239 xo_warnx("bad line: %s", line);
251 * Given a hostname, fills up a (static) struct sockaddr_in with
252 * the address of the host and returns a pointer to the
259 static struct sockaddr_in reply;
261 bzero(&reply, sizeof(reply));
262 reply.sin_len = sizeof(reply);
263 reply.sin_family = AF_INET;
264 reply.sin_addr.s_addr = inet_addr(host);
265 if (reply.sin_addr.s_addr == INADDR_NONE) {
266 if (!(hp = gethostbyname(host))) {
267 xo_warnx("%s: %s", host, hstrerror(h_errno));
270 bcopy((char *)hp->h_addr, (char *)&reply.sin_addr,
271 sizeof reply.sin_addr);
276 int valid_type(int type);
278 * Returns true if the type is a valid one for ARP.
300 * Set an individual arp entry
303 set(int argc, char **argv)
305 struct sockaddr_in *dst; /* what are we looking for */
306 struct ether_addr *ea;
307 char *host = argv[0], *eaddr = argv[1];
308 struct sockaddr_dl sdl_m;
313 bzero(&sdl_m, sizeof(sdl_m));
314 sdl_m.sdl_len = sizeof(sdl_m);
315 sdl_m.sdl_family = AF_LINK;
321 if (strcmp(argv[0], "temp") == 0) {
323 size_t len = sizeof(max_age);
325 if (sysctlbyname("net.link.ether.inet.max_age",
326 &max_age, &len, NULL, 0) != 0)
327 xo_err(1, "sysctlbyname");
328 opts.expire_time = max_age;
329 } else if (strcmp(argv[0], "pub") == 0) {
330 opts.flags |= RTF_ANNOUNCE;
331 if (argc && strcmp(argv[1], "only") == 0) {
333 * Compatibility: in pre FreeBSD 8 times
334 * the "only" keyword used to mean that
335 * an ARP entry should be announced, but
336 * not installed into routing table.
340 } else if (strcmp(argv[0], "blackhole") == 0) {
341 if (opts.flags & RTF_REJECT) {
342 xo_errx(1, "Choose one of blackhole or reject, "
345 opts.flags |= RTF_BLACKHOLE;
346 } else if (strcmp(argv[0], "reject") == 0) {
347 if (opts.flags & RTF_BLACKHOLE) {
348 xo_errx(1, "Choose one of blackhole or reject, "
351 opts.flags |= RTF_REJECT;
353 xo_warnx("Invalid parameter '%s'", argv[0]);
358 ea = (struct ether_addr *)LLADDR(&sdl_m);
359 if ((opts.flags & RTF_ANNOUNCE) && !strcmp(eaddr, "auto")) {
360 if (!get_ether_addr(dst->sin_addr.s_addr, ea)) {
361 xo_warnx("no interface found for %s",
362 inet_ntoa(dst->sin_addr));
365 sdl_m.sdl_alen = ETHER_ADDR_LEN;
367 struct ether_addr *ea1 = ether_aton(eaddr);
370 xo_warnx("invalid Ethernet address '%s'", eaddr);
374 sdl_m.sdl_alen = ETHER_ADDR_LEN;
377 #ifndef WITHOUT_NETLINK
378 return (set_nl(0, dst, &sdl_m, host));
380 return (set_rtsock(dst, &sdl_m, host));
384 #ifdef WITHOUT_NETLINK
386 set_rtsock(struct sockaddr_in *dst, struct sockaddr_dl *sdl_m, char *host)
388 struct sockaddr_in *addr;
389 struct sockaddr_dl *sdl;
390 struct rt_msghdr *rtm;
393 * In the case a proxy-arp entry is being added for
394 * a remote end point, the RTF_ANNOUNCE flag in the
395 * RTM_GET command is an indication to the kernel
396 * routing code that the interface associated with
397 * the prefix route covering the local end of the
398 * PPP link should be returned, on which ARP applies.
400 rtm = rtmsg(RTM_GET, dst, NULL);
405 addr = (struct sockaddr_in *)(rtm + 1);
406 sdl = (struct sockaddr_dl *)(SA_SIZE(addr) + (char *)addr);
408 if ((sdl->sdl_family != AF_LINK) ||
409 (rtm->rtm_flags & RTF_GATEWAY) ||
410 !valid_type(sdl->sdl_type)) {
411 xo_warnx("cannot intuit interface index and type for %s", host);
414 sdl_m->sdl_type = sdl->sdl_type;
415 sdl_m->sdl_index = sdl->sdl_index;
416 return (rtmsg(RTM_ADD, dst, sdl_m) == NULL);
421 * Display an individual arp entry
426 struct sockaddr_in *addr;
429 addr = getaddr(host);
433 xo_set_version(ARP_XO_VERSION);
434 xo_open_container("arp");
435 xo_open_list("arp-cache");
437 found = print_entries(opts.rifindex, addr->sin_addr);
440 xo_emit("{d:hostname/%s} ({d:ip-address/%s}) -- no entry",
441 host, inet_ntoa(addr->sin_addr));
443 xo_emit(" on {d:interface/%s}", opts.rifname);
447 xo_close_list("arp-cache");
448 xo_close_container("arp");
455 * Delete an arp entry
457 #ifdef WITHOUT_NETLINK
459 delete_rtsock(char *host)
461 struct sockaddr_in *addr, *dst;
462 struct rt_msghdr *rtm;
463 struct sockaddr_dl *sdl;
470 * Perform a regular entry delete first.
472 opts.flags &= ~RTF_ANNOUNCE;
474 for (;;) { /* try twice */
475 rtm = rtmsg(RTM_GET, dst, NULL);
480 addr = (struct sockaddr_in *)(rtm + 1);
481 sdl = (struct sockaddr_dl *)(SA_SIZE(addr) + (char *)addr);
484 * With the new L2/L3 restructure, the route
485 * returned is a prefix route. The important
486 * piece of information from the previous
487 * RTM_GET is the interface index. In the
488 * case of ECMP, the kernel will traverse
489 * the route group for the given entry.
491 if (sdl->sdl_family == AF_LINK &&
492 !(rtm->rtm_flags & RTF_GATEWAY) &&
493 valid_type(sdl->sdl_type) ) {
494 addr->sin_addr.s_addr = dst->sin_addr.s_addr;
499 * Regular entry delete failed, now check if there
500 * is a proxy-arp entry to remove.
502 if (opts.flags & RTF_ANNOUNCE) {
503 xo_warnx("delete: cannot locate %s", host);
507 opts.flags |= RTF_ANNOUNCE;
509 rtm->rtm_flags |= RTF_LLDATA;
510 if (rtmsg(RTM_DELETE, dst, NULL) != NULL) {
511 printf("%s (%s) deleted\n", host, inet_ntoa(addr->sin_addr));
521 #ifdef WITHOUT_NETLINK
522 return (delete_rtsock(host));
524 return (delete_nl(0, host));
530 * Search the arp table and do some action on matching entries
533 search(u_long addr, action_fn *action)
537 char *lim, *buf, *next;
538 struct rt_msghdr *rtm;
539 struct sockaddr_in *sin2;
540 struct sockaddr_dl *sdl;
541 int st, found_entry = 0;
547 mib[4] = NET_RT_FLAGS;
553 if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
554 xo_err(1, "route-sysctl-estimate");
555 if (needed == 0) /* empty table */
559 buf = reallocf(buf, needed);
561 xo_errx(1, "could not reallocate memory");
562 st = sysctl(mib, 6, buf, &needed, NULL, 0);
563 if (st == 0 || errno != ENOMEM)
565 needed += needed / 8;
568 xo_err(1, "actual retrieval of routing table");
570 for (next = buf; next < lim; next += rtm->rtm_msglen) {
571 rtm = (struct rt_msghdr *)next;
572 sin2 = (struct sockaddr_in *)(rtm + 1);
573 sdl = (struct sockaddr_dl *)((char *)sin2 + SA_SIZE(sin2));
575 (opts.rifindex != sdl->sdl_index))
578 (addr != sin2->sin_addr.s_addr))
581 (*action)(sdl, sin2, rtm);
584 return (found_entry);
588 * Display an arp entry
592 print_entry(struct sockaddr_dl *sdl,
593 struct sockaddr_in *addr, struct rt_msghdr *rtm)
597 struct if_nameindex *p;
599 if (ifnameindex == NULL)
600 if ((ifnameindex = if_nameindex()) == NULL)
601 xo_err(1, "cannot retrieve interface names");
603 xo_open_instance("arp-cache");
606 hp = gethostbyaddr((caddr_t)&(addr->sin_addr),
607 sizeof addr->sin_addr, AF_INET);
614 if (h_errno == TRY_AGAIN)
617 xo_emit("{:hostname/%s} ({:ip-address/%s}) at ", host,
618 inet_ntoa(addr->sin_addr));
620 if ((sdl->sdl_type == IFT_ETHER ||
621 sdl->sdl_type == IFT_L2VLAN ||
622 sdl->sdl_type == IFT_BRIDGE) &&
623 sdl->sdl_alen == ETHER_ADDR_LEN)
624 xo_emit("{:mac-address/%s}",
625 ether_ntoa((struct ether_addr *)LLADDR(sdl)));
627 int n = sdl->sdl_nlen > 0 ? sdl->sdl_nlen + 1 : 0;
629 xo_emit("{:mac-address/%s}", link_ntoa(sdl) + n);
632 xo_emit("{d:/(incomplete)}{en:incomplete/true}");
634 for (p = ifnameindex; p && p->if_index && p->if_name; p++) {
635 if (p->if_index == sdl->sdl_index) {
636 xo_emit(" on {:interface/%s}", p->if_name);
641 if (rtm->rtm_rmx.rmx_expire == 0)
642 xo_emit("{d:/ permanent}{en:permanent/true}");
644 static struct timespec tp;
645 time_t expire_time = 0;
648 clock_gettime(CLOCK_MONOTONIC, &tp);
649 if ((expire_time = rtm->rtm_rmx.rmx_expire - tp.tv_sec) > 0)
650 xo_emit(" expires in {:expires/%d} seconds",
653 xo_emit("{d:/ expired}{en:expired/true}");
656 if (rtm->rtm_flags & RTF_ANNOUNCE)
657 xo_emit("{d:/ published}{en:published/true}");
659 switch(sdl->sdl_type) {
661 xo_emit(" [{:type/ethernet}]");
664 xo_emit(" [{:type/fddi}]");
667 xo_emit(" [{:type/atm}]");
670 xo_emit(" [{:type/vlan}]");
673 xo_emit(" [{:type/firewire}]");
676 xo_emit(" [{:type/bridge}]");
679 xo_emit(" [{:type/infiniband}]");
687 xo_close_instance("arp-cache");
691 print_entries(uint32_t ifindex, struct in_addr addr)
693 #ifndef WITHOUT_NETLINK
694 return (print_entries_nl(ifindex, addr));
696 return (search(addr.s_addr, print_entry));
705 nuke_entry(struct sockaddr_dl *sdl __unused,
706 struct sockaddr_in *addr, struct rt_msghdr *rtm)
710 if (rtm->rtm_flags & RTF_PINNED)
713 snprintf(ip, sizeof(ip), "%s", inet_ntoa(addr->sin_addr));
718 nuke_entries(uint32_t ifindex, struct in_addr addr)
720 search(addr.s_addr, nuke_entry);
726 fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
727 "usage: arp [-n] [-i interface] hostname",
728 " arp [-n] [-i interface] -a",
729 " arp -d hostname [pub]",
730 " arp -d [-i interface] -a",
731 " arp -s hostname ether_addr [temp] [reject | blackhole] [pub [only]]",
732 " arp -S hostname ether_addr [temp] [reject | blackhole] [pub [only]]",
737 static struct rt_msghdr *
738 rtmsg(int cmd, struct sockaddr_in *dst, struct sockaddr_dl *sdl)
747 struct rt_msghdr m_rtm;
751 struct rt_msghdr *rtm = &m_rtmsg.m_rtm;
752 char *cp = m_rtmsg.m_space;
754 if (s < 0) { /* first time: open socket, get pid */
755 s = socket(PF_ROUTE, SOCK_RAW, 0);
763 * XXX RTM_DELETE relies on a previous RTM_GET to fill the buffer
766 if (cmd == RTM_DELETE)
768 bzero((char *)&m_rtmsg, sizeof(m_rtmsg));
769 rtm->rtm_flags = opts.flags;
770 rtm->rtm_version = RTM_VERSION;
774 xo_errx(1, "internal wrong cmd");
776 rtm->rtm_addrs |= RTA_GATEWAY;
777 if (opts.expire_time != 0) {
780 clock_gettime(CLOCK_MONOTONIC, &tp);
781 rtm->rtm_rmx.rmx_expire = opts.expire_time + tp.tv_sec;
783 rtm->rtm_inits = RTV_EXPIRE;
784 rtm->rtm_flags |= (RTF_HOST | RTF_STATIC | RTF_LLDATA);
787 rtm->rtm_addrs |= RTA_DST;
789 #define NEXTADDR(w, s) \
791 if ((s) != NULL && rtm->rtm_addrs & (w)) { \
792 bcopy((s), cp, sizeof(*(s))); \
797 NEXTADDR(RTA_DST, dst);
798 NEXTADDR(RTA_GATEWAY, sdl);
800 rtm->rtm_msglen = cp - (char *)&m_rtmsg;
803 rtm->rtm_seq = ++seq;
805 if ((rlen = write(s, (char *)&m_rtmsg, l)) < 0) {
806 if (errno != ESRCH || cmd != RTM_DELETE) {
807 xo_warn("writing to routing socket");
812 l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg));
813 } while (l > 0 && (rtm->rtm_type != cmd || rtm->rtm_seq != seq ||
814 rtm->rtm_pid != pid));
816 xo_warn("read from routing socket");
821 * get_ether_addr - get the hardware address of an interface on the
822 * the same subnet as ipaddr.
825 get_ether_addr(in_addr_t ipaddr, struct ether_addr *hwaddr)
827 struct ifaddrs *ifa, *ifd, *ifas = NULL;
829 struct sockaddr_dl *dla;
833 * Scan through looking for an interface with an Internet
834 * address on the same subnet as `ipaddr'.
836 if (getifaddrs(&ifas) < 0) {
837 xo_warnx("getifaddrs");
841 for (ifa = ifas; ifa != NULL; ifa = ifa->ifa_next) {
842 if (ifa->ifa_addr == NULL || ifa->ifa_netmask == NULL)
844 if (ifa->ifa_addr->sa_family != AF_INET)
847 * Check that the interface is up,
848 * and not point-to-point or loopback.
850 if ((ifa->ifa_flags &
851 (IFF_UP|IFF_BROADCAST|IFF_POINTOPOINT|
852 IFF_LOOPBACK|IFF_NOARP)) != (IFF_UP|IFF_BROADCAST))
854 /* Get its netmask and check that it's on the right subnet. */
855 mask = ((struct sockaddr_in *)
856 ifa->ifa_netmask)->sin_addr.s_addr;
857 ina = ((struct sockaddr_in *)
858 ifa->ifa_addr)->sin_addr.s_addr;
859 if ((ipaddr & mask) == (ina & mask))
860 break; /* ok, we got it! */
866 * Now scan through again looking for a link-level address
867 * for this interface.
869 for (ifd = ifas; ifd != NULL; ifd = ifd->ifa_next) {
870 if (ifd->ifa_addr == NULL)
872 if (strcmp(ifa->ifa_name, ifd->ifa_name) == 0 &&
873 ifd->ifa_addr->sa_family == AF_LINK)
879 * Found the link-level address - copy it out
881 dla = (struct sockaddr_dl *)ifd->ifa_addr;
882 memcpy(hwaddr, LLADDR(dla), dla->sdl_alen);
883 printf("using interface %s for proxy with address %s\n", ifa->ifa_name,
885 retval = dla->sdl_alen;