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