4 * Mostly stolen from: dhcpcd - DHCP client daemon
5 * by Yoichi Hariguchi <yoichi@fore.com>
11 #include <sys/types.h>
12 #include <sys/socket.h>
13 #include <netinet/if_ether.h>
14 #include <net/if_arp.h>
15 #include <netinet/in.h>
25 /* args: yiaddr - what IP to ping
27 * mac - our arp address
28 * interface - interface to use
34 /* FIXME: match response against chaddr */
35 int arpping(u_int32_t yiaddr, u_int32_t ip, unsigned char *mac, char *interface)
41 int rv = 1; /* return value */
42 struct sockaddr addr; /* for interface name */
49 if ((s = socket (PF_PACKET, SOCK_PACKET, htons(ETH_P_ARP))) == -1) {
50 LOG(LOG_ERR, "Could not open raw socket");
54 if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval)) == -1) {
55 LOG(LOG_ERR, "Could not setsocketopt on raw socket");
60 /* send arp request */
61 memset(&arp, 0, sizeof(arp));
62 memcpy(arp.ethhdr.h_dest, MAC_BCAST_ADDR, 6); /* MAC DA */
63 memcpy(arp.ethhdr.h_source, mac, 6); /* MAC SA */
64 arp.ethhdr.h_proto = htons(ETH_P_ARP); /* protocol type (Ethernet) */
65 arp.htype = htons(ARPHRD_ETHER); /* hardware type */
66 arp.ptype = htons(ETH_P_IP); /* protocol type (ARP message) */
67 arp.hlen = 6; /* hardware address length */
68 arp.plen = 4; /* protocol address length */
69 arp.operation = htons(ARPOP_REQUEST); /* ARP op code */
70 memcpy(arp.sInaddr, &ip, sizeof(ip)); /* source IP address */
71 memcpy(arp.sHaddr, mac, 6); /* source hardware address */
72 memcpy(arp.tInaddr, &yiaddr, sizeof(yiaddr)); /* target IP address */
74 memset(&addr, 0, sizeof(addr));
75 strcpy(addr.sa_data, interface);
76 if (sendto(s, &arp, sizeof(arp), 0, &addr, sizeof(addr)) < 0)
79 /* wait arp reply, and check it */
86 if (select(s + 1, &fdset, (fd_set *) NULL, (fd_set *) NULL, &tm) < 0) {
87 DEBUG(LOG_ERR, "Error on ARPING request: %s", strerror(errno));
88 if (errno != EINTR) rv = 0;
89 } else if (FD_ISSET(s, &fdset)) {
90 if (recv(s, &arp, sizeof(arp), 0) < 0 ) rv = 0;
91 if (arp.operation == htons(ARPOP_REPLY) &&
92 bcmp(arp.tHaddr, mac, 6) == 0 &&
93 *((u_int *) arp.sInaddr) == yiaddr) {
94 DEBUG(LOG_INFO, "Valid arp reply receved for this address");
99 timeout -= time(NULL) - prevTime;
103 DEBUG(LOG_INFO, "%salid arp replies for this address", rv ? "No v" : "V");