Repository navigation
Expand file tree
/
Copy pathPingWindows.cpp
More file actions
261 lines (226 loc) · 10.3 KB
/
Copy pathPingWindows.cpp
File metadata and controls
261 lines (226 loc) · 10.3 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
// Native Windows ICMP implementation using the IP Helper API.
#include "Ping.h"
#include <iphlpapi.h>
#include <icmpapi.h>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <mutex>
#include <thread>
#include "NameResolver.h"
namespace PingWindowsInternal {
constexpr size_t ICMP_HEADER_SIZE = 8;
bool ensureWinsock() {
static std::once_flag lOnce;
static bool lReady = false;
std::call_once(lOnce, [] {
WSADATA lData{};
lReady = WSAStartup(MAKEWORD(2, 2), &lData) == 0;
});
return lReady;
}
std::string ipv4ToString(IPAddr aAddress) {
IN_ADDR lAddress{};
lAddress.S_un.S_addr = aAddress;
char lBuffer[INET_ADDRSTRLEN]{};
return InetNtopA(AF_INET, &lAddress, lBuffer, sizeof(lBuffer)) ? lBuffer : "";
}
std::string ipv6ToString(const IPV6_ADDRESS_EX& aAddress) {
IN6_ADDR lAddress{};
std::memcpy(&lAddress, aAddress.sin6_addr, sizeof(lAddress));
char lBuffer[INET6_ADDRSTRLEN]{};
return InetNtopA(AF_INET6, &lAddress, lBuffer, sizeof(lBuffer)) ? lBuffer : "";
}
} // namespace PingWindowsInternal
Ping::Ping() = default;
Ping::~Ping() = default;
bool Ping::canPing() {
if (!PingWindowsInternal::ensureWinsock()) return false;
HANDLE lHandle = IcmpCreateFile();
if (lHandle == INVALID_HANDLE_VALUE) return false;
IcmpCloseHandle(lHandle);
return true;
}
bool Ping::isIPv6Available() {
if (!PingWindowsInternal::ensureWinsock()) return false;
HANDLE lHandle = Icmp6CreateFile();
if (lHandle == INVALID_HANDLE_VALUE) return false;
IcmpCloseHandle(lHandle);
return true;
}
void Ping::setOnReply(OnPingReplyCallback aCallback) {
mOnReply = std::move(aCallback);
}
void Ping::stop() {
mStopped.store(true);
}
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{};
}
void Ping::computeStatistics(PingResult& rResult) {
auto& lStats = rResult.mStatistics;
lStats.mPacketsSent = static_cast<int32_t>(rResult.mReplies.size());
lStats.mPacketsReceived = 0;
lStats.mPacketsDuplicate = 0;
std::vector<int64_t> lRtts;
for (const auto& lReply : rResult.mReplies) {
if (lReply.mResponded) {
lStats.mPacketsReceived++;
lRtts.push_back(lReply.mRttMicroseconds);
}
}
if (lStats.mPacketsSent > 0) {
lStats.mPacketLossPercent = 100.0 *
(1.0 - static_cast<double>(lStats.mPacketsReceived) / lStats.mPacketsSent);
}
if (lRtts.empty()) return;
lStats.mMinRttMicroseconds = *std::min_element(lRtts.begin(), lRtts.end());
lStats.mMaxRttMicroseconds = *std::max_element(lRtts.begin(), lRtts.end());
int64_t lSum = 0;
for (auto lRtt : lRtts) lSum += lRtt;
lStats.mAvgRttMicroseconds = lSum / static_cast<int64_t>(lRtts.size());
if (lRtts.size() > 1) {
double lSquaredDifference = 0.0;
double lJitter = 0.0;
for (size_t lIndex = 0; lIndex < lRtts.size(); ++lIndex) {
const double lDifference = lRtts[lIndex] - lStats.mAvgRttMicroseconds;
lSquaredDifference += lDifference * lDifference;
if (lIndex > 0) lJitter += std::abs(lRtts[lIndex] - lRtts[lIndex - 1]);
}
lStats.mStdDevRttMicroseconds =
std::sqrt(lSquaredDifference / static_cast<double>(lRtts.size() - 1));
lStats.mJitterMicroseconds = lJitter / static_cast<double>(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 < PingWindowsInternal::ICMP_HEADER_SIZE) {
lResult.mError = PingError::INVALID_CONFIG;
return lResult;
}
sockaddr_storage lDestination{};
socklen_t lDestinationLength = 0;
bool lIsV6 = false;
if (!resolveDestination(aDestination, aConfig.mIpVersion,
lDestination, lDestinationLength, lIsV6)) {
lResult.mError = PingError::INVALID_ADDRESS;
return lResult;
}
lResult.mDestinationIp = addrToString(lDestination);
lResult.mIpVersion = lIsV6 ? PingIpVersion::V6 : PingIpVersion::V4;
if (aConfig.mVerbose) {
std::cout << "Ping target " << aDestination << " (" << lResult.mDestinationIp
<< "), IPv" << (lIsV6 ? '6' : '4')
<< ", Windows IP Helper backend, " << aConfig.mPacketSize
<< " byte packets" << std::endl;
}
if (aConfig.mResolveHostname) {
lResult.mResolvedHostname = resolveHostname(lDestination, lDestinationLength);
}
HANDLE lIcmp = lIsV6 ? Icmp6CreateFile() : IcmpCreateFile();
if (lIcmp == INVALID_HANDLE_VALUE) {
lResult.mError = PingError::SOCKET_CREATE_ERROR;
return lResult;
}
const size_t lPayloadSize = aConfig.mPacketSize - PingWindowsInternal::ICMP_HEADER_SIZE;
std::vector<uint8_t> lPayload(lPayloadSize, 0x42);
const DWORD lTimeout = static_cast<DWORD>(
aConfig.mFloodMode ? aConfig.mFloodTimeoutMs : aConfig.mTimeoutMs);
int32_t lCount = aConfig.mCount == 0 ? INT32_MAX : aConfig.mCount;
const auto lStart = std::chrono::steady_clock::now();
for (int32_t lIndex = 0; lIndex < lCount && !mStopped.load(); ++lIndex) {
const auto lSendStart = std::chrono::steady_clock::now();
PingReply lReply;
lReply.mSequence = static_cast<uint16_t>(lIndex + 1);
IP_OPTION_INFORMATION lOptions{};
lOptions.Ttl = aConfig.mTtl;
if (!lIsV6) {
const auto* lpDestination = reinterpret_cast<const sockaddr_in*>(&lDestination);
std::vector<uint8_t> lReplyBuffer(sizeof(ICMP_ECHO_REPLY) + lPayload.size() + 8);
const DWORD lCountReceived = IcmpSendEcho(
lIcmp, lpDestination->sin_addr.s_addr,
lPayload.empty() ? nullptr : lPayload.data(), static_cast<WORD>(lPayload.size()),
&lOptions, lReplyBuffer.data(), static_cast<DWORD>(lReplyBuffer.size()), lTimeout);
if (lCountReceived > 0) {
const auto* lpReply = reinterpret_cast<const ICMP_ECHO_REPLY*>(lReplyBuffer.data());
if (lpReply->Status == IP_SUCCESS) {
lReply.mResponded = true;
lReply.mRttMicroseconds = static_cast<int64_t>(lpReply->RoundTripTime) * 1000;
lReply.mFromIp = PingWindowsInternal::ipv4ToString(lpReply->Address);
lReply.mTtl = lpReply->Options.Ttl;
lReply.mIcmpType = 0;
} else {
lReply.mError = lpReply->Status == IP_REQ_TIMED_OUT
? PingError::TIMEOUT : PingError::UNKNOWN_ERROR;
}
} else {
lReply.mError = PingError::TIMEOUT;
}
} else {
sockaddr_in6 lSource{};
lSource.sin6_family = AF_INET6;
auto lDestination6 = *reinterpret_cast<const sockaddr_in6*>(&lDestination);
std::vector<uint8_t> lReplyBuffer(sizeof(ICMPV6_ECHO_REPLY) + lPayload.size() + 32);
const DWORD lCountReceived = Icmp6SendEcho2(
lIcmp, nullptr, nullptr, nullptr, &lSource, &lDestination6,
lPayload.empty() ? nullptr : lPayload.data(), static_cast<WORD>(lPayload.size()),
&lOptions, lReplyBuffer.data(), static_cast<DWORD>(lReplyBuffer.size()), lTimeout);
if (lCountReceived > 0) {
const auto* lpReply = reinterpret_cast<const ICMPV6_ECHO_REPLY*>(lReplyBuffer.data());
if (lpReply->Status == IP_SUCCESS) {
lReply.mResponded = true;
lReply.mRttMicroseconds = static_cast<int64_t>(lpReply->RoundTripTime) * 1000;
lReply.mFromIp = PingWindowsInternal::ipv6ToString(lpReply->Address);
// IP Helper does not expose the IPv6 reply hop limit.
lReply.mTtl = 0;
lReply.mIcmpType = 129;
} else {
lReply.mError = lpReply->Status == IP_REQ_TIMED_OUT
? PingError::TIMEOUT : PingError::UNKNOWN_ERROR;
}
} else {
lReply.mError = PingError::TIMEOUT;
}
}
lResult.mReplies.push_back(lReply);
if (mOnReply) mOnReply(lReply);
if (!aConfig.mFloodMode && lIndex < lCount - 1 && !mStopped.load()) {
const auto lElapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - lSendStart).count();
if (lElapsed < aConfig.mIntervalMs) {
std::this_thread::sleep_for(std::chrono::milliseconds(aConfig.mIntervalMs - lElapsed));
}
}
}
lResult.mStatistics.mTotalTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - lStart).count();
computeStatistics(lResult);
IcmpCloseHandle(lIcmp);
return lResult;
}