Repository navigation
Expand file tree
/
Copy pathPing.cpp
More file actions
497 lines (405 loc) · 16 KB
/
Copy pathPing.cpp
File metadata and controls
497 lines (405 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
// Ping.cpp
// Implementation of cross-platform ICMP ping for Linux and macOS
#include "Ping.h"
#include <algorithm>
#include <cerrno>
#include <cmath>
#include <cstring>
#include <iostream>
#include <random>
#include <thread>
#include <vector>
#include "NameResolver.h"
// -------------------- Constants --------------------
namespace PingInternal {
constexpr int32_t ICMP_HEADER_SIZE = 8;
constexpr int32_t IP_HEADER_SIZE = 20;
constexpr int32_t RECV_BUFFER_SIZE = 1500;
// ICMP types
constexpr uint8_t ICMP_ECHO_REPLY_TYPE = 0;
constexpr uint8_t ICMP_ECHO_REQUEST_TYPE = 8;
// ICMPv6 types
constexpr uint8_t ICMPV6_ECHO_REQUEST_TYPE = 128;
constexpr uint8_t ICMPV6_ECHO_REPLY_TYPE = 129;
// -------------------- Helper Functions --------------------
int64_t nowMicroseconds() {
auto lNow = std::chrono::steady_clock::now();
return std::chrono::duration_cast<std::chrono::microseconds>(
lNow.time_since_epoch()).count();
}
uint16_t generateIdentifier() {
std::random_device lRd;
std::mt19937 lGen(lRd());
std::uniform_int_distribution<uint16_t> lDist(1, 65535);
return lDist(lGen);
}
} // namespace PingInternal
// -------------------- Ping Implementation --------------------
Ping::Ping() {
mIdentifier = PingInternal::generateIdentifier();
}
Ping::~Ping() = default;
bool Ping::canPing() {
// Try to create a raw ICMP socket
int32_t lSock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (lSock < 0) {
if (errno == EPERM || errno == EACCES) {
return false;
}
return false;
}
close(lSock);
return true;
}
bool Ping::isIPv6Available() {
int32_t lSock = socket(AF_INET6, SOCK_DGRAM, 0);
if (lSock < 0) {
return false;
}
// Try to bind to loopback
sockaddr_in6 lAddr{};
lAddr.sin6_family = AF_INET6;
lAddr.sin6_addr = in6addr_loopback;
lAddr.sin6_port = 0;
bool lAvailable = (bind(lSock, reinterpret_cast<sockaddr*>(&lAddr), sizeof(lAddr)) == 0);
close(lSock);
return lAvailable;
}
void Ping::setOnReply(OnPingReplyCallback aCallback) {
mOnReply = std::move(aCallback);
}
void Ping::stop() {
mStopped.store(true);
}
int32_t Ping::createIcmpSocket(bool aIsV6) {
int32_t lSock;
if (aIsV6) {
lSock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
} else {
lSock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
}
return lSock;
}
bool Ping::resolveDestination(const std::string& aHost, PingIpVersion aIpVersion,
sockaddr_storage& rAddr, socklen_t& rAddrLen, bool& rIsV6) {
const auto lFamily = aIpVersion == PingIpVersion::V4 ? NameResolverFamily::IPV4
: aIpVersion == PingIpVersion::V6 ? NameResolverFamily::IPV6
: NameResolverFamily::ANY;
const auto lResolution = NameResolver::resolve(aHost, 0, lFamily);
if (!lResolution.succeeded() || lResolution.mEndpoints.empty()) return false;
const auto& lEndpoint = lResolution.mEndpoints.front();
rIsV6 = lEndpoint.mAddress.isIPv6();
return lEndpoint.toSockaddr(rAddr, rAddrLen);
}
std::string Ping::resolveHostname(const sockaddr_storage& aAddr, socklen_t aAddrLen) {
const auto lAddress = IpAddress::fromSockaddr(
reinterpret_cast<const sockaddr*>(&aAddr), aAddrLen);
if (!lAddress) return {};
const auto lResult = NameResolver::reverseLookup(*lAddress);
return lResult.succeeded() ? lResult.mHostname : std::string{};
}
std::string Ping::addrToString(const sockaddr_storage& aAddr) {
const auto lAddress = IpAddress::fromSockaddr(
reinterpret_cast<const sockaddr*>(&aAddr),
aAddr.ss_family == AF_INET
? static_cast<socklen_t>(sizeof(sockaddr_in))
: static_cast<socklen_t>(sizeof(sockaddr_in6)));
return lAddress ? lAddress->toString() : std::string{};
}
uint16_t Ping::computeIcmpChecksum(const uint8_t* apData, size_t aLength) {
uint32_t lSum = 0;
const uint8_t* lpPtr = apData;
size_t lLen = aLength;
while (lLen > 1) {
uint16_t lWord = 0;
std::memcpy(&lWord, lpPtr, sizeof(lWord));
lSum += lWord;
lpPtr += sizeof(lWord);
lLen -= 2;
}
if (lLen == 1) {
lSum += *lpPtr;
}
lSum = (lSum >> 16) + (lSum & 0xFFFF);
lSum += (lSum >> 16);
return static_cast<uint16_t>(~lSum);
}
bool Ping::sendPing(int32_t aSocket, uint16_t aSeq, const sockaddr_storage& aDestAddr,
socklen_t aAddrLen, bool aIsV6, const PingConfig& aConfig) {
// Set TTL
if (aIsV6) {
int32_t lTtl = aConfig.mTtl;
if (setsockopt(aSocket, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &lTtl, sizeof(lTtl)) < 0) {
return false;
}
} else {
int32_t lTtl = aConfig.mTtl;
if (setsockopt(aSocket, IPPROTO_IP, IP_TTL, &lTtl, sizeof(lTtl)) < 0) {
return false;
}
}
// Build ICMP packet
size_t lPacketSize = std::max(static_cast<size_t>(aConfig.mPacketSize),
static_cast<size_t>(PingInternal::ICMP_HEADER_SIZE));
std::vector<uint8_t> lPacket(lPacketSize, 0);
// Fill payload with pattern (timestamp for RTT backup)
int64_t lTimestamp = PingInternal::nowMicroseconds();
if (lPacketSize > PingInternal::ICMP_HEADER_SIZE + sizeof(int64_t)) {
std::memcpy(lPacket.data() + PingInternal::ICMP_HEADER_SIZE, &lTimestamp, sizeof(int64_t));
}
if (aIsV6) {
// ICMPv6 Echo Request
auto* lpIcmp6 = reinterpret_cast<icmp6_hdr*>(lPacket.data());
lpIcmp6->icmp6_type = PingInternal::ICMPV6_ECHO_REQUEST_TYPE;
lpIcmp6->icmp6_code = 0;
lpIcmp6->icmp6_id = htons(mIdentifier);
lpIcmp6->icmp6_seq = htons(aSeq);
// Checksum is computed by kernel for ICMPv6
} else {
// ICMP Echo Request
auto* lpIcmp = reinterpret_cast<icmp*>(lPacket.data());
lpIcmp->icmp_type = PingInternal::ICMP_ECHO_REQUEST_TYPE;
lpIcmp->icmp_code = 0;
lpIcmp->icmp_id = htons(mIdentifier);
lpIcmp->icmp_seq = htons(aSeq);
lpIcmp->icmp_cksum = 0;
lpIcmp->icmp_cksum = computeIcmpChecksum(lPacket.data(), lPacket.size());
}
ssize_t lSent = sendto(aSocket, lPacket.data(), lPacket.size(), 0,
reinterpret_cast<const sockaddr*>(&aDestAddr), aAddrLen);
return lSent > 0;
}
std::optional<PingReply> Ping::receiveReply(int32_t aSocket, int32_t aTimeoutMs,
bool aIsV6, uint16_t aExpectedSequence,
int64_t aSendTime) {
pollfd lPfd{};
lPfd.fd = aSocket;
lPfd.events = POLLIN;
int64_t lStartTime = PingInternal::nowMicroseconds();
int32_t lRemainingMs = aTimeoutMs;
while (lRemainingMs > 0) {
int32_t lRet = poll(&lPfd, 1, lRemainingMs);
if (lRet < 0) {
if (errno == EINTR) {
int64_t lElapsed = (PingInternal::nowMicroseconds() - lStartTime) / 1000;
lRemainingMs = aTimeoutMs - static_cast<int32_t>(lElapsed);
continue;
}
return std::nullopt;
}
if (lRet == 0) {
// Timeout
return std::nullopt;
}
// Data available
std::vector<uint8_t> lBuffer(PingInternal::RECV_BUFFER_SIZE);
sockaddr_storage lFromAddr{};
socklen_t lFromLen = sizeof(lFromAddr);
ssize_t lRecv = recvfrom(aSocket, lBuffer.data(), lBuffer.size(), 0,
reinterpret_cast<sockaddr*>(&lFromAddr), &lFromLen);
if (lRecv < 0) {
continue;
}
int64_t lRecvTime = PingInternal::nowMicroseconds();
int64_t lRtt = lRecvTime - aSendTime;
PingReply lReply;
lReply.mRttMicroseconds = lRtt;
lReply.mFromIp = addrToString(lFromAddr);
if (aIsV6) {
// ICMPv6 packet (no IP header when using raw socket)
if (lRecv < static_cast<ssize_t>(sizeof(icmp6_hdr))) {
continue;
}
auto* lpIcmp6 = reinterpret_cast<icmp6_hdr*>(lBuffer.data());
lReply.mIcmpType = lpIcmp6->icmp6_type;
lReply.mIcmpCode = lpIcmp6->icmp6_code;
if (lpIcmp6->icmp6_type == PingInternal::ICMPV6_ECHO_REPLY_TYPE) {
if (ntohs(lpIcmp6->icmp6_id) == mIdentifier) {
lReply.mResponded = true;
lReply.mSequence = ntohs(lpIcmp6->icmp6_seq);
// This backend does not request ancillary IPv6 hop-limit metadata.
lReply.mTtl = 0;
if (lReply.mSequence == aExpectedSequence) return lReply;
if (mReceivedSequences[lReply.mSequence]) mObservedDuplicates++;
}
}
} else {
// IPv4 ICMP packet includes IP header
if (lRecv < PingInternal::IP_HEADER_SIZE + PingInternal::ICMP_HEADER_SIZE) {
continue;
}
auto* lpIp = reinterpret_cast<ip*>(lBuffer.data());
int32_t lIpHdrLen = lpIp->ip_hl * 4;
if (lIpHdrLen < PingInternal::IP_HEADER_SIZE ||
lRecv < lIpHdrLen + PingInternal::ICMP_HEADER_SIZE) {
continue;
}
auto* lpIcmp = reinterpret_cast<icmp*>(lBuffer.data() + lIpHdrLen);
lReply.mIcmpType = lpIcmp->icmp_type;
lReply.mIcmpCode = lpIcmp->icmp_code;
lReply.mTtl = lpIp->ip_ttl;
if (lpIcmp->icmp_type == PingInternal::ICMP_ECHO_REPLY_TYPE) {
if (ntohs(lpIcmp->icmp_id) == mIdentifier) {
lReply.mResponded = true;
lReply.mSequence = ntohs(lpIcmp->icmp_seq);
if (lReply.mSequence == aExpectedSequence) return lReply;
if (mReceivedSequences[lReply.mSequence]) mObservedDuplicates++;
}
}
}
// Not our packet, keep waiting
int64_t lElapsed = (PingInternal::nowMicroseconds() - lStartTime) / 1000;
lRemainingMs = aTimeoutMs - static_cast<int32_t>(lElapsed);
}
return std::nullopt;
}
void Ping::computeStatistics(PingResult& rResult) {
auto& lStats = rResult.mStatistics;
// Count packets
lStats.mPacketsSent = static_cast<int32_t>(rResult.mReplies.size());
lStats.mPacketsReceived = 0;
lStats.mPacketsDuplicate = mObservedDuplicates;
std::vector<int64_t> lRtts;
lRtts.reserve(lStats.mPacketsSent);
for (const auto& lReply : rResult.mReplies) {
if (lReply.mResponded) {
lStats.mPacketsReceived++;
lRtts.push_back(lReply.mRttMicroseconds);
}
}
// Packet loss
if (lStats.mPacketsSent > 0) {
lStats.mPacketLossPercent = 100.0 *
(1.0 - static_cast<double>(lStats.mPacketsReceived) / lStats.mPacketsSent);
}
// RTT statistics
if (!lRtts.empty()) {
// Min/Max
lStats.mMinRttMicroseconds = *std::min_element(lRtts.begin(), lRtts.end());
lStats.mMaxRttMicroseconds = *std::max_element(lRtts.begin(), lRtts.end());
// Average
int64_t lSum = 0;
for (int64_t lRtt : lRtts) {
lSum += lRtt;
}
lStats.mAvgRttMicroseconds = lSum / static_cast<int64_t>(lRtts.size());
// Standard deviation (Welford's algorithm for numerical stability)
if (lRtts.size() > 1) {
double lMean = 0.0;
double lM2 = 0.0;
size_t lN = 0;
for (int64_t lRtt : lRtts) {
lN++;
double lDelta = static_cast<double>(lRtt) - lMean;
lMean += lDelta / lN;
double lDelta2 = static_cast<double>(lRtt) - lMean;
lM2 += lDelta * lDelta2;
}
lStats.mStdDevRttMicroseconds = std::sqrt(lM2 / (lN - 1));
}
// Jitter (average absolute difference between consecutive RTTs)
if (lRtts.size() > 1) {
double lJitterSum = 0.0;
for (size_t lI = 1; lI < lRtts.size(); ++lI) {
lJitterSum += std::abs(static_cast<double>(lRtts[lI] - lRtts[lI - 1]));
}
lStats.mJitterMicroseconds = lJitterSum / (lRtts.size() - 1);
}
}
}
PingResult Ping::ping(const std::string& aDestination, const PingConfig& aConfig) {
PingResult lResult;
lResult.mDestinationHostname = aDestination;
mStopped.store(false);
if (aConfig.mCount < 0 || aConfig.mIntervalMs < 0 || aConfig.mTimeoutMs <= 0 ||
aConfig.mFloodTimeoutMs <= 0 || aConfig.mPacketSize < PingInternal::ICMP_HEADER_SIZE) {
lResult.mError = PingError::INVALID_CONFIG;
return lResult;
}
// Resolve destination
sockaddr_storage lDestAddr{};
socklen_t lAddrLen = 0;
bool lIsV6 = false;
if (!resolveDestination(aDestination, aConfig.mIpVersion,
lDestAddr, lAddrLen, lIsV6)) {
lResult.mError = PingError::INVALID_ADDRESS;
return lResult;
}
lResult.mDestinationIp = addrToString(lDestAddr);
lResult.mIpVersion = lIsV6 ? PingIpVersion::V6 : PingIpVersion::V4;
if (aConfig.mVerbose) {
std::cout << "Ping target " << aDestination << " (" << lResult.mDestinationIp
<< "), IPv" << (lIsV6 ? '6' : '4')
<< ", raw-socket backend, " << aConfig.mPacketSize << " byte packets"
<< std::endl;
}
// Resolve hostname if requested
if (aConfig.mResolveHostname) {
lResult.mResolvedHostname = resolveHostname(lDestAddr, lAddrLen);
}
// Create socket
int32_t lSocket = createIcmpSocket(lIsV6);
if (lSocket < 0) {
if (errno == EPERM || errno == EACCES) {
lResult.mError = PingError::PERMISSION_DENIED;
} else {
lResult.mError = PingError::SOCKET_CREATE_ERROR;
}
return lResult;
}
// Initialize sequence tracking for duplicate detection
mReceivedSequences.clear();
mReceivedSequences.resize(65536, false);
mObservedDuplicates = 0;
// Start timing
auto lStartTime = std::chrono::steady_clock::now();
// Send pings
int32_t lCount = aConfig.mCount;
if (lCount == 0) {
lCount = INT32_MAX; // Infinite mode
}
int32_t lTimeoutMs = aConfig.mFloodMode ? aConfig.mFloodTimeoutMs : aConfig.mTimeoutMs;
for (int32_t lSeqIdx = 0; lSeqIdx < lCount && !mStopped.load(); ++lSeqIdx) {
uint16_t lSeq = static_cast<uint16_t>(lSeqIdx + 1);
int64_t lSendTime = PingInternal::nowMicroseconds();
bool lSent = sendPing(lSocket, lSeq, lDestAddr, lAddrLen, lIsV6, aConfig);
PingReply lReply;
lReply.mSequence = lSeq;
if (!lSent) {
lReply.mError = PingError::SEND_ERROR;
lResult.mReplies.push_back(lReply);
if (mOnReply) {
mOnReply(lReply);
}
} else {
auto lRecvResult = receiveReply(lSocket, lTimeoutMs, lIsV6, lSeq, lSendTime);
if (lRecvResult) {
lReply = *lRecvResult;
uint16_t lRecvSeq = lReply.mSequence;
mReceivedSequences[lRecvSeq] = true;
} else {
lReply.mError = PingError::TIMEOUT;
}
lResult.mReplies.push_back(lReply);
if (mOnReply) {
mOnReply(lReply);
}
}
// Wait for interval (unless flood mode or last ping)
if (!aConfig.mFloodMode && lSeqIdx < lCount - 1 && !mStopped.load()) {
int64_t lElapsedMs = (PingInternal::nowMicroseconds() - lSendTime) / 1000;
int64_t lSleepMs = aConfig.mIntervalMs - lElapsedMs;
if (lSleepMs > 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(lSleepMs));
}
}
}
// Calculate total time
auto lEndTime = std::chrono::steady_clock::now();
lResult.mStatistics.mTotalTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(
lEndTime - lStartTime).count();
// Compute statistics
computeStatistics(lResult);
close(lSocket);
return lResult;
}