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 -t TTL Set TTL"
78 //usage: "\n -I IFACE/IP Source interface or IP address"
79 //usage: "\n -W SEC Seconds to wait for the first response (default 10)"
80 //usage: "\n (after all -c CNT packets are sent)"
81 //usage: "\n -w SEC Seconds until ping exits (default:infinite)"
82 //usage: "\n (can exit earlier with -c CNT)"
83 //usage: "\n -q Quiet, only display output at start"
84 //usage: "\n and when finished"
85 //usage: "\n -p HEXBYTE Pattern to use for payload"
87 //usage:# define ping6_trivial_usage
88 //usage: "[OPTIONS] HOST"
89 //usage:# define ping6_full_usage "\n\n"
90 //usage: "Send ICMP ECHO_REQUEST packets to network hosts\n"
91 //usage: "\n -c CNT Send only CNT pings"
92 //usage: "\n -s SIZE Send SIZE data bytes in packets (default 56)"
93 //usage: "\n -I IFACE/IP Source interface or IP address"
94 //usage: "\n -q Quiet, only display output at start"
95 //usage: "\n and when finished"
96 //usage: "\n -p HEXBYTE Pattern to use for payload"
100 //usage:#define ping_example_usage
101 //usage: "$ ping localhost\n"
102 //usage: "PING slag (127.0.0.1): 56 data bytes\n"
103 //usage: "64 bytes from 127.0.0.1: icmp_seq=0 ttl=255 time=20.1 ms\n"
105 //usage: "--- debian ping statistics ---\n"
106 //usage: "1 packets transmitted, 1 packets received, 0% packet loss\n"
107 //usage: "round-trip min/avg/max = 20.1/20.1/20.1 ms\n"
108 //usage:#define ping6_example_usage
109 //usage: "$ ping6 ip6-localhost\n"
110 //usage: "PING ip6-localhost (::1): 56 data bytes\n"
111 //usage: "64 bytes from ::1: icmp6_seq=0 ttl=64 time=20.1 ms\n"
113 //usage: "--- ip6-localhost ping statistics ---\n"
114 //usage: "1 packets transmitted, 1 packets received, 0% packet loss\n"
115 //usage: "round-trip min/avg/max = 20.1/20.1/20.1 ms\n"
118 #include <netinet/ip_icmp.h>
120 #include "common_bufsiz.h"
123 /* should be in netinet/ip_icmp.h */
124 # define ICMP_DEST_UNREACH 3 /* Destination Unreachable */
125 # define ICMP_SOURCE_QUENCH 4 /* Source Quench */
126 # define ICMP_REDIRECT 5 /* Redirect (change route) */
127 # define ICMP_ECHO 8 /* Echo Request */
128 # define ICMP_TIME_EXCEEDED 11 /* Time Exceeded */
129 # define ICMP_PARAMETERPROB 12 /* Parameter Problem */
130 # define ICMP_TIMESTAMP 13 /* Timestamp Request */
131 # define ICMP_TIMESTAMPREPLY 14 /* Timestamp Reply */
132 # define ICMP_INFO_REQUEST 15 /* Information Request */
133 # define ICMP_INFO_REPLY 16 /* Information Reply */
134 # define ICMP_ADDRESS 17 /* Address Mask Request */
135 # define ICMP_ADDRESSREPLY 18 /* Address Mask Reply */
138 /* Some operating systems, like GNU/Hurd, don't define SOL_RAW, but do have
139 * IPPROTO_RAW. Since the IPPROTO definitions are also valid to use for
140 * setsockopt (and take the same value as their corresponding SOL definitions,
141 * if they exist), we can just fall back on IPPROTO_RAW. */
143 # define SOL_RAW IPPROTO_RAW
147 # include <netinet/icmp6.h>
148 /* I see RENUMBERED constants in bits/in.h - !!?
149 * What a fuck is going on with libc? Is it a glibc joke? */
150 # ifdef IPV6_2292HOPLIMIT
151 # undef IPV6_HOPLIMIT
152 # define IPV6_HOPLIMIT IPV6_2292HOPLIMIT
160 MAX_DUP_CHK = (8 * 128),
162 PINGINTERVAL = 1, /* 1 second */
168 create_icmp_socket(len_and_sockaddr *lsa)
170 create_icmp_socket(void)
171 #define create_icmp_socket(lsa) create_icmp_socket()
176 if (lsa->u.sa.sa_family == AF_INET6)
177 sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
180 sock = socket(AF_INET, SOCK_RAW, 1); /* 1 == ICMP */
183 bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
184 bb_perror_msg_and_die(bb_msg_can_not_create_raw_socket);
187 xmove_fd(sock, pingsock);
190 #if !ENABLE_FEATURE_FANCY_PING
196 char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
199 #define G (*(struct globals*)bb_common_bufsiz1)
200 #define INIT_G() do { setup_common_bufsiz(); } while (0)
202 static void noresp(int ign UNUSED_PARAM)
204 printf("No response from %s\n", G.hostname);
208 static void ping4(len_and_sockaddr *lsa)
213 pkt = (struct icmp *) G.packet;
214 /*memset(pkt, 0, sizeof(G.packet)); already is */
215 pkt->icmp_type = ICMP_ECHO;
216 pkt->icmp_id = G.myid;
217 pkt->icmp_cksum = inet_cksum((uint16_t *) pkt, sizeof(G.packet));
219 xsendto(pingsock, G.packet, DEFDATALEN + ICMP_MINLEN, &lsa->u.sa, lsa->len);
221 /* listen for replies */
224 struct sockaddr_in from;
225 socklen_t fromlen = sizeof(from);
227 c = recvfrom(pingsock, G.packet, sizeof(G.packet), 0,
228 (struct sockaddr *) &from, &fromlen);
230 c = recv(pingsock, G.packet, sizeof(G.packet), 0);
234 bb_perror_msg("recvfrom");
237 if (c >= 76) { /* ip + icmp */
238 struct iphdr *iphdr = (struct iphdr *) G.packet;
240 pkt = (struct icmp *) (G.packet + (iphdr->ihl << 2)); /* skip ip hdr */
241 if (pkt->icmp_id != G.myid)
242 continue; /* not our ping */
243 if (pkt->icmp_type == ICMP_ECHOREPLY)
250 static void ping6(len_and_sockaddr *lsa)
252 struct icmp6_hdr *pkt;
256 pkt = (struct icmp6_hdr *) G.packet;
257 /*memset(pkt, 0, sizeof(G.packet)); already is */
258 pkt->icmp6_type = ICMP6_ECHO_REQUEST;
259 pkt->icmp6_id = G.myid;
261 sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
262 setsockopt_int(pingsock, SOL_RAW, IPV6_CHECKSUM, sockopt);
264 xsendto(pingsock, G.packet, DEFDATALEN + sizeof(struct icmp6_hdr), &lsa->u.sa, lsa->len);
266 /* listen for replies */
269 struct sockaddr_in6 from;
270 socklen_t fromlen = sizeof(from);
272 c = recvfrom(pingsock, G.packet, sizeof(G.packet), 0,
273 (struct sockaddr *) &from, &fromlen);
275 c = recv(pingsock, G.packet, sizeof(G.packet), 0);
279 bb_perror_msg("recvfrom");
282 if (c >= ICMP_MINLEN) { /* icmp6_hdr */
283 if (pkt->icmp6_id != G.myid)
284 continue; /* not our ping */
285 if (pkt->icmp6_type == ICMP6_ECHO_REPLY)
293 # define common_ping_main(af, argv) common_ping_main(argv)
295 static int common_ping_main(sa_family_t af, char **argv)
297 len_and_sockaddr *lsa;
302 while ((++argv)[0] && argv[0][0] == '-') {
303 if (argv[0][1] == '4') {
307 if (argv[0][1] == '6') {
322 lsa = xhost_and_af2sockaddr(G.hostname, 0, af);
324 lsa = xhost_and_af2sockaddr(G.hostname, 0, AF_INET);
326 /* Set timer _after_ DNS resolution */
327 signal(SIGALRM, noresp);
328 alarm(5); /* give the host 5000ms to respond */
330 create_icmp_socket(lsa);
331 G.myid = (uint16_t) getpid();
333 if (lsa->u.sa.sa_family == AF_INET6)
338 if (ENABLE_FEATURE_CLEAN_UP)
340 printf("%s is alive!\n", G.hostname);
345 #else /* FEATURE_FANCY_PING */
348 /* Full(er) version */
350 /* -c NUM, -t NUM, -w NUM, -W NUM */
351 #define OPT_STRING "qvc:+s:t:+w:+W:+I:np:4"IF_PING6("6")
354 OPT_VERBOSE = 1 << 1,
361 /*OPT_n = 1 << 8, - ignored */
364 OPT_IPV6 = (1 << 11) * ENABLE_PING6,
371 len_and_sockaddr *source_lsa;
373 unsigned pingcount; /* must be int-sized */
375 unsigned long ntransmitted, nreceived, nrepeats;
378 unsigned tmin, tmax; /* in us */
379 unsigned long long tsum; /* in us, sum of all times */
383 unsigned sizeof_rcv_packet;
384 char *rcv_packet; /* [datalen + MAXIPLEN + MAXICMPLEN] */
385 void *snd_packet; /* [datalen + ipv4/ipv6_const] */
386 const char *hostname;
390 struct sockaddr_in sin;
392 struct sockaddr_in6 sin6;
395 unsigned char rcvd_tbl[MAX_DUP_CHK / 8];
397 #define G (*(struct globals*)bb_common_bufsiz1)
398 #define if_index (G.if_index )
399 #define source_lsa (G.source_lsa )
400 #define str_I (G.str_I )
401 #define datalen (G.datalen )
402 #define pingcount (G.pingcount )
403 #define opt_ttl (G.opt_ttl )
404 #define myid (G.myid )
405 #define tmin (G.tmin )
406 #define tmax (G.tmax )
407 #define tsum (G.tsum )
408 #define deadline (G.deadline )
409 #define timeout (G.timeout )
410 #define total_secs (G.total_secs )
411 #define hostname (G.hostname )
412 #define dotted (G.dotted )
413 #define pingaddr (G.pingaddr )
414 #define rcvd_tbl (G.rcvd_tbl )
415 #define INIT_G() do { \
416 setup_common_bufsiz(); \
417 BUILD_BUG_ON(sizeof(G) > COMMON_BUFSIZE); \
418 datalen = DEFDATALEN; \
424 #define BYTE(bit) rcvd_tbl[(bit)>>3]
425 #define MASK(bit) (1 << ((bit) & 7))
426 #define SET(bit) (BYTE(bit) |= MASK(bit))
427 #define CLR(bit) (BYTE(bit) &= (~MASK(bit)))
428 #define TST(bit) (BYTE(bit) & MASK(bit))
430 static void print_stats_and_exit(int junk) NORETURN;
431 static void print_stats_and_exit(int junk UNUSED_PARAM)
436 signal(SIGINT, SIG_IGN);
439 printf("\n--- %s ping statistics ---\n"
440 "%lu packets transmitted, "
441 "%lu packets received, ",
442 hostname, G.ntransmitted, nrecv
445 printf("%lu duplicates, ", G.nrepeats);
448 ul = (ul - nrecv) * 100 / ul;
449 printf("%lu%% packet loss\n", ul);
450 if (tmin != UINT_MAX) {
451 unsigned tavg = tsum / (nrecv + G.nrepeats);
452 printf("round-trip min/avg/max = %u.%03u/%u.%03u/%u.%03u ms\n",
453 tmin / 1000, tmin % 1000,
454 tavg / 1000, tavg % 1000,
455 tmax / 1000, tmax % 1000);
457 /* if condition is true, exit with 1 -- 'failure' */
458 exit(nrecv == 0 || (deadline && nrecv < pingcount));
461 static void sendping_tail(void (*sp)(int), int size_pkt)
465 CLR((uint16_t)G.ntransmitted % MAX_DUP_CHK);
470 /* sizeof(pingaddr) can be larger than real sa size, but I think
471 * it doesn't matter */
472 sz = xsendto(pingsock, G.snd_packet, size_pkt, &pingaddr.sa, sizeof(pingaddr));
474 bb_error_msg_and_die(bb_msg_write_error);
476 if (pingcount == 0 || deadline || G.ntransmitted < pingcount) {
477 /* Didn't send all pings yet - schedule next in 1s */
480 total_secs += PINGINTERVAL;
481 if (total_secs >= deadline)
482 signal(SIGALRM, print_stats_and_exit);
485 } else { /* -c NN, and all NN are sent (and no deadline) */
486 /* Wait for the last ping to come back.
487 * -W timeout: wait for a response in seconds.
488 * Affects only timeout in absence of any responses,
489 * otherwise ping waits for two RTTs. */
490 unsigned expire = timeout;
493 /* approx. 2*tmax, in seconds (2 RTT) */
494 expire = tmax / (512*1024);
498 signal(SIGALRM, print_stats_and_exit);
503 static void sendping4(int junk UNUSED_PARAM)
505 struct icmp *pkt = G.snd_packet;
507 memset(pkt, G.pattern, datalen + ICMP_MINLEN + 4);
508 pkt->icmp_type = ICMP_ECHO;
509 /*pkt->icmp_code = 0;*/
510 pkt->icmp_cksum = 0; /* cksum is calculated with this field set to 0 */
511 pkt->icmp_seq = htons(G.ntransmitted); /* don't ++ here, it can be a macro */
514 /* If datalen < 4, we store timestamp _past_ the packet,
515 * but it's ok - we allocated 4 extra bytes in xzalloc() just in case.
517 /*if (datalen >= 4)*/
518 /* No hton: we'll read it back on the same machine */
519 *(uint32_t*)&pkt->icmp_dun = monotonic_us();
521 pkt->icmp_cksum = inet_cksum((uint16_t *) pkt, datalen + ICMP_MINLEN);
523 sendping_tail(sendping4, ICMP_MINLEN);
526 static void sendping6(int junk UNUSED_PARAM)
528 struct icmp6_hdr *pkt = G.snd_packet;
530 memset(pkt, G.pattern, datalen + sizeof(struct icmp6_hdr) + 4);
531 pkt->icmp6_type = ICMP6_ECHO_REQUEST;
532 /*pkt->icmp6_code = 0;*/
533 /*pkt->icmp6_cksum = 0;*/
534 pkt->icmp6_seq = htons(G.ntransmitted); /* don't ++ here, it can be a macro */
535 pkt->icmp6_id = myid;
537 /*if (datalen >= 4)*/
538 *(bb__aliased_uint32_t*)(&pkt->icmp6_data8[4]) = monotonic_us();
540 //TODO? pkt->icmp_cksum = inet_cksum(...);
542 sendping_tail(sendping6, sizeof(struct icmp6_hdr));
546 static const char *icmp_type_name(int id)
549 case ICMP_ECHOREPLY: return "Echo Reply";
550 case ICMP_DEST_UNREACH: return "Destination Unreachable";
551 case ICMP_SOURCE_QUENCH: return "Source Quench";
552 case ICMP_REDIRECT: return "Redirect (change route)";
553 case ICMP_ECHO: return "Echo Request";
554 case ICMP_TIME_EXCEEDED: return "Time Exceeded";
555 case ICMP_PARAMETERPROB: return "Parameter Problem";
556 case ICMP_TIMESTAMP: return "Timestamp Request";
557 case ICMP_TIMESTAMPREPLY: return "Timestamp Reply";
558 case ICMP_INFO_REQUEST: return "Information Request";
559 case ICMP_INFO_REPLY: return "Information Reply";
560 case ICMP_ADDRESS: return "Address Mask Request";
561 case ICMP_ADDRESSREPLY: return "Address Mask Reply";
562 default: return "unknown ICMP type";
566 /* RFC3542 changed some definitions from RFC2292 for no good reason, whee!
567 * the newer 3542 uses a MLD_ prefix where as 2292 uses ICMP6_ prefix */
568 #ifndef MLD_LISTENER_QUERY
569 # define MLD_LISTENER_QUERY ICMP6_MEMBERSHIP_QUERY
571 #ifndef MLD_LISTENER_REPORT
572 # define MLD_LISTENER_REPORT ICMP6_MEMBERSHIP_REPORT
574 #ifndef MLD_LISTENER_REDUCTION
575 # define MLD_LISTENER_REDUCTION ICMP6_MEMBERSHIP_REDUCTION
577 static const char *icmp6_type_name(int id)
580 case ICMP6_DST_UNREACH: return "Destination Unreachable";
581 case ICMP6_PACKET_TOO_BIG: return "Packet too big";
582 case ICMP6_TIME_EXCEEDED: return "Time Exceeded";
583 case ICMP6_PARAM_PROB: return "Parameter Problem";
584 case ICMP6_ECHO_REPLY: return "Echo Reply";
585 case ICMP6_ECHO_REQUEST: return "Echo Request";
586 case MLD_LISTENER_QUERY: return "Listener Query";
587 case MLD_LISTENER_REPORT: return "Listener Report";
588 case MLD_LISTENER_REDUCTION: return "Listener Reduction";
589 default: return "unknown ICMP type";
594 static void unpack_tail(int sz, uint32_t *tp,
595 const char *from_str,
596 uint16_t recv_seq, int ttl)
599 const char *dupmsg = " (DUP!)";
600 unsigned triptime = triptime; /* for gcc */
603 /* (int32_t) cast is for hypothetical 64-bit unsigned */
604 /* (doesn't hurt 32-bit real-world anyway) */
605 triptime = (int32_t) ((uint32_t)monotonic_us() - *tp);
613 b = &BYTE(recv_seq % MAX_DUP_CHK);
614 m = MASK(recv_seq % MAX_DUP_CHK);
615 /*if TST(recv_seq % MAX_DUP_CHK):*/
619 /*SET(recv_seq % MAX_DUP_CHK):*/
625 if (option_mask32 & OPT_QUIET)
628 printf("%d bytes from %s: seq=%u ttl=%d", sz,
629 from_str, recv_seq, ttl);
631 printf(" time=%u.%03u ms", triptime / 1000, triptime % 1000);
635 static void unpack4(char *buf, int sz, struct sockaddr_in *from)
637 struct icmp *icmppkt;
641 /* discard if too short */
642 if (sz < (datalen + ICMP_MINLEN))
645 /* check IP header */
646 iphdr = (struct iphdr *) buf;
647 hlen = iphdr->ihl << 2;
649 icmppkt = (struct icmp *) (buf + hlen);
650 if (icmppkt->icmp_id != myid)
651 return; /* not our ping */
653 if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
654 uint16_t recv_seq = ntohs(icmppkt->icmp_seq);
657 if (sz >= ICMP_MINLEN + sizeof(uint32_t))
658 tp = (uint32_t *) icmppkt->icmp_data;
660 inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
661 recv_seq, iphdr->ttl);
662 } else if (icmppkt->icmp_type != ICMP_ECHO) {
663 bb_error_msg("warning: got ICMP %d (%s)",
665 icmp_type_name(icmppkt->icmp_type));
669 static void unpack6(char *packet, int sz, struct sockaddr_in6 *from, int hoplimit)
671 struct icmp6_hdr *icmppkt;
672 char buf[INET6_ADDRSTRLEN];
674 /* discard if too short */
675 if (sz < (datalen + sizeof(struct icmp6_hdr)))
678 icmppkt = (struct icmp6_hdr *) packet;
679 if (icmppkt->icmp6_id != myid)
680 return; /* not our ping */
682 if (icmppkt->icmp6_type == ICMP6_ECHO_REPLY) {
683 uint16_t recv_seq = ntohs(icmppkt->icmp6_seq);
686 if (sz >= sizeof(struct icmp6_hdr) + sizeof(uint32_t))
687 tp = (uint32_t *) &icmppkt->icmp6_data8[4];
689 inet_ntop(AF_INET6, &from->sin6_addr,
692 } else if (icmppkt->icmp6_type != ICMP6_ECHO_REQUEST) {
693 bb_error_msg("warning: got ICMP %d (%s)",
695 icmp6_type_name(icmppkt->icmp6_type));
700 static void ping4(len_and_sockaddr *lsa)
704 pingaddr.sin = lsa->u.sin;
706 if (setsockopt(pingsock, IPPROTO_IP, IP_MULTICAST_IF,
707 &source_lsa->u.sa, source_lsa->len))
708 bb_error_msg_and_die("can't set multicast source interface");
709 xbind(pingsock, &source_lsa->u.sa, source_lsa->len);
712 /* enable broadcast pings */
713 setsockopt_broadcast(pingsock);
715 /* set recv buf (needed if we can get lots of responses: flood ping,
716 * broadcast ping etc) */
717 sockopt = (datalen * 2) + 7 * 1024; /* giving it a bit of extra room */
718 setsockopt_SOL_SOCKET_int(pingsock, SO_RCVBUF, sockopt);
721 setsockopt_int(pingsock, IPPROTO_IP, IP_TTL, opt_ttl);
722 /* above doesn't affect packets sent to bcast IP, so... */
723 setsockopt_int(pingsock, IPPROTO_IP, IP_MULTICAST_TTL, opt_ttl);
726 signal(SIGINT, print_stats_and_exit);
728 /* start the ping's going ... */
731 /* listen for replies */
733 struct sockaddr_in from;
734 socklen_t fromlen = (socklen_t) sizeof(from);
737 c = recvfrom(pingsock, G.rcv_packet, G.sizeof_rcv_packet, 0,
738 (struct sockaddr *) &from, &fromlen);
741 bb_perror_msg("recvfrom");
744 unpack4(G.rcv_packet, c, &from);
745 if (pingcount && G.nreceived >= pingcount)
750 static void ping6(len_and_sockaddr *lsa)
754 struct sockaddr_in6 from;
756 char control_buf[CMSG_SPACE(36)];
758 pingaddr.sin6 = lsa->u.sin6;
760 xbind(pingsock, &source_lsa->u.sa, source_lsa->len);
764 struct icmp6_filter filt;
765 if (!(option_mask32 & OPT_VERBOSE)) {
766 ICMP6_FILTER_SETBLOCKALL(&filt);
767 ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt);
769 ICMP6_FILTER_SETPASSALL(&filt);
771 if (setsockopt(pingsock, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
773 bb_error_msg_and_die("setsockopt(%s)", "ICMP6_FILTER");
775 #endif /*ICMP6_FILTER*/
777 /* enable broadcast pings */
778 setsockopt_broadcast(pingsock);
780 /* set recv buf (needed if we can get lots of responses: flood ping,
781 * broadcast ping etc) */
782 sockopt = (datalen * 2) + 7 * 1024; /* giving it a bit of extra room */
783 setsockopt_SOL_SOCKET_int(pingsock, SO_RCVBUF, sockopt);
785 sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
786 BUILD_BUG_ON(offsetof(struct icmp6_hdr, icmp6_cksum) != 2);
787 setsockopt_int(pingsock, SOL_RAW, IPV6_CHECKSUM, sockopt);
789 /* request ttl info to be returned in ancillary data */
790 setsockopt_1(pingsock, SOL_IPV6, IPV6_HOPLIMIT);
793 pingaddr.sin6.sin6_scope_id = if_index;
795 signal(SIGINT, print_stats_and_exit);
797 /* start the ping's going ... */
800 /* listen for replies */
801 msg.msg_name = &from;
802 msg.msg_namelen = sizeof(from);
805 msg.msg_control = control_buf;
806 iov.iov_base = G.rcv_packet;
807 iov.iov_len = G.sizeof_rcv_packet;
812 msg.msg_controllen = sizeof(control_buf);
814 c = recvmsg(pingsock, &msg, 0);
817 bb_perror_msg("recvfrom");
820 for (mp = CMSG_FIRSTHDR(&msg); mp; mp = CMSG_NXTHDR(&msg, mp)) {
821 if (mp->cmsg_level == SOL_IPV6
822 && mp->cmsg_type == IPV6_HOPLIMIT
823 /* don't check len - we trust the kernel: */
824 /* && mp->cmsg_len >= CMSG_LEN(sizeof(int)) */
826 /*hoplimit = *(int*)CMSG_DATA(mp); - unaligned access */
827 move_from_unaligned_int(hoplimit, CMSG_DATA(mp));
830 unpack6(G.rcv_packet, c, &from, hoplimit);
831 if (pingcount && G.nreceived >= pingcount)
837 static void ping(len_and_sockaddr *lsa)
839 printf("PING %s (%s)", hostname, dotted);
842 xmalloc_sockaddr2dotted_noport(&source_lsa->u.sa));
844 printf(": %d data bytes\n", datalen);
846 create_icmp_socket(lsa);
847 /* untested whether "-I addr" really works for IPv6: */
849 setsockopt_bindtodevice(pingsock, str_I);
851 G.sizeof_rcv_packet = datalen + MAXIPLEN + MAXICMPLEN;
852 G.rcv_packet = xzalloc(G.sizeof_rcv_packet);
854 if (lsa->u.sa.sa_family == AF_INET6) {
855 /* +4 reserves a place for timestamp, which may end up sitting
856 * _after_ packet. Saves one if() - see sendping4/6() */
857 G.snd_packet = xzalloc(datalen + sizeof(struct icmp6_hdr) + 4);
862 G.snd_packet = xzalloc(datalen + ICMP_MINLEN + 4);
867 static int common_ping_main(int opt, char **argv)
869 len_and_sockaddr *lsa;
874 opt |= getopt32(argv, "^"
876 /* exactly one arg; -v and -q don't mix */
878 &pingcount, &str_s, &opt_ttl, &deadline, &timeout, &str_I, &str_p
881 datalen = xatou16(str_s); // -s
882 if (opt & OPT_I) { // -I
883 if_index = if_nametoindex(str_I);
885 /* TODO: I'm not sure it takes IPv6 unless in [XX:XX..] format */
886 source_lsa = xdotted2sockaddr(str_I, 0);
887 str_I = NULL; /* don't try to bind to device later */
891 G.pattern = xstrtou_range(str_p, 16, 0, 255);
893 myid = (uint16_t) getpid();
894 hostname = argv[optind];
897 sa_family_t af = AF_UNSPEC;
902 lsa = xhost_and_af2sockaddr(hostname, 0, af);
905 lsa = xhost_and_af2sockaddr(hostname, 0, AF_INET);
908 if (source_lsa && source_lsa->u.sa.sa_family != lsa->u.sa.sa_family)
909 /* leaking it here... */
912 dotted = xmalloc_sockaddr2dotted_noport(&lsa->u.sa);
914 print_stats_and_exit(EXIT_SUCCESS);
915 /*return EXIT_SUCCESS;*/
917 #endif /* FEATURE_FANCY_PING */
921 int ping_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
922 int ping_main(int argc UNUSED_PARAM, char **argv)
924 # if !ENABLE_FEATURE_FANCY_PING
925 return common_ping_main(AF_UNSPEC, argv);
927 return common_ping_main(0, argv);
933 int ping6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
934 int ping6_main(int argc UNUSED_PARAM, char **argv)
936 # if !ENABLE_FEATURE_FANCY_PING
937 return common_ping_main(AF_INET6, argv);
939 return common_ping_main(OPT_IPV6, argv);
945 * Copyright (c) 1989 The Regents of the University of California.
946 * All rights reserved.
948 * This code is derived from software contributed to Berkeley by
951 * Redistribution and use in source and binary forms, with or without
952 * modification, are permitted provided that the following conditions
954 * 1. Redistributions of source code must retain the above copyright
955 * notice, this list of conditions and the following disclaimer.
956 * 2. Redistributions in binary form must reproduce the above copyright
957 * notice, this list of conditions and the following disclaimer in the
958 * documentation and/or other materials provided with the distribution.
960 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
961 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
963 * 4. Neither the name of the University nor the names of its contributors
964 * may be used to endorse or promote products derived from this software
965 * without specific prior written permission.
967 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
968 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
969 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
970 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
971 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
972 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
973 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
974 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
975 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
976 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF