Repository navigation
Expand file tree
/
Copy pathping_main.cpp
More file actions
291 lines (253 loc) · 10.3 KB
/
Copy pathping_main.cpp
File metadata and controls
291 lines (253 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
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
// ping_main.cpp
// CLI demo for Ping class
// Usage: ./ping_demo <destination> [options]
#include "Ping.h"
#include <csignal>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <string>
namespace PingDemo {
// Global ping instance for signal handling
Ping* gpPing = nullptr;
void signalHandler(int aSignal) {
static_cast<void>(aSignal);
if (gpPing) {
gpPing->stop();
}
}
void printUsage(const char* apProgram) {
std::cout << "Usage: " << apProgram << " <destination> [options]" << std::endl
<< std::endl;
std::cout << "Options:" << std::endl;
std::cout << " -c, --count <n> Number of pings to send (default: 4, 0=infinite)" << std::endl;
std::cout << " -i, --interval <ms> Interval between pings in milliseconds (default: 1000)" << std::endl;
std::cout << " -W, --timeout <ms> Timeout per ping in milliseconds (default: 3000)" << std::endl;
std::cout << " -s, --size <bytes> Packet size in bytes (default: 64)" << std::endl;
std::cout << " -t, --ttl <n> Time to live (default: 64)" << std::endl;
std::cout << " -f, --flood Flood mode: send as fast as possible" << std::endl;
std::cout << " -4, --ipv4 Force IPv4" << std::endl;
std::cout << " -6, --ipv6 Force IPv6" << std::endl;
std::cout << " -n, --no-dns Disable reverse DNS lookup" << std::endl;
std::cout << " -q, --quiet Quiet mode: only show statistics" << std::endl;
std::cout << " -v, --verbose Print target, IP family, backend, and packet size" << std::endl;
std::cout << " -h, --help Show this help message" << std::endl;
std::cout << std::endl << "Examples:" << std::endl;
std::cout << " " << apProgram << " google.com" << std::endl;
std::cout << " " << apProgram << " 8.8.8.8 -c 10 -i 500" << std::endl;
std::cout << " " << apProgram << " ::1 -6" << std::endl;
std::cout << " " << apProgram << " 192.168.1.1 -f -c 100" << std::endl;
#if defined(__linux__)
std::cout << std::endl
<< "Permission: this Unix backend uses raw ICMP sockets. Grant CAP_NET_RAW"
<< std::endl;
std::cout << "to this executable after building, or run an individual command as root."
<< std::endl;
#elif defined(__APPLE__)
std::cout << std::endl
<< "Permission: this Unix backend uses raw ICMP sockets and must run as root."
<< std::endl;
#endif
}
void printReply(const PingReply& aReply, bool aQuiet) {
if (aQuiet) {
return;
}
if (aReply.mResponded) {
std::cout << "Reply from " << aReply.mFromIp;
std::cout << ": icmp_seq=" << aReply.mSequence;
std::cout << " ttl=" << static_cast<int>(aReply.mTtl);
std::cout << " time=" << std::fixed << std::setprecision(3)
<< (aReply.mRttMicroseconds / 1000.0) << " ms";
std::cout << std::endl;
} else {
std::cout << "Request timeout for icmp_seq " << aReply.mSequence << std::endl;
}
}
void printStatistics(const PingResult& aResult) {
std::cout << std::endl << "--- " << aResult.mDestinationHostname
<< " ping statistics ---" << std::endl;
const auto& lStats = aResult.mStatistics;
std::cout << lStats.mPacketsSent << " packets transmitted, "
<< lStats.mPacketsReceived << " received";
if (lStats.mPacketsDuplicate > 0) {
std::cout << ", +" << lStats.mPacketsDuplicate << " duplicates";
}
std::cout << ", " << std::fixed << std::setprecision(1)
<< lStats.mPacketLossPercent << "% packet loss";
std::cout << ", time " << lStats.mTotalTimeMs << " ms" << std::endl;
if (lStats.mPacketsReceived > 0) {
std::cout << "rtt min/avg/max/mdev = "
<< std::fixed << std::setprecision(3)
<< (lStats.mMinRttMicroseconds / 1000.0) << "/"
<< (lStats.mAvgRttMicroseconds / 1000.0) << "/"
<< (lStats.mMaxRttMicroseconds / 1000.0) << "/"
<< (lStats.mStdDevRttMicroseconds / 1000.0) << " ms";
if (lStats.mJitterMicroseconds > 0) {
std::cout << ", jitter " << (lStats.mJitterMicroseconds / 1000.0) << " ms";
}
std::cout << std::endl;
}
}
} // namespace PingDemo
int main(int aArgc, char** apArgv) {
if (aArgc < 2) {
PingDemo::printUsage(apArgv[0]);
return 1;
}
std::string lDestination;
PingConfig lConfig;
bool lQuiet = false;
// Parse arguments
for (int lI = 1; lI < aArgc; ++lI) {
std::string lArg = apArgv[lI];
if (lArg == "-h" || lArg == "--help") {
PingDemo::printUsage(apArgv[0]);
return 0;
} else if (lArg == "-c" || lArg == "--count") {
if (++lI < aArgc) {
lConfig.mCount = std::atoi(apArgv[lI]);
}
} else if (lArg == "-i" || lArg == "--interval") {
if (++lI < aArgc) {
lConfig.mIntervalMs = std::atoi(apArgv[lI]);
}
} else if (lArg == "-W" || lArg == "--timeout") {
if (++lI < aArgc) {
lConfig.mTimeoutMs = std::atoi(apArgv[lI]);
}
} else if (lArg == "-s" || lArg == "--size") {
if (++lI < aArgc) {
lConfig.mPacketSize = static_cast<uint16_t>(std::atoi(apArgv[lI]));
}
} else if (lArg == "-t" || lArg == "--ttl") {
if (++lI < aArgc) {
lConfig.mTtl = static_cast<uint8_t>(std::atoi(apArgv[lI]));
}
} else if (lArg == "-f" || lArg == "--flood") {
lConfig.mFloodMode = true;
} else if (lArg == "-4" || lArg == "--ipv4") {
lConfig.mIpVersion = PingIpVersion::V4;
} else if (lArg == "-6" || lArg == "--ipv6") {
lConfig.mIpVersion = PingIpVersion::V6;
} else if (lArg == "-n" || lArg == "--no-dns") {
lConfig.mResolveHostname = false;
} else if (lArg == "-q" || lArg == "--quiet") {
lQuiet = true;
} else if (lArg == "-v" || lArg == "--verbose") {
lConfig.mVerbose = true;
} else if (lArg[0] != '-') {
lDestination = lArg;
} else {
std::cerr << "Unknown option: " << lArg << std::endl;
PingDemo::printUsage(apArgv[0]);
return 1;
}
}
if (lDestination.empty()) {
std::cerr << "Error: No destination specified" << std::endl;
PingDemo::printUsage(apArgv[0]);
return 1;
}
// Check permissions
if (!Ping::canPing()) {
#ifdef _WIN32
std::cerr << "Error: Windows ICMP services are unavailable." << std::endl;
#elif defined(__linux__)
std::cerr << "Error: Ping uses a raw ICMP socket and needs CAP_NET_RAW." << std::endl;
std::cerr << " Grant it with: sudo setcap cap_net_raw+ep " << apArgv[0] << std::endl;
#else
std::cerr << "Error: Ping uses a raw ICMP socket and must run as root." << std::endl;
#endif
return 1;
}
// Check IPv6 if requested
if (lConfig.mIpVersion == PingIpVersion::V6 && !Ping::isIPv6Available()) {
std::cerr << "Error: IPv6 is not available on this system." << std::endl;
return 1;
}
Ping lPing;
PingDemo::gpPing = &lPing;
// Set up signal handler for Ctrl+C
std::signal(SIGINT, PingDemo::signalHandler);
std::signal(SIGTERM, PingDemo::signalHandler);
// Set callback for real-time output
if (!lQuiet && !lConfig.mFloodMode) {
lPing.setOnReply([lQuiet](const PingReply& aReply) {
PingDemo::printReply(aReply, lQuiet);
});
}
// Print header
if (!lQuiet) {
std::cout << "PING " << lDestination;
// Resolve to show IP
addrinfo lHints{};
addrinfo* lpResult = nullptr;
lHints.ai_family = lConfig.mIpVersion == PingIpVersion::V4 ? AF_INET
: lConfig.mIpVersion == PingIpVersion::V6 ? AF_INET6
: AF_UNSPEC;
lHints.ai_socktype = SOCK_DGRAM;
if (getaddrinfo(lDestination.c_str(), nullptr, &lHints, &lpResult) == 0 && lpResult) {
char lBuf[INET6_ADDRSTRLEN];
if (lpResult->ai_family == AF_INET) {
auto* lpAddr4 = reinterpret_cast<sockaddr_in*>(lpResult->ai_addr);
inet_ntop(AF_INET, &lpAddr4->sin_addr, lBuf, sizeof(lBuf));
std::cout << " (" << lBuf << ")";
} else if (lpResult->ai_family == AF_INET6) {
auto* lpAddr6 = reinterpret_cast<sockaddr_in6*>(lpResult->ai_addr);
inet_ntop(AF_INET6, &lpAddr6->sin6_addr, lBuf, sizeof(lBuf));
std::cout << " (" << lBuf << ")";
}
freeaddrinfo(lpResult);
}
std::cout << " " << lConfig.mPacketSize << " bytes of data";
if (lConfig.mFloodMode) {
std::cout << " (flood mode)";
}
std::cout << std::endl;
}
// Flood mode output
if (lConfig.mFloodMode && !lQuiet) {
lPing.setOnReply([](const PingReply& aReply) {
if (aReply.mResponded) {
std::cout << "." << std::flush;
} else {
std::cout << "!" << std::flush;
}
});
}
// Run ping
auto lResult = lPing.ping(lDestination, lConfig);
if (lConfig.mFloodMode && !lQuiet) {
std::cout << std::endl;
}
// Handle errors
if (lResult.mError != PingError::SUCCESS) {
switch (lResult.mError) {
case PingError::INVALID_ADDRESS:
std::cerr << "Error: Invalid address or hostname" << std::endl;
break;
case PingError::INVALID_CONFIG:
std::cerr << "Error: Invalid ping configuration" << std::endl;
break;
case PingError::PERMISSION_DENIED:
std::cerr << "Error: Permission denied" << std::endl;
break;
case PingError::SOCKET_CREATE_ERROR:
std::cerr << "Error: Failed to create socket" << std::endl;
break;
default:
std::cerr << "Error: Ping failed" << std::endl;
break;
}
return 1;
}
// Print statistics
PingDemo::printStatistics(lResult);
PingDemo::gpPing = nullptr;
// Return code based on packet loss
if (lResult.mStatistics.mPacketsReceived == 0) {
return 1;
}
return 0;
}