1 /* vi: set sw=4 ts=4: */
3 * Mini ping implementation for busybox
5 * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
7 * Adapted from the ping in netkit-base 0.10:
8 * Copyright (c) 1989 The Regents of the University of California.
11 * This code is derived from software contributed to Berkeley by
14 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
17 * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
19 * This version of ping is adapted from the ping in netkit-base 0.10,
22 * Original copyright notice is retained at the end of this file.
24 * This version is an adaptation of ping.c from busybox.
25 * The code was modified by Bart Visscher <magick@linux-fan.com>
28 //config: bool "ping (9.5 kb)"
30 //config: select PLATFORM_LINUX
32 //config: ping uses the ICMP protocol's mandatory ECHO_REQUEST datagram to
33 //config: elicit an ICMP ECHO_RESPONSE from a host or gateway.
36 //config: bool "ping6 (10 kb)"
38 //config: depends on FEATURE_IPV6
40 //config: Alias to "ping -6".
42 //config:config FEATURE_FANCY_PING
43 //config: bool "Enable fancy ping output"
45 //config: depends on PING || PING6
47 //config: With this option off, ping will say "HOST is alive!"
48 //config: or terminate with SIGALRM in 5 seconds otherwise.
49 //config: No command-line options will be recognized.
51 /* Needs socket(AF_INET, SOCK_RAW, IPPROTO_ICMP), therefore BB_SUID_MAYBE: */
52 //applet:IF_PING(APPLET(ping, BB_DIR_BIN, BB_SUID_MAYBE))
53 //applet:IF_PING6(APPLET(ping6, BB_DIR_BIN, BB_SUID_MAYBE))
55 //kbuild:lib-$(CONFIG_PING) += ping.o
56 //kbuild:lib-$(CONFIG_PING6) += ping.o
58 //usage:#if !ENABLE_FEATURE_FANCY_PING
59 //usage:# define ping_trivial_usage
61 //usage:# define ping_full_usage "\n\n"
62 //usage: "Send ICMP ECHO_REQUEST packets to network hosts"
63 //usage:# define ping6_trivial_usage
65 //usage:# define ping6_full_usage "\n\n"
66 //usage: "Send ICMP ECHO_REQUEST packets to network hosts"
68 //usage:# define ping_trivial_usage
69 //usage: "[OPTIONS] HOST"
70 //usage:# define ping_full_usage "\n\n"
71 //usage: "Send ICMP ECHO_REQUEST packets to network hosts\n"
73 //usage: "\n -4,-6 Force IP or IPv6 name resolution"
75 //usage: "\n -c CNT Send only CNT pings"
76 //usage: "\n -s SIZE Send SIZE data bytes in packets (default 56)"
77 //usage: "\n -A Ping as soon as reply is recevied"
78 //usage: "\n -t TTL Set TTL"
79 //usage: "\n -I IFACE/IP Source interface or IP address"
80 //usage: "\n -W SEC Seconds to wait for the first response (default 10)"
81 //usage: "\n (after all -c CNT packets are sent)"
82 //usage: "\n -w SEC Seconds until ping exits (default:infinite)"
83 //usage: "\n (can exit earlier with -c CNT)"
84 //usage: "\n -q Quiet, only display output at start"
85 //usage: "\n and when finished"
86 //usage: "\n -p HEXBYTE Pattern to use for payload"
88 //usage:# define ping6_trivial_usage
89 //usage: "[OPTIONS] HOST"
90 //usage:# define ping6_full_usage "\n\n"
91 //usage: "Send ICMP ECHO_REQUEST packets to network hosts\n"
92 //usage: "\n -c CNT Send only CNT pings"
93 //usage: "\n -s SIZE Send SIZE data bytes in packets (default 56)"
94 //usage: "\n -A Ping as soon as reply is recevied"
95 //usage: "\n -I IFACE/IP Source interface or IP address"
96 //usage: "\n -q Quiet, only display output at start"
97 //usage: "\n and when finished"
98 //usage: "\n -p HEXBYTE Pattern to use for payload"
102 //usage:#define ping_example_usage
103 //usage: "$ ping localhost\n"
104 //usage: "PING slag (127.0.0.1): 56 data bytes\n"
105 //usage: "64 bytes from 127.0.0.1: icmp_seq=0 ttl=255 time=20.1 ms\n"
107 //usage: "--- debian ping statistics ---\n"
108 //usage: "1 packets transmitted, 1 packets received, 0% packet loss\n"
109 //usage: "round-trip min/avg/max = 20.1/20.1/20.1 ms\n"
110 //usage:#define ping6_example_usage
111 //usage: "$ ping6 ip6-localhost\n"
112 //usage: "PING ip6-localhost (::1): 56 data bytes\n"
113 //usage: "64 bytes from ::1: icmp6_seq=0 ttl=64 time=20.1 ms\n"
115 //usage: "--- ip6-localhost ping statistics ---\n"
116 //usage: "1 packets transmitted, 1 packets received, 0% packet loss\n"
117 //usage: "round-trip min/avg/max = 20.1/20.1/20.1 ms\n"
120 #include <netinet/ip_icmp.h>
122 #include "common_bufsiz.h"
125 /* should be in netinet/ip_icmp.h */
126 # define ICMP_DEST_UNREACH 3 /* Destination Unreachable */
127 # define ICMP_SOURCE_QUENCH 4 /* Source Quench */
128 # define ICMP_REDIRECT 5 /* Redirect (change route) */
129 # define ICMP_ECHO 8 /* Echo Request */
130 # define ICMP_TIME_EXCEEDED 11 /* Time Exceeded */
131 # define ICMP_PARAMETERPROB 12 /* Parameter Problem */
132 # define ICMP_TIMESTAMP 13 /* Timestamp Request */
133 # define ICMP_TIMESTAMPREPLY 14 /* Timestamp Reply */
134 # define ICMP_INFO_REQUEST 15 /* Information Request */
135 # define ICMP_INFO_REPLY 16 /* Information Reply */
136 # define ICMP_ADDRESS 17 /* Address Mask Request */
137 # define ICMP_ADDRESSREPLY 18 /* Address Mask Reply */
140 /* Some operating systems, like GNU/Hurd, don't define SOL_RAW, but do have
141 * IPPROTO_RAW. Since the IPPROTO definitions are also valid to use for
142 * setsockopt (and take the same value as their corresponding SOL definitions,
143 * if they exist), we can just fall back on IPPROTO_RAW. */
145 # define SOL_RAW IPPROTO_RAW
149 # include <netinet/icmp6.h>
150 /* I see RENUMBERED constants in bits/in.h - !!?
151 * What a fuck is going on with libc? Is it a glibc joke? */
152 # ifdef IPV6_2292HOPLIMIT
153 # undef IPV6_HOPLIMIT
154 # define IPV6_HOPLIMIT IPV6_2292HOPLIMIT
162 MAX_DUP_CHK = (8 * 128),
164 PINGINTERVAL = 1, /* 1 second */
170 create_icmp_socket(len_and_sockaddr *lsa)
172 create_icmp_socket(void)
173 #define create_icmp_socket(lsa) create_icmp_socket()
178 if (lsa->u.sa.sa_family == AF_INET6)
179 sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
182 sock = socket(AF_INET, SOCK_RAW, 1); /* 1 == ICMP */
185 bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
186 bb_perror_msg_and_die(bb_msg_can_not_create_raw_socket);
189 xmove_fd(sock, pingsock);
192 #if !ENABLE_FEATURE_FANCY_PING
198 char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
201 #define G (*(struct globals*)bb_common_bufsiz1)
202 #define INIT_G() do { setup_common_bufsiz(); } while (0)
204 static void noresp(int ign UNUSED_PARAM)
206 printf("No response from %s\n", G.hostname);
210 static void ping4(len_and_sockaddr *lsa)
215 pkt = (struct icmp *) G.packet;
216 /*memset(pkt, 0, sizeof(G.packet)); already is */
217 pkt->icmp_type = ICMP_ECHO;
218 pkt->icmp_id = G.myid;
219 pkt->icmp_cksum = inet_cksum((uint16_t *) pkt, sizeof(G.packet));
221 xsendto(pingsock, G.packet, DEFDATALEN + ICMP_MINLEN, &lsa->u.sa, lsa->len);
223 /* listen for replies */
226 struct sockaddr_in from;
227 socklen_t fromlen = sizeof(from);
229 c = recvfrom(pingsock, G.packet, sizeof(G.packet), 0,
230 (struct sockaddr *) &from, &fromlen);
232 c = recv(pingsock, G.packet, sizeof(G.packet), 0);
236 bb_perror_msg("recvfrom");
239 if (c >= 76) { /* ip + icmp */
240 struct iphdr *iphdr = (struct iphdr *) G.packet;
242 pkt = (struct icmp *) (G.packet + (iphdr->ihl << 2)); /* skip ip hdr */
243 if (pkt->icmp_id != G.myid)
244 continue; /* not our ping */
245 if (pkt->icmp_type == ICMP_ECHOREPLY)
252 static void ping6(len_and_sockaddr *lsa)
254 struct icmp6_hdr *pkt;
258 pkt = (struct icmp6_hdr *) G.packet;
259 /*memset(pkt, 0, sizeof(G.packet)); already is */
260 pkt->icmp6_type = ICMP6_ECHO_REQUEST;
261 pkt->icmp6_id = G.myid;
263 sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
264 setsockopt_int(pingsock, SOL_RAW, IPV6_CHECKSUM, sockopt);
266 xsendto(pingsock, G.packet, DEFDATALEN + sizeof(struct icmp6_hdr), &lsa->u.sa, lsa->len);
268 /* listen for replies */
271 struct sockaddr_in6 from;
272 socklen_t fromlen = sizeof(from);
274 c = recvfrom(pingsock, G.packet, sizeof(G.packet), 0,
275 (struct sockaddr *) &from, &fromlen);
277 c = recv(pingsock, G.packet, sizeof(G.packet), 0);
281 bb_perror_msg("recvfrom");
284 if (c >= ICMP_MINLEN) { /* icmp6_hdr */
285 if (pkt->icmp6_id != G.myid)
286 continue; /* not our ping */
287 if (pkt->icmp6_type == ICMP6_ECHO_REPLY)
295 # define common_ping_main(af, argv) common_ping_main(argv)
297 static int common_ping_main(sa_family_t af, char **argv)
299 len_and_sockaddr *lsa;
304 while ((++argv)[0] && argv[0][0] == '-') {
305 if (argv[0][1] == '4') {
309 if (argv[0][1] == '6') {
324 lsa = xhost_and_af2sockaddr(G.hostname, 0, af);
326 lsa = xhost_and_af2sockaddr(G.hostname, 0, AF_INET);
328 /* Set timer _after_ DNS resolution */
329 signal(SIGALRM, noresp);
330 alarm(5); /* give the host 5000ms to respond */
332 create_icmp_socket(lsa);
333 G.myid = (uint16_t) getpid();
335 if (lsa->u.sa.sa_family == AF_INET6)
340 if (ENABLE_FEATURE_CLEAN_UP)
342 printf("%s is alive!\n", G.hostname);
347 #else /* FEATURE_FANCY_PING */
350 /* Full(er) version */
352 /* -c NUM, -t NUM, -w NUM, -W NUM */
353 #define OPT_STRING "qvAc:+s:t:+w:+W:+I:np:4"IF_PING6("6")
356 OPT_VERBOSE = 1 << 1,
364 /*OPT_n = 1 << 9, - ignored */
367 OPT_IPV6 = (1 << 12) * ENABLE_PING6,
374 len_and_sockaddr *source_lsa;
376 unsigned pingcount; /* must be int-sized */
378 unsigned long ntransmitted, nreceived, nrepeats;
381 unsigned tmin, tmax; /* in us */
382 unsigned long long tsum; /* in us, sum of all times */
383 unsigned cur_us; /* low word only, we don't need more */
384 unsigned deadline_us;
386 unsigned sizeof_rcv_packet;
387 char *rcv_packet; /* [datalen + MAXIPLEN + MAXICMPLEN] */
388 void *snd_packet; /* [datalen + ipv4/ipv6_const] */
389 const char *hostname;
393 struct sockaddr_in sin;
395 struct sockaddr_in6 sin6;
398 unsigned char rcvd_tbl[MAX_DUP_CHK / 8];
400 #define G (*(struct globals*)bb_common_bufsiz1)
401 #define if_index (G.if_index )
402 #define source_lsa (G.source_lsa )
403 #define str_I (G.str_I )
404 #define datalen (G.datalen )
405 #define pingcount (G.pingcount )
406 #define opt_ttl (G.opt_ttl )
407 #define myid (G.myid )
408 #define tmin (G.tmin )
409 #define tmax (G.tmax )
410 #define tsum (G.tsum )
411 #define timeout (G.timeout )
412 #define hostname (G.hostname )
413 #define dotted (G.dotted )
414 #define pingaddr (G.pingaddr )
415 #define rcvd_tbl (G.rcvd_tbl )
416 #define INIT_G() do { \
417 setup_common_bufsiz(); \
418 BUILD_BUG_ON(sizeof(G) > COMMON_BUFSIZE); \
419 datalen = DEFDATALEN; \
425 #define BYTE(bit) rcvd_tbl[(bit)>>3]
426 #define MASK(bit) (1 << ((bit) & 7))
427 #define SET(bit) (BYTE(bit) |= MASK(bit))
428 #define CLR(bit) (BYTE(bit) &= (~MASK(bit)))
429 #define TST(bit) (BYTE(bit) & MASK(bit))
431 static void print_stats_and_exit(int junk) NORETURN;
432 static void print_stats_and_exit(int junk UNUSED_PARAM)
437 signal(SIGINT, SIG_IGN);
440 printf("\n--- %s ping statistics ---\n"
441 "%lu packets transmitted, "
442 "%lu packets received, ",
443 hostname, G.ntransmitted, nrecv
446 printf("%lu duplicates, ", G.nrepeats);
449 ul = (ul - nrecv) * 100 / ul;
450 printf("%lu%% packet loss\n", ul);
451 if (tmin != UINT_MAX) {
452 unsigned tavg = tsum / (nrecv + G.nrepeats);
453 printf("round-trip min/avg/max = %u.%03u/%u.%03u/%u.%03u ms\n",
454 tmin / 1000, tmin % 1000,
455 tavg / 1000, tavg % 1000,
456 tmax / 1000, tmax % 1000);
458 /* if condition is true, exit with 1 -- 'failure' */
459 exit(nrecv == 0 || (G.deadline_us && nrecv < pingcount));
462 static void sendping_tail(void (*sp)(int), int size_pkt)
466 CLR((uint16_t)G.ntransmitted % MAX_DUP_CHK);
472 unsigned n = G.cur_us - G.deadline_us;
474 print_stats_and_exit(0);
477 /* sizeof(pingaddr) can be larger than real sa size, but I think
478 * it doesn't matter */
479 sz = xsendto(pingsock, G.snd_packet, size_pkt, &pingaddr.sa, sizeof(pingaddr));
481 bb_error_msg_and_die(bb_msg_write_error);
483 if (pingcount == 0 || G.ntransmitted < pingcount) {
484 /* Didn't send all pings yet - schedule next in 1s */
487 } else { /* -c NN, and all NN are sent */
488 /* Wait for the last ping to come back.
489 * -W timeout: wait for a response in seconds.
490 * Affects only timeout in absence of any responses,
491 * otherwise ping waits for two RTTs. */
492 unsigned expire = timeout;
495 /* approx. 2*tmax, in seconds (2 RTT) */
496 expire = tmax / (512*1024);
500 signal(SIGALRM, print_stats_and_exit);
505 static void sendping4(int junk UNUSED_PARAM)
507 struct icmp *pkt = G.snd_packet;
509 memset(pkt, G.pattern, datalen + ICMP_MINLEN + 4);
510 pkt->icmp_type = ICMP_ECHO;
511 /*pkt->icmp_code = 0;*/
512 pkt->icmp_cksum = 0; /* cksum is calculated with this field set to 0 */
513 pkt->icmp_seq = htons(G.ntransmitted); /* don't ++ here, it can be a macro */
516 /* If datalen < 4, we store timestamp _past_ the packet,
517 * but it's ok - we allocated 4 extra bytes in xzalloc() just in case.
519 /*if (datalen >= 4)*/
520 /* No hton: we'll read it back on the same machine */
521 *(uint32_t*)&pkt->icmp_dun = G.cur_us = monotonic_us();
523 pkt->icmp_cksum = inet_cksum((uint16_t *) pkt, datalen + ICMP_MINLEN);
525 sendping_tail(sendping4, ICMP_MINLEN);
528 static void sendping6(int junk UNUSED_PARAM)
530 struct icmp6_hdr *pkt = G.snd_packet;
532 memset(pkt, G.pattern, datalen + sizeof(struct icmp6_hdr) + 4);
533 pkt->icmp6_type = ICMP6_ECHO_REQUEST;
534 /*pkt->icmp6_code = 0;*/
535 /*pkt->icmp6_cksum = 0;*/
536 pkt->icmp6_seq = htons(G.ntransmitted); /* don't ++ here, it can be a macro */
537 pkt->icmp6_id = myid;
539 /*if (datalen >= 4)*/
540 *(bb__aliased_uint32_t*)(&pkt->icmp6_data8[4]) = G.cur_us = monotonic_us();
542 //TODO? pkt->icmp_cksum = inet_cksum(...);
544 sendping_tail(sendping6, sizeof(struct icmp6_hdr));
548 static const char *icmp_type_name(int id)
551 case ICMP_ECHOREPLY: return "Echo Reply";
552 case ICMP_DEST_UNREACH: return "Destination Unreachable";
553 case ICMP_SOURCE_QUENCH: return "Source Quench";
554 case ICMP_REDIRECT: return "Redirect (change route)";
555 case ICMP_ECHO: return "Echo Request";
556 case ICMP_TIME_EXCEEDED: return "Time Exceeded";
557 case ICMP_PARAMETERPROB: return "Parameter Problem";
558 case ICMP_TIMESTAMP: return "Timestamp Request";
559 case ICMP_TIMESTAMPREPLY: return "Timestamp Reply";
560 case ICMP_INFO_REQUEST: return "Information Request";
561 case ICMP_INFO_REPLY: return "Information Reply";
562 case ICMP_ADDRESS: return "Address Mask Request";
563 case ICMP_ADDRESSREPLY: return "Address Mask Reply";
564 default: return "unknown ICMP type";
568 /* RFC3542 changed some definitions from RFC2292 for no good reason, whee!
569 * the newer 3542 uses a MLD_ prefix where as 2292 uses ICMP6_ prefix */
570 #ifndef MLD_LISTENER_QUERY
571 # define MLD_LISTENER_QUERY ICMP6_MEMBERSHIP_QUERY
573 #ifndef MLD_LISTENER_REPORT
574 # define MLD_LISTENER_REPORT ICMP6_MEMBERSHIP_REPORT
576 #ifndef MLD_LISTENER_REDUCTION
577 # define MLD_LISTENER_REDUCTION ICMP6_MEMBERSHIP_REDUCTION
579 static const char *icmp6_type_name(int id)
582 case ICMP6_DST_UNREACH: return "Destination Unreachable";
583 case ICMP6_PACKET_TOO_BIG: return "Packet too big";
584 case ICMP6_TIME_EXCEEDED: return "Time Exceeded";
585 case ICMP6_PARAM_PROB: return "Parameter Problem";
586 case ICMP6_ECHO_REPLY: return "Echo Reply";
587 case ICMP6_ECHO_REQUEST: return "Echo Request";
588 case MLD_LISTENER_QUERY: return "Listener Query";
589 case MLD_LISTENER_REPORT: return "Listener Report";
590 case MLD_LISTENER_REDUCTION: return "Listener Reduction";
591 default: return "unknown ICMP type";
596 static void unpack_tail(int sz, uint32_t *tp,
597 const char *from_str,
598 uint16_t recv_seq, int ttl)
601 const char *dupmsg = " (DUP!)";
602 unsigned triptime = triptime; /* for gcc */
605 /* (int32_t) cast is for hypothetical 64-bit unsigned */
606 /* (doesn't hurt 32-bit real-world anyway) */
607 triptime = (int32_t) ((uint32_t)monotonic_us() - *tp);
615 b = &BYTE(recv_seq % MAX_DUP_CHK);
616 m = MASK(recv_seq % MAX_DUP_CHK);
617 /*if TST(recv_seq % MAX_DUP_CHK):*/
621 /*SET(recv_seq % MAX_DUP_CHK):*/
627 if (option_mask32 & OPT_QUIET)
630 printf("%d bytes from %s: seq=%u ttl=%d", sz,
631 from_str, recv_seq, ttl);
633 printf(" time=%u.%03u ms", triptime / 1000, triptime % 1000);
637 static int unpack4(char *buf, int sz, struct sockaddr_in *from)
639 struct icmp *icmppkt;
643 /* discard if too short */
644 if (sz < (datalen + ICMP_MINLEN))
647 /* check IP header */
648 iphdr = (struct iphdr *) buf;
649 hlen = iphdr->ihl << 2;
651 icmppkt = (struct icmp *) (buf + hlen);
652 if (icmppkt->icmp_id != myid)
653 return 0; /* not our ping */
655 if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
656 uint16_t recv_seq = ntohs(icmppkt->icmp_seq);
659 if (sz >= ICMP_MINLEN + sizeof(uint32_t))
660 tp = (uint32_t *) icmppkt->icmp_data;
662 inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
663 recv_seq, iphdr->ttl);
666 if (icmppkt->icmp_type != ICMP_ECHO) {
667 bb_error_msg("warning: got ICMP %d (%s)",
669 icmp_type_name(icmppkt->icmp_type));
674 static int unpack6(char *packet, int sz, struct sockaddr_in6 *from, int hoplimit)
676 struct icmp6_hdr *icmppkt;
677 char buf[INET6_ADDRSTRLEN];
679 /* discard if too short */
680 if (sz < (datalen + sizeof(struct icmp6_hdr)))
683 icmppkt = (struct icmp6_hdr *) packet;
684 if (icmppkt->icmp6_id != myid)
685 return 0; /* not our ping */
687 if (icmppkt->icmp6_type == ICMP6_ECHO_REPLY) {
688 uint16_t recv_seq = ntohs(icmppkt->icmp6_seq);
691 if (sz >= sizeof(struct icmp6_hdr) + sizeof(uint32_t))
692 tp = (uint32_t *) &icmppkt->icmp6_data8[4];
694 inet_ntop(AF_INET6, &from->sin6_addr,
699 if (icmppkt->icmp6_type != ICMP6_ECHO_REQUEST) {
700 bb_error_msg("warning: got ICMP %d (%s)",
702 icmp6_type_name(icmppkt->icmp6_type));
708 static void ping4(len_and_sockaddr *lsa)
712 pingaddr.sin = lsa->u.sin;
714 if (setsockopt(pingsock, IPPROTO_IP, IP_MULTICAST_IF,
715 &source_lsa->u.sa, source_lsa->len))
716 bb_error_msg_and_die("can't set multicast source interface");
717 xbind(pingsock, &source_lsa->u.sa, source_lsa->len);
720 /* enable broadcast pings */
721 setsockopt_broadcast(pingsock);
723 /* set recv buf (needed if we can get lots of responses: flood ping,
724 * broadcast ping etc) */
725 sockopt = (datalen * 2) + 7 * 1024; /* giving it a bit of extra room */
726 setsockopt_SOL_SOCKET_int(pingsock, SO_RCVBUF, sockopt);
729 setsockopt_int(pingsock, IPPROTO_IP, IP_TTL, opt_ttl);
730 /* above doesn't affect packets sent to bcast IP, so... */
731 setsockopt_int(pingsock, IPPROTO_IP, IP_MULTICAST_TTL, opt_ttl);
734 signal(SIGINT, print_stats_and_exit);
736 /* start the ping's going ... */
740 /* listen for replies */
742 struct sockaddr_in from;
743 socklen_t fromlen = (socklen_t) sizeof(from);
746 c = recvfrom(pingsock, G.rcv_packet, G.sizeof_rcv_packet, 0,
747 (struct sockaddr *) &from, &fromlen);
750 bb_perror_msg("recvfrom");
753 c = unpack4(G.rcv_packet, c, &from);
754 if (pingcount && G.nreceived >= pingcount)
756 if (c && (option_mask32 & OPT_A)) {
762 static void ping6(len_and_sockaddr *lsa)
766 struct sockaddr_in6 from;
768 char control_buf[CMSG_SPACE(36)];
770 pingaddr.sin6 = lsa->u.sin6;
772 xbind(pingsock, &source_lsa->u.sa, source_lsa->len);
776 struct icmp6_filter filt;
777 if (!(option_mask32 & OPT_VERBOSE)) {
778 ICMP6_FILTER_SETBLOCKALL(&filt);
779 ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt);
781 ICMP6_FILTER_SETPASSALL(&filt);
783 if (setsockopt(pingsock, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
785 bb_error_msg_and_die("setsockopt(%s)", "ICMP6_FILTER");
787 #endif /*ICMP6_FILTER*/
789 /* enable broadcast pings */
790 setsockopt_broadcast(pingsock);
792 /* set recv buf (needed if we can get lots of responses: flood ping,
793 * broadcast ping etc) */
794 sockopt = (datalen * 2) + 7 * 1024; /* giving it a bit of extra room */
795 setsockopt_SOL_SOCKET_int(pingsock, SO_RCVBUF, sockopt);
797 sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
798 BUILD_BUG_ON(offsetof(struct icmp6_hdr, icmp6_cksum) != 2);
799 setsockopt_int(pingsock, SOL_RAW, IPV6_CHECKSUM, sockopt);
801 /* request ttl info to be returned in ancillary data */
802 setsockopt_1(pingsock, SOL_IPV6, IPV6_HOPLIMIT);
805 pingaddr.sin6.sin6_scope_id = if_index;
807 signal(SIGINT, print_stats_and_exit);
809 msg.msg_name = &from;
810 msg.msg_namelen = sizeof(from);
813 msg.msg_control = control_buf;
814 iov.iov_base = G.rcv_packet;
815 iov.iov_len = G.sizeof_rcv_packet;
817 /* start the ping's going ... */
821 /* listen for replies */
827 msg.msg_controllen = sizeof(control_buf);
828 c = recvmsg(pingsock, &msg, 0);
831 bb_perror_msg("recvfrom");
834 for (mp = CMSG_FIRSTHDR(&msg); mp; mp = CMSG_NXTHDR(&msg, mp)) {
835 if (mp->cmsg_level == SOL_IPV6
836 && mp->cmsg_type == IPV6_HOPLIMIT
837 /* don't check len - we trust the kernel: */
838 /* && mp->cmsg_len >= CMSG_LEN(sizeof(int)) */
840 /*hoplimit = *(int*)CMSG_DATA(mp); - unaligned access */
841 move_from_unaligned_int(hoplimit, CMSG_DATA(mp));
844 c = unpack6(G.rcv_packet, c, &from, hoplimit);
845 if (pingcount && G.nreceived >= pingcount)
847 if (c && (option_mask32 & OPT_A)) {
854 static void ping(len_and_sockaddr *lsa)
856 printf("PING %s (%s)", hostname, dotted);
859 xmalloc_sockaddr2dotted_noport(&source_lsa->u.sa));
861 printf(": %d data bytes\n", datalen);
863 create_icmp_socket(lsa);
864 /* untested whether "-I addr" really works for IPv6: */
866 setsockopt_bindtodevice(pingsock, str_I);
868 G.sizeof_rcv_packet = datalen + MAXIPLEN + MAXICMPLEN;
869 G.rcv_packet = xzalloc(G.sizeof_rcv_packet);
871 if (lsa->u.sa.sa_family == AF_INET6) {
872 /* +4 reserves a place for timestamp, which may end up sitting
873 * _after_ packet. Saves one if() - see sendping4/6() */
874 G.snd_packet = xzalloc(datalen + sizeof(struct icmp6_hdr) + 4);
879 G.snd_packet = xzalloc(datalen + ICMP_MINLEN + 4);
884 static int common_ping_main(int opt, char **argv)
886 len_and_sockaddr *lsa;
891 opt |= getopt32(argv, "^"
893 /* exactly one arg; -v and -q don't mix */
895 &pingcount, &str_s, &opt_ttl, &G.deadline_us, &timeout, &str_I, &str_p
898 datalen = xatou16(str_s); // -s
899 if (opt & OPT_I) { // -I
900 if_index = if_nametoindex(str_I);
902 /* TODO: I'm not sure it takes IPv6 unless in [XX:XX..] format */
903 source_lsa = xdotted2sockaddr(str_I, 0);
904 str_I = NULL; /* don't try to bind to device later */
908 G.pattern = xstrtou_range(str_p, 16, 0, 255);
910 unsigned d = G.deadline_us < INT_MAX/1000000 ? G.deadline_us : INT_MAX/1000000;
911 G.deadline_us = 1 | ((d * 1000000) + monotonic_us());
914 myid = (uint16_t) getpid();
915 hostname = argv[optind];
918 sa_family_t af = AF_UNSPEC;
923 lsa = xhost_and_af2sockaddr(hostname, 0, af);
926 lsa = xhost_and_af2sockaddr(hostname, 0, AF_INET);
929 if (source_lsa && source_lsa->u.sa.sa_family != lsa->u.sa.sa_family)
930 /* leaking it here... */
933 dotted = xmalloc_sockaddr2dotted_noport(&lsa->u.sa);
935 print_stats_and_exit(0);
936 /*return EXIT_SUCCESS;*/
938 #endif /* FEATURE_FANCY_PING */
942 int ping_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
943 int ping_main(int argc UNUSED_PARAM, char **argv)
945 # if !ENABLE_FEATURE_FANCY_PING
946 return common_ping_main(AF_UNSPEC, argv);
948 return common_ping_main(0, argv);
954 int ping6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
955 int ping6_main(int argc UNUSED_PARAM, char **argv)
957 # if !ENABLE_FEATURE_FANCY_PING
958 return common_ping_main(AF_INET6, argv);
960 return common_ping_main(OPT_IPV6, argv);
966 * Copyright (c) 1989 The Regents of the University of California.
967 * All rights reserved.
969 * This code is derived from software contributed to Berkeley by
972 * Redistribution and use in source and binary forms, with or without
973 * modification, are permitted provided that the following conditions
975 * 1. Redistributions of source code must retain the above copyright
976 * notice, this list of conditions and the following disclaimer.
977 * 2. Redistributions in binary form must reproduce the above copyright
978 * notice, this list of conditions and the following disclaimer in the
979 * documentation and/or other materials provided with the distribution.
981 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
982 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
984 * 4. Neither the name of the University nor the names of its contributors
985 * may be used to endorse or promote products derived from this software
986 * without specific prior written permission.
988 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
989 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
990 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
991 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
992 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
993 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
994 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
995 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
996 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
997 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF