1 /* vi: set sw=4 ts=4: */
5 * Mostly stolen from: dhcpcd - DHCP client daemon
6 * by Yoichi Hariguchi <yoichi@fore.com>
9 #include <netinet/if_ether.h>
10 #include <net/if_arp.h>
18 u_char h_dest[6]; /* destination ether addr */
19 u_char h_source[6]; /* source ether addr */
20 u_short h_proto; /* packet type ID field */
23 uint16_t htype; /* hardware type (must be ARPHRD_ETHER) */
24 uint16_t ptype; /* protocol type (must be ETH_P_IP) */
25 uint8_t hlen; /* hardware address length (must be 6) */
26 uint8_t plen; /* protocol address length (must be 4) */
27 uint16_t operation; /* ARP opcode */
28 uint8_t sHaddr[6]; /* sender's hardware address */
29 uint8_t sInaddr[4]; /* sender's IP address */
30 uint8_t tHaddr[6]; /* target's hardware address */
31 uint8_t tInaddr[4]; /* target's IP address */
32 uint8_t pad[18]; /* pad for min. Ethernet payload (60 bytes) */
35 /* args: yiaddr - what IP to ping
37 * mac - our arp address
38 * interface - interface to use
44 /* FIXME: match response against chaddr */
45 int arpping(uint32_t yiaddr, uint32_t ip, uint8_t *mac, char *interface)
51 int rv = 1; /* return value */
52 struct sockaddr addr; /* for interface name */
59 if ((s = socket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ARP))) == -1) {
60 bb_perror_msg(bb_msg_can_not_create_raw_socket);
64 if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval)) == -1) {
65 bb_perror_msg("cannot setsocketopt on raw socket");
70 /* send arp request */
71 memset(&arp, 0, sizeof(arp));
72 memcpy(arp.h_dest, MAC_BCAST_ADDR, 6); /* MAC DA */
73 memcpy(arp.h_source, mac, 6); /* MAC SA */
74 arp.h_proto = htons(ETH_P_ARP); /* protocol type (Ethernet) */
75 arp.htype = htons(ARPHRD_ETHER); /* hardware type */
76 arp.ptype = htons(ETH_P_IP); /* protocol type (ARP message) */
77 arp.hlen = 6; /* hardware address length */
78 arp.plen = 4; /* protocol address length */
79 arp.operation = htons(ARPOP_REQUEST); /* ARP op code */
80 memcpy(arp.sInaddr, &ip, sizeof(ip)); /* source IP address */
81 memcpy(arp.sHaddr, mac, 6); /* source hardware address */
82 memcpy(arp.tInaddr, &yiaddr, sizeof(yiaddr)); /* target IP address */
84 memset(&addr, 0, sizeof(addr));
85 strcpy(addr.sa_data, interface);
86 if (sendto(s, &arp, sizeof(arp), 0, &addr, sizeof(addr)) < 0)
89 /* wait arp reply, and check it */
96 if (select(s + 1, &fdset, (fd_set *) NULL, (fd_set *) NULL, &tm) < 0) {
97 bb_perror_msg("error on ARPING request");
98 if (errno != EINTR) rv = 0;
99 } else if (FD_ISSET(s, &fdset)) {
100 if (recv(s, &arp, sizeof(arp), 0) < 0 ) rv = 0;
101 if (arp.operation == htons(ARPOP_REPLY) &&
102 memcmp(arp.tHaddr, mac, 6) == 0 &&
103 *((uint32_t *) arp.sInaddr) == yiaddr) {
104 DEBUG("Valid arp reply received for this address");
109 timeout -= uptime() - prevTime;
113 DEBUG("%salid arp replies for this address", rv ? "No v" : "V");