1 /* vi: set sw=4 ts=4: */
5 * Mostly stolen from: dhcpcd - DHCP client daemon
6 * by Yoichi Hariguchi <yoichi@fore.com>
10 #include <sys/socket.h>
11 #include <netinet/if_ether.h>
12 #include <net/if_arp.h>
13 #include <netinet/in.h>
22 /* args: yiaddr - what IP to ping
24 * mac - our arp address
25 * interface - interface to use
31 /* FIXME: match response against chaddr */
32 int arpping(uint32_t yiaddr, uint32_t ip, uint8_t *mac, char *interface)
38 int rv = 1; /* return value */
39 struct sockaddr addr; /* for interface name */
46 if ((s = socket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ARP))) == -1) {
47 bb_perror_msg(bb_msg_can_not_create_raw_socket);
51 if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval)) == -1) {
52 bb_perror_msg("cannot setsocketopt on raw socket");
57 /* send arp request */
58 memset(&arp, 0, sizeof(arp));
59 memcpy(arp.h_dest, MAC_BCAST_ADDR, 6); /* MAC DA */
60 memcpy(arp.h_source, mac, 6); /* MAC SA */
61 arp.h_proto = htons(ETH_P_ARP); /* protocol type (Ethernet) */
62 arp.htype = htons(ARPHRD_ETHER); /* hardware type */
63 arp.ptype = htons(ETH_P_IP); /* protocol type (ARP message) */
64 arp.hlen = 6; /* hardware address length */
65 arp.plen = 4; /* protocol address length */
66 arp.operation = htons(ARPOP_REQUEST); /* ARP op code */
67 memcpy(arp.sInaddr, &ip, sizeof(ip)); /* source IP address */
68 memcpy(arp.sHaddr, mac, 6); /* source hardware address */
69 memcpy(arp.tInaddr, &yiaddr, sizeof(yiaddr)); /* target IP address */
71 memset(&addr, 0, sizeof(addr));
72 strcpy(addr.sa_data, interface);
73 if (sendto(s, &arp, sizeof(arp), 0, &addr, sizeof(addr)) < 0)
76 /* wait arp reply, and check it */
83 if (select(s + 1, &fdset, (fd_set *) NULL, (fd_set *) NULL, &tm) < 0) {
84 bb_perror_msg("Error on ARPING request");
85 if (errno != EINTR) rv = 0;
86 } else if (FD_ISSET(s, &fdset)) {
87 if (recv(s, &arp, sizeof(arp), 0) < 0 ) rv = 0;
88 if (arp.operation == htons(ARPOP_REPLY) &&
89 memcmp(arp.tHaddr, mac, 6) == 0 &&
90 *((uint32_t *) arp.sInaddr) == yiaddr) {
91 DEBUG("Valid arp reply received for this address");
96 timeout -= uptime() - prevTime;
100 DEBUG("%salid arp replies for this address", rv ? "No v" : "V");