4 * Mostly stolen from: dhcpcd - DHCP client daemon
5 * 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) {
48 LOG(LOG_ERR, bb_msg_can_not_create_raw_socket);
50 LOG(LOG_ERR, "Could not open raw socket");
55 if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval)) == -1) {
56 LOG(LOG_ERR, "Could not setsocketopt on raw socket");
61 /* send arp request */
62 memset(&arp, 0, sizeof(arp));
63 memcpy(arp.h_dest, MAC_BCAST_ADDR, 6); /* MAC DA */
64 memcpy(arp.h_source, mac, 6); /* MAC SA */
65 arp.h_proto = htons(ETH_P_ARP); /* protocol type (Ethernet) */
66 arp.htype = htons(ARPHRD_ETHER); /* hardware type */
67 arp.ptype = htons(ETH_P_IP); /* protocol type (ARP message) */
68 arp.hlen = 6; /* hardware address length */
69 arp.plen = 4; /* protocol address length */
70 arp.operation = htons(ARPOP_REQUEST); /* ARP op code */
71 memcpy(arp.sInaddr, &ip, sizeof(ip)); /* source IP address */
72 memcpy(arp.sHaddr, mac, 6); /* source hardware address */
73 memcpy(arp.tInaddr, &yiaddr, sizeof(yiaddr)); /* target IP address */
75 memset(&addr, 0, sizeof(addr));
76 strcpy(addr.sa_data, interface);
77 if (sendto(s, &arp, sizeof(arp), 0, &addr, sizeof(addr)) < 0)
80 /* wait arp reply, and check it */
82 prevTime = time(NULL);
87 if (select(s + 1, &fdset, (fd_set *) NULL, (fd_set *) NULL, &tm) < 0) {
88 DEBUG(LOG_ERR, "Error on ARPING request: %m");
89 if (errno != EINTR) rv = 0;
90 } else if (FD_ISSET(s, &fdset)) {
91 if (recv(s, &arp, sizeof(arp), 0) < 0 ) rv = 0;
92 if (arp.operation == htons(ARPOP_REPLY) &&
93 bcmp(arp.tHaddr, mac, 6) == 0 &&
94 *((uint32_t *) arp.sInaddr) == yiaddr) {
95 DEBUG(LOG_INFO, "Valid arp reply receved for this address");
100 timeout -= time(NULL) - prevTime;
101 prevTime = time(NULL);
104 DEBUG(LOG_INFO, "%salid arp replies for this address", rv ? "No v" : "V");