-
Notifications
You must be signed in to change notification settings - Fork 2
/
pingutil.cc
682 lines (541 loc) · 20.6 KB
/
pingutil.cc
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
/*
========
Pingutil
========
Pingutil is a linux `ping` command clone written in C++.
It can send ICMPv4 and ICMPv6 `ECHO_REQUEST` to network hosts.
Currently, Pingutil only works on linux.
--------
Features
--------
1. Supports both ICMPv4 and ICMPv6 protocols (can work with IPv4 and IPv6 addresses).
Use arguments `-4` or `-6` to force pingutil to use ICMPv4 and ICMPv6 respectively.
2. Allows users to set Time to live (TTL) (or Hop Limit).
Use argument `--ttl` to set TTL on outgoing packets.
3. Performs automatic reverse DNS lookup.
4. Argument `--count` allows users to send a given number of ICMP ECHO requests.
-----
Usage
-----
Pingutil uses raw sockets (`SOCK_RAW`) hence requires root privileges to work.
Examples :-
>>> sudo ./pingutil google.com
PING del03s15-in-f14.1e100.net (172.217.167.14) with 56 bytes of data (icmp packet size = 64 bytes)
64 bytes from del03s15-in-f14.1e100.net (172.217.167.14): icmp_seq=1 ttl=52 time=90.4496ms
64 bytes from del03s15-in-f14.1e100.net (172.217.167.14): icmp_seq=2 ttl=52 time=123.118ms
64 bytes from del03s15-in-f14.1e100.net (172.217.167.14): icmp_seq=3 ttl=52 time=133.439ms
64 bytes from del03s15-in-f14.1e100.net (172.217.167.14): icmp_seq=4 ttl=52 time=113.994ms
64 bytes from del03s15-in-f14.1e100.net (172.217.167.14): icmp_seq=5 ttl=52 time=119.671ms
64 bytes from del03s15-in-f14.1e100.net (172.217.167.14): icmp_seq=6 ttl=52 time=120.836ms
64 bytes from del03s15-in-f14.1e100.net (172.217.167.14): icmp_seq=7 ttl=52 time=299.872ms
^C--- del03s15-in-f14.1e100.net ping statistics ---
7 packets transmitted, 7 received, 0.00% packet loss, time 1001.38ms
rtt min/avg/max/mdev = 90.45/143.05/299.87/22.40 ms
>>> sudo ./pingutil -6 google.com
PING del03s13-in-x0e.1e100.net (2404:6800:4002:808::200e) with 56 bytes of data (icmp packet size = 64 bytes)
64 bytes from del03s13-in-x0e.1e100.net (2404:6800:4002:808::200e): icmp_seq=1 ttl=64 time=100.335ms
64 bytes from del03s13-in-x0e.1e100.net (2404:6800:4002:808::200e): icmp_seq=2 ttl=64 time=67.382ms
64 bytes from del03s13-in-x0e.1e100.net (2404:6800:4002:808::200e): icmp_seq=3 ttl=64 time=109.401ms
64 bytes from del03s13-in-x0e.1e100.net (2404:6800:4002:808::200e): icmp_seq=4 ttl=64 time=110.298ms
64 bytes from del03s13-in-x0e.1e100.net (2404:6800:4002:808::200e): icmp_seq=5 ttl=64 time=97.8638ms
64 bytes from del03s13-in-x0e.1e100.net (2404:6800:4002:808::200e): icmp_seq=6 ttl=64 time=99.9024ms
^C--- del03s13-in-x0e.1e100.net ping statistics ---
6 packets transmitted, 6 received, 0.00% packet loss, time 585.18ms
rtt min/avg/max/mdev = 67.38/97.53/110.30/0.40 ms
>>> sudo ./pingutil --help
pingutil - Send ICMPv4/ICMPv6 ECHO_REQUEST to network hosts.
Example Usage : >> pingutil facebook.com
>> pingutil 157.240.16.35
>> pingutil --ttl 100 google.com
>> pingutil 2a03:2880:f12f:83:face:b00c:0:25de
>> pingutil -6 google.com
>> pingutil -c 10 -4 google.com
Usage:
pingutil [OPTION...] <destination_host>
-c, --count arg stop after given responses
--timeout arg time to wait for response in seconds (default: 3)
--ttl arg set time to live (default: 64)
-4, --forceip4 use IPv4
-6, --forceip6 use IPv6
-h, --help print help
>>> sudo ./pingutil --count 5 8.8.8.8
PING dns.google (8.8.8.8) with 56 bytes of data (icmp packet size = 64 bytes)
64 bytes from dns.google (8.8.8.8): icmp_seq=1 ttl=52 time=70.9144ms
64 bytes from dns.google (8.8.8.8): icmp_seq=2 ttl=52 time=107.195ms
64 bytes from dns.google (8.8.8.8): icmp_seq=3 ttl=52 time=73.7835ms
64 bytes from dns.google (8.8.8.8): icmp_seq=4 ttl=52 time=87.993ms
64 bytes from dns.google (8.8.8.8): icmp_seq=5 ttl=52 time=109.696ms
--- dns.google ping statistics ---
5 packets transmitted, 5 received, 0.00% packet loss, time 449.58ms
rtt min/avg/max/mdev = 70.91/89.92/109.70/3.96 ms
>>> sudo ./pingutil --ttl 1 -6 google.com
PING del03s15-in-x0e.1e100.net (2404:6800:4002:80a::200e) with 56 bytes of data (icmp packet size = 64 bytes)
Time Exceeded
Time Exceeded
Time Exceeded
Time Exceeded
Time Exceeded
^C--- del03s15-in-x0e.1e100.net ping statistics ---
5 packets transmitted, 0 received, 100.00% packet loss, time 0.00ms
rtt min/avg/max/mdev = inf/inf/0.00/inf ms
--------------------
Building from source
--------------------
>>> make
or
>>> g++ pingutil.cc -o pingutil
-----------------
See it in action
-----------------
https://asciinema.org/a/321259
*/
#include <string>
#include <cassert>
#include <iostream>
#include <cstdio>
#include <vector>
#include <iomanip>
#include <limits>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/ip_icmp.h>
#include <arpa/inet.h>
#include <netinet/icmp6.h>
#include <netinet/ip.h>
#include "include/cxxopts.hpp" /* external lib for argument parsing */
namespace pingutil {
class Pinger {
private:
int sockfd; /* file descriptor for the socket */
static const int ICMP_PACKET_SIZE = 64;
/* ICMP packets have 8 byte header followed by variable size data section
See https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol or https://tools.ietf.org/html/rfc792 */
struct icmp_packet {
struct icmphdr hdr;
char data[ICMP_PACKET_SIZE - sizeof(struct icmphdr)];
};
struct overall_stats {
int packets_transmitted; /* number of ECHO_REQUEST send */
int packets_received; /* number of ECHO_REPLY recevied */
std::vector<double> rtt; /* round trip delay time for each ECHO request */
} stats;
/* set by signal handler to exit ping loop */
bool exit_ping_loop = false;
/* Checksum() : calculates checksum for ICMP Header */
unsigned short Checksum(void *b, int len)
{ unsigned short *buf = (unsigned short *)b;
unsigned int sum=0;
unsigned short result;
for ( sum = 0; len > 1; len -= 2 )
sum += *buf++;
if ( len == 1 )
sum += *(unsigned char*)buf;
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
result = ~sum;
return result;
}
/* ResolveHostName() : Performs a DNS lookup for the given hostname */
sockaddr* ResolveHostName(std::string hostname, int addr_family) {
/* requested address must be either IPv4 or IPv6 */
if (addr_family != AF_INET && addr_family != AF_INET6)
return NULL;
struct sockaddr *saddr = NULL;
struct addrinfo *result;
int error;
/* resolve the hostname into a list of address */
if (error = getaddrinfo(hostname.c_str(), NULL, NULL, &result) != 0) {
return NULL;
}
/* use the first address from list of addresses returned by getaddrinfo() */
for (struct addrinfo *r = result; r != NULL; r = r->ai_next) {
if (r->ai_family == addr_family) {
if (r->ai_family == AF_INET) {
saddr = (sockaddr*) malloc(sizeof(sockaddr_in));
memcpy(saddr, r->ai_addr, sizeof(sockaddr_in));
}
else if (r->ai_family == AF_INET6){
saddr = (sockaddr*) malloc(sizeof(sockaddr_in6));
memcpy(saddr, r->ai_addr, sizeof(sockaddr_in6));
}
break;
}
}
freeaddrinfo(result);
return saddr;
}
/* GetHostName() : Performs a reverse DNS lookup for the given address */
char* GetHostName(struct sockaddr* address, int addrlen) {
char *hostname = (char*)malloc(256);
if ( getnameinfo(address, addrlen, hostname, 256, NULL, 0, NI_NAMEREQD) != 0) {
free(hostname);
return NULL;
}
return hostname;
}
/* PingV4() : Sends a ICMP ECHO request to the given IPv4 address. */
int PingV4(struct sockaddr_in *target, int ttl, int count, int timeout) {
if (target == NULL)
return -1;
/* create a raw socket. Creating a raw socket requires root privilges. */
int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if ( sockfd < 0 ) {
std::cout<<"Unable to create socket. Raw sockets require super user privileges.\n";
return -1;
}
/* set Time to Live (TTL) value */
if (setsockopt(sockfd, SOL_IP, IP_TTL, &ttl, sizeof(ttl)) != 0)
{
std::cout<<"Unable to set Time To Live (TTL). \n";
return -1;
}
/* set RECEIVE_TIMOUT on the socket as we don't want to wait forever for a response. */
struct timeval recvtimout;
recvtimout.tv_sec = timeout;
recvtimout.tv_usec = 0;
if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&recvtimout, sizeof(recvtimout)) != 0) {
std::cout<<"Unable to set Receive Timout. \n";
return -1;
}
char *domain_name = GetHostName((struct sockaddr *)target, sizeof(*target));
char ip[256];
inet_ntop(AF_INET, &(target->sin_addr), ip, 255);
struct icmp_packet ipkt;
unsigned int ping_cnt = 0;
char buf[512]; /* buffer to store incoming packets */
if (domain_name != NULL)
std::cout<<"PING "<<domain_name<<" ("<<ip<<") with 56 bytes of data (icmp packet size = 64 bytes)\n";
else
std::cout<<"PING "<<ip<<" with 56 bytes of data (icmp packet size = 64 bytes)\n";
while (!exit_ping_loop and ping_cnt < count) {
bzero(&ipkt, sizeof(ipkt));
ipkt.hdr.type = ICMP_ECHO;
ipkt.hdr.code = 0;
ipkt.hdr.un.echo.id = htons(getpid());
ipkt.hdr.un.echo.sequence = htons(++ping_cnt);
ipkt.hdr.checksum = Checksum(&ipkt, sizeof(ipkt));
/* remember the current time to calculate round trip delay */
struct timespec time_start, time_end;
clock_gettime(CLOCK_MONOTONIC, &time_start);
/* flag is whether packet was sent or not */
bool packet_sent = true;
if (sendto(sockfd, &ipkt, sizeof(ipkt), 0, (struct sockaddr*) target, sizeof(*target)) <= 0) {
std::cout<<"Unable to send packet. Retrying again. \n";
packet_sent = false;
}
stats.packets_transmitted++;
struct sockaddr_in recv_addr;
socklen_t addr_len = sizeof(recv_addr);
int tries = 3;
bool packet_received = false;
while (tries-- && !exit_ping_loop) {
if (packet_sent && recvfrom(sockfd, buf, 500, 0, (struct sockaddr*) &recv_addr, &addr_len) <= 0) {
continue;
}
else if (packet_sent) {
/* strip IPv4 header */
struct iphdr *iphdr = (struct iphdr *)buf;
struct icmp_packet *recv_icmp_pkt = (struct icmp_packet *)(buf + (iphdr->ihl << 2));
recv_icmp_pkt->hdr.type = ntohs(recv_icmp_pkt->hdr.type);
recv_icmp_pkt->hdr.un.echo.sequence = ntohs(recv_icmp_pkt->hdr.un.echo.sequence);
if (recv_icmp_pkt->hdr.type == ICMP_ECHOREPLY) {
if (recv_icmp_pkt->hdr.un.echo.sequence < ping_cnt)
continue;
stats.packets_received++;
clock_gettime(CLOCK_MONOTONIC, &time_end);
PrintStats(time_start, time_end, domain_name, ip, iphdr->ttl, recv_icmp_pkt->hdr.un.echo.sequence);
packet_received = true;
break;
}
if (recv_icmp_pkt->hdr.type == ICMP_DEST_UNREACH) {
std::cout<<"Destination Host Unreachable\n";
packet_received = true;
break;
}
if (recv_icmp_pkt->hdr.type == ICMP_TIME_EXCEEDED) {
std::cout<<"Time Exceeded\n";
packet_received = true;
break;
}
}
}
if (!packet_received) {
std::cout<<"Received No Response. \n";
}
/* sleep for 1 second */
usleep(1000000);
}
PrintOverallStats(domain_name, ip);
/* free memory */
if (domain_name)
free(domain_name);
close(sockfd);
return 0;
}
/* PingV6() : Sends a ICMPv6 ECHO request to the given IPv6 address. */
int PingV6(struct sockaddr_in6 *target, int ttl, int count, int timeout) {
if (target == NULL)
return -1;
/* create a raw socket. Creating a raw socket requires root privilges. */
int sockfd = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
if ( sockfd < 0 ) {
std::cout<<"Unable to create socket. Raw sockets require super user privileges.\n";
return -1;
}
\
/* set Time to Live (TTL) value */
if (setsockopt(sockfd, SOL_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof(ttl)) != 0)
{
std::cout<<"Unable to set Time To Live (TTL). \n";
return -1;
}
/* set RECEIVE_TIMOUT on the socket as we don't want to wait forever for a response. */
struct timeval recvtimout;
recvtimout.tv_sec = timeout;
recvtimout.tv_usec = 0;
if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&recvtimout, sizeof(recvtimout)) != 0) {
std::cout<<"Unable to set Receive Timout. \n";
return -1;
}
char *domain_name = GetHostName((struct sockaddr *)target, sizeof(*target));
char ip[256];
inet_ntop(AF_INET6, &(target->sin6_addr), ip, 255);
struct icmp_packet ipkt;
unsigned int ping_cnt = 0;
if (domain_name != NULL)
std::cout<<"PING "<<domain_name<<" ("<<ip<<") with 56 bytes of data (icmp packet size = 64 bytes)\n";
else
std::cout<<"PING "<<ip<<" with 56 bytes of data (icmp packet size = 64 bytes)\n";
while (!exit_ping_loop and ping_cnt < count) {
bzero(&ipkt, sizeof(ipkt));
ipkt.hdr.type = ICMP6_ECHO_REQUEST;
ipkt.hdr.code = 0;
ipkt.hdr.un.echo.id = getpid();
ipkt.hdr.un.echo.sequence = ++ping_cnt;
/* calculate checksum for the packet */
ipkt.hdr.checksum = Checksum(&ipkt, sizeof(ipkt));
/* remember the current time to calculate round trip delay */
struct timespec time_start, time_end;
clock_gettime(CLOCK_MONOTONIC, &time_start);
/* flag is whether packet was sent or not */
bool packet_sent = true;
if (sendto(sockfd, &ipkt, sizeof(ipkt), 0, (struct sockaddr*) target, sizeof(*target)) <= 0) {
std::cout<<"Unable to send packet. Retrying again. \n";
packet_sent = false;
}
stats.packets_transmitted++;
char buf[500]; /* to store the incoming packets */
struct sockaddr_in recv_addr;
socklen_t addr_len = sizeof(recv_addr);
int tries = 3;
bool packet_received = false;
while (tries-- && !exit_ping_loop) {
if (packet_sent && recvfrom(sockfd, buf, 500, 0, (struct sockaddr*) &recv_addr, &addr_len) <= 0) {
continue;
}
else if (packet_sent) {
struct icmp_packet *recv_icmp_pkt = (struct icmp_packet *)buf;
if (recv_icmp_pkt->hdr.type == ICMP6_ECHO_REPLY) {
if (recv_icmp_pkt->hdr.un.echo.sequence < ping_cnt)
continue;
stats.packets_received++;
clock_gettime(CLOCK_MONOTONIC, &time_end);
PrintStats(time_start, time_end, domain_name, ip, ttl, recv_icmp_pkt->hdr.un.echo.sequence);
packet_received = true;
break;
}
if (recv_icmp_pkt->hdr.type == ICMP6_DST_UNREACH) {
std::cout<<"Destination Host Unreachable\n";
packet_received = true;
break;
}
if (recv_icmp_pkt->hdr.type == ICMP6_TIME_EXCEEDED) {
std::cout<<"Time Exceeded\n";
packet_received = true;
break;
}
}
}
if (!packet_received) {
std::cout<<"Received No Response. \n";
}
/* sleep for 1 second */
usleep(1000000);
}
PrintOverallStats(domain_name, ip);
/* free memory */
if (domain_name)
free(domain_name);
close(sockfd);
return 0;
}
/* PrintStats() : prints statistics for a single ping. */
void PrintStats(struct timespec time_start, struct timespec time_end, char *domain_name, char *ip, int ttl, int imcp_seq) {
double rtt; /* round trip delay in milliseconds */
rtt = double(time_end.tv_sec - time_start.tv_sec) * 1000.0 + double(time_end.tv_nsec - time_start.tv_nsec) / 1000000.0;
stats.rtt.push_back(rtt); /* keep rtt to gather overall statistics */
std::cout<<ICMP_PACKET_SIZE<<" bytes from ";
if (domain_name)
std::cout<<domain_name<<" ("<<ip<<")";
else
std::cout<<ip;
std::cout<<": icmp_seq="<<imcp_seq<<" ttl="<<ttl<<" time="<<rtt<<"ms\n";
}
/* PrintOverallStats() : prints statistics for a single ping. */
void PrintOverallStats(char *domain_name, char *ip) {
if (domain_name)
std::cout<<"--- "<<domain_name<<" ping statistics ---\n";
else
std::cout<<"--- "<<ip<<" ping statistics ---\n";
double total_rtt;
double min_rtt = std::numeric_limits<double>::infinity();
double max_rtt = 0;
double avg_rtt;
double mdev_rtt;
for (double rtt : stats.rtt) {
total_rtt += rtt;
min_rtt = std::min(min_rtt, rtt);
max_rtt = std::max(max_rtt, rtt);
}
avg_rtt = total_rtt / stats.rtt.size();
for (double rtt : stats.rtt)
mdev_rtt = abs(rtt - avg_rtt);
mdev_rtt /= stats.rtt.size();
double loss = 1 - (double(stats.packets_received)/stats.packets_transmitted);
loss = loss * 100;
std::cout<<stats.packets_transmitted<<" packets transmitted, "<<stats.packets_received<<" received, "
<<std::fixed<<std::setprecision(2)<<loss<<"% packet loss, time "<<total_rtt<<"ms\n"
<<"rtt min/avg/max/mdev = "<<min_rtt<<"/"<<avg_rtt<<"/"<<max_rtt<<"/"<<mdev_rtt<<" ms\n";
}
public:
void StopPingLoop() {
exit_ping_loop = true;
}
/* Ping() : Pings the host specified by the given IPv4/IPv6 address or domain name. */
int Ping(std::string host, int ttl, int count, int timeout, bool forceip4=false, bool forceip6=false) {
/* if IPv4 address is provided */
if (std::count(host.begin(), host.end(), '.') == 3) {
bool valid_ip4 = true;
for (char c : host)
if (c != '.' && !isdigit(c)) {
valid_ip4 = false;
break;
}
if (forceip6) {
std::cout<<"Address family for hostname not supported.\n";
return -1;
}
if (valid_ip4) {
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = 0;
inet_pton(AF_INET, host.c_str(), &(addr.sin_addr));
return PingV4(&addr, ttl, count, timeout);
}
}
/* if IPv6 address is provided */
if (std::count(host.begin(), host.end(), '.') == 0 && std::count(host.begin(), host.end(), ':')) {
if (forceip4) {
std::cout<<"Address family for hostname not supported.\n";
return -1;
}
struct sockaddr_in6 addr;
addr.sin6_family = AF_INET6;
addr.sin6_port = 0;
inet_pton(AF_INET6, host.c_str(), &(addr.sin6_addr));
return PingV6(&addr, ttl, count, timeout);
}
/* Since we exhausted all possibilities, assuming hostname is provided */
if (forceip4 || !forceip6) {
struct sockaddr_in *addr = (sockaddr_in*) ResolveHostName(host.c_str(), AF_INET);
if (!addr) {
std::cout<<"Unable to resolve hostname.\n";
return -1;
}
int err = PingV4(addr, ttl, count, timeout);
free(addr);
return err;
}
/* Must be forced IPv6 */
struct sockaddr_in6 *addr = (sockaddr_in6*) ResolveHostName(host.c_str(), AF_INET6);
if (!addr) {
std::cout<<"Unable to resolve hostname.\n";
return -1;
}
int err = PingV6(addr, ttl, count, timeout);
free(addr);
return err;
}
};
}
/* Instance of Pinger */
pingutil::Pinger pngr;
/* Signal Handler for SIG_INT (Ctrl + C) */
void SigIntHandler(int sig) {
pngr.StopPingLoop();
}
int main(int argc, char *argv[]) {
std::string help_str = "pingutil - Send ICMPv4/ICMPv6 ECHO_REQUEST to network hosts.\n"
"\nExample Usage : >> pingutil facebook.com"
"\n >> pingutil 157.240.16.35"
"\n >> pingutil --ttl 100 google.com"
"\n >> pingutil 2a03:2880:f12f:83:face:b00c:0:25de"
"\n >> pingutil -6 google.com"
"\n >> pingutil -c 10 -4 google.com \n";
cxxopts::Options options("pingutil", help_str);
options.positional_help("<destination_host>");
options.add_options()
("c,count", "stop after given responses", cxxopts::value<int>())
("timeout", "time to wait for response in seconds", cxxopts::value<int>()->default_value("3"))
("ttl", "set time to live", cxxopts::value<int>()->default_value("64"))
("4,forceip4", "use IPv4")
("6,forceip6", "use IPv6")
("h,help", "print help")
("destination_host", "Hostname or IPv4/IPv6 address of the destination network host", cxxopts::value<std::string>())
;
options.parse_positional({"destination_host"});
auto args = options.parse(argc, argv);
/* print help */
if (args.count("help")) {
std::cout<<options.help()<<'\n';
return 0;
}
/* extract options from arguments */
int count = 1000; /* no limit */
int timeout = 3; /* 3 seconds */
int ttl = 64; /* deafult time to live */
bool forceip4 = false;
bool forceip6 = false;
std::string destination_host;
if (args.count("count")) {
count = args["count"].as<int>();
}
if (args.count("timeout")) {
timeout = args["timeout"].as<int>();
}
if (args.count("ttl")) {
ttl = args["ttl"].as<int>();
}
if (args.count("forceip4")) {
forceip4 = true;
}
if (args.count("forceip6")) {
forceip6 = true;
}
if (!args.count("destination_host")) {
std::cout<<"Please specify a network host to send ICMP ECHO requests. Use --help option to learn more.\n";
return 0;
}
destination_host = args["destination_host"].as<std::string>();
signal(SIGINT, SigIntHandler);
pngr.Ping(destination_host, ttl, count, timeout, forceip4, forceip6);
return 0;
}