1
2
3
4
5
6
7
8#include <netinet/if_ether.h>
9#include <net/if_arp.h>
10
11#include "common.h"
12
13struct arpMsg {
14
15 uint8_t h_dest[6];
16 uint8_t h_source[6];
17 uint16_t h_proto;
18
19
20 uint16_t htype;
21 uint16_t ptype;
22 uint8_t hlen;
23 uint8_t plen;
24 uint16_t operation;
25 uint8_t sHaddr[6];
26 uint8_t sInaddr[4];
27 uint8_t tHaddr[6];
28 uint8_t tInaddr[4];
29 uint8_t pad[18];
30} PACKED;
31
32enum {
33 ARP_MSG_SIZE = 0x2a
34};
35
36
37int FAST_FUNC arpping(uint32_t test_nip,
38 const uint8_t *safe_mac,
39 uint32_t from_ip,
40 uint8_t *from_mac,
41 const char *interface,
42 unsigned timeo)
43{
44 int timeout_ms;
45 struct pollfd pfd[1];
46#define s (pfd[0].fd)
47 int rv = 1;
48 struct sockaddr addr;
49 struct arpMsg arp;
50
51 if (!timeo)
52 return 1;
53
54 s = socket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ARP));
55 if (s == -1) {
56 bb_perror_msg(bb_msg_can_not_create_raw_socket);
57 return -1;
58 }
59
60 if (setsockopt_broadcast(s) == -1) {
61 bb_perror_msg("can't enable bcast on raw socket");
62 goto ret;
63 }
64
65
66 memset(&arp, 0, sizeof(arp));
67 memset(arp.h_dest, 0xff, 6);
68 memcpy(arp.h_source, from_mac, 6);
69 arp.h_proto = htons(ETH_P_ARP);
70 arp.htype = htons(ARPHRD_ETHER);
71 arp.ptype = htons(ETH_P_IP);
72 arp.hlen = 6;
73 arp.plen = 4;
74 arp.operation = htons(ARPOP_REQUEST);
75 memcpy(arp.sHaddr, from_mac, 6);
76 memcpy(arp.sInaddr, &from_ip, sizeof(from_ip));
77
78 memcpy(arp.tInaddr, &test_nip, sizeof(test_nip));
79
80 memset(&addr, 0, sizeof(addr));
81 safe_strncpy(addr.sa_data, interface, sizeof(addr.sa_data));
82 if (sendto(s, &arp, sizeof(arp), 0, &addr, sizeof(addr)) < 0) {
83
84
85 goto ret;
86 }
87
88
89 timeout_ms = (int)timeo;
90 do {
91 typedef uint32_t aliased_uint32_t FIX_ALIASING;
92 int r;
93 unsigned prevTime = monotonic_ms();
94
95 pfd[0].events = POLLIN;
96 r = safe_poll(pfd, 1, timeout_ms);
97 if (r < 0)
98 break;
99 if (r) {
100 r = safe_read(s, &arp, sizeof(arp));
101 if (r < 0)
102 break;
103
104
105
106
107
108 if (r >= ARP_MSG_SIZE
109 && arp.operation == htons(ARPOP_REPLY)
110
111
112 && *(aliased_uint32_t*)arp.sInaddr == test_nip
113 ) {
114
115
116
117
118 if (!safe_mac || memcmp(safe_mac, arp.sHaddr, 6) != 0)
119 rv = 0;
120
121 break;
122 }
123 }
124 timeout_ms -= (unsigned)monotonic_ms() - prevTime + 1;
125
126
127
128
129
130 } while ((unsigned)timeout_ms <= timeo);
131
132 ret:
133 close(s);
134 log1("%srp reply received for this address", rv ? "no a" : "A");
135 return rv;
136}
137