1 /* vi: set sw=4 ts=4: */
3 * $Id: ping.c,v 1.37 2001/02/14 21:23:06 andersen Exp $
4 * Mini ping implementation for busybox
6 * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 * This version of ping is adapted from the ping in netkit-base 0.10,
25 * Copyright (c) 1989 The Regents of the University of California.
26 * All rights reserved.
28 * This code is derived from software contributed to Berkeley by
31 * Original copyright notice is retained at the end of this file.
35 #include <sys/param.h>
36 #include <sys/socket.h>
39 #include <sys/times.h>
40 #include <sys/signal.h>
42 #include <netinet/in.h>
43 #include <netinet/ip.h>
44 #include <netinet/ip_icmp.h>
45 #include <arpa/inet.h>
55 /* It turns out that libc5 doesn't have proper icmp support
56 * built into it header files, so we have to supplement it */
57 #if ! defined __GLIBC__ && ! defined __UCLIBC__
58 typedef unsigned int socklen_t;
60 static const int ICMP_MINLEN = 8; /* abs minimum */
65 u_int32_t ira_preference;
71 u_int8_t icmp_type; /* type of message, see below */
72 u_int8_t icmp_code; /* type sub code */
73 u_int16_t icmp_cksum; /* ones complement checksum of struct */
76 u_char ih_pptr; /* ICMP_PARAMPROB */
77 struct in_addr ih_gwaddr; /* gateway address */
78 struct ih_idseq /* echo datagram */
85 /* ICMP_UNREACH_NEEDFRAG -- Path MTU Discovery (RFC1191) */
89 u_int16_t ipm_nextmtu;
94 u_int8_t irt_num_addrs;
96 u_int16_t irt_lifetime;
99 #define icmp_pptr icmp_hun.ih_pptr
100 #define icmp_gwaddr icmp_hun.ih_gwaddr
101 #define icmp_id icmp_hun.ih_idseq.icd_id
102 #define icmp_seq icmp_hun.ih_idseq.icd_seq
103 #define icmp_void icmp_hun.ih_void
104 #define icmp_pmvoid icmp_hun.ih_pmtu.ipm_void
105 #define icmp_nextmtu icmp_hun.ih_pmtu.ipm_nextmtu
106 #define icmp_num_addrs icmp_hun.ih_rtradv.irt_num_addrs
107 #define icmp_wpa icmp_hun.ih_rtradv.irt_wpa
108 #define icmp_lifetime icmp_hun.ih_rtradv.irt_lifetime
120 /* options and then 64 bits of data */
122 struct icmp_ra_addr id_radv;
126 #define icmp_otime icmp_dun.id_ts.its_otime
127 #define icmp_rtime icmp_dun.id_ts.its_rtime
128 #define icmp_ttime icmp_dun.id_ts.its_ttime
129 #define icmp_ip icmp_dun.id_ip.idi_ip
130 #define icmp_radv icmp_dun.id_radv
131 #define icmp_mask icmp_dun.id_mask
132 #define icmp_data icmp_dun.id_data
136 static const int DEFDATALEN = 56;
137 static const int MAXIPLEN = 60;
138 static const int MAXICMPLEN = 76;
139 static const int MAXPACKET = 65468;
140 #define MAX_DUP_CHK (8 * 128)
141 static const int MAXWAIT = 10;
142 static const int PINGINTERVAL = 1; /* second */
144 #define O_QUIET (1 << 0)
146 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
147 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
148 #define SET(bit) (A(bit) |= B(bit))
149 #define CLR(bit) (A(bit) &= (~B(bit)))
150 #define TST(bit) (A(bit) & B(bit))
152 static void ping(const char *host);
154 /* common routines */
155 static int in_cksum(unsigned short *buf, int sz)
159 unsigned short *w = buf;
160 unsigned short ans = 0;
168 *(unsigned char *) (&ans) = *(unsigned char *) w;
172 sum = (sum >> 16) + (sum & 0xFFFF);
179 #ifdef BB_FEATURE_SIMPLE_PING
180 static char *hostname = NULL;
182 static void noresp(int ign)
184 printf("No response from %s\n", hostname);
188 static void ping(const char *host)
191 struct sockaddr_in pingaddr;
194 char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
196 if ((pingsock = socket(AF_INET, SOCK_RAW, 1)) < 0) /* 1 == ICMP */
197 perror_msg_and_die("creating a raw socket");
199 /* drop root privs if running setuid */
202 memset(&pingaddr, 0, sizeof(struct sockaddr_in));
204 pingaddr.sin_family = AF_INET;
205 if (!(h = gethostbyname(host))) {
206 error_msg("unknown host %s", host);
209 memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
210 hostname = h->h_name;
212 pkt = (struct icmp *) packet;
213 memset(pkt, 0, sizeof(packet));
214 pkt->icmp_type = ICMP_ECHO;
215 pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
217 c = sendto(pingsock, packet, sizeof(packet), 0,
218 (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
220 if (c < 0 || c != sizeof(packet))
221 perror_msg_and_die("sendto");
223 signal(SIGALRM, noresp);
224 alarm(5); /* give the host 5000ms to respond */
225 /* listen for replies */
227 struct sockaddr_in from;
228 size_t fromlen = sizeof(from);
230 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
231 (struct sockaddr *) &from, &fromlen)) < 0) {
234 perror_msg("recvfrom");
237 if (c >= 76) { /* ip + icmp */
238 struct iphdr *iphdr = (struct iphdr *) packet;
240 pkt = (struct icmp *) (packet + (iphdr->ihl << 2)); /* skip ip hdr */
241 if (pkt->icmp_type == ICMP_ECHOREPLY)
245 printf("%s is alive!\n", hostname);
249 extern int ping_main(int argc, char **argv)
259 #else /* ! BB_FEATURE_SIMPLE_PING */
260 /* full(er) version */
261 static char *hostname = NULL;
262 static struct sockaddr_in pingaddr;
263 static int pingsock = -1;
264 static int datalen; /* intentionally uninitialized to work around gcc bug */
266 static long ntransmitted = 0, nreceived = 0, nrepeats = 0, pingcount = 0;
267 static int myid = 0, options = 0;
268 static unsigned long tmin = ULONG_MAX, tmax = 0, tsum = 0;
269 static char rcvd_tbl[MAX_DUP_CHK / 8];
271 static void sendping(int);
272 static void pingstats(int);
273 static void unpack(char *, int, struct sockaddr_in *);
275 /**************************************************************************/
277 static void pingstats(int junk)
281 signal(SIGINT, SIG_IGN);
283 printf("\n--- %s ping statistics ---\n", hostname);
284 printf("%ld packets transmitted, ", ntransmitted);
285 printf("%ld packets received, ", nreceived);
287 printf("%ld duplicates, ", nrepeats);
289 printf("%ld%% packet loss\n",
290 (ntransmitted - nreceived) * 100 / ntransmitted);
292 printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n",
293 tmin / 10, tmin % 10,
294 (tsum / (nreceived + nrepeats)) / 10,
295 (tsum / (nreceived + nrepeats)) % 10, tmax / 10, tmax % 10);
297 status = EXIT_SUCCESS;
299 status = EXIT_FAILURE;
303 static void sendping(int junk)
307 char packet[datalen + 8];
309 pkt = (struct icmp *) packet;
311 pkt->icmp_type = ICMP_ECHO;
314 pkt->icmp_seq = ntransmitted++;
316 CLR(pkt->icmp_seq % MAX_DUP_CHK);
318 gettimeofday((struct timeval *) &packet[8], NULL);
319 pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
321 i = sendto(pingsock, packet, sizeof(packet), 0,
322 (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
325 perror_msg_and_die("sendto");
326 else if ((size_t)i != sizeof(packet))
327 error_msg_and_die("ping wrote %d chars; %d expected", i,
328 (int)sizeof(packet));
330 signal(SIGALRM, sendping);
331 if (pingcount == 0 || ntransmitted < pingcount) { /* schedule next in 1s */
333 } else { /* done, wait for the last ping to come back */
334 /* todo, don't necessarily need to wait so long... */
335 signal(SIGALRM, pingstats);
340 static char *icmp_type_name (int id)
343 case ICMP_ECHOREPLY: return "Echo Reply";
344 case ICMP_DEST_UNREACH: return "Destination Unreachable";
345 case ICMP_SOURCE_QUENCH: return "Source Quench";
346 case ICMP_REDIRECT: return "Redirect (change route)";
347 case ICMP_ECHO: return "Echo Request";
348 case ICMP_TIME_EXCEEDED: return "Time Exceeded";
349 case ICMP_PARAMETERPROB: return "Parameter Problem";
350 case ICMP_TIMESTAMP: return "Timestamp Request";
351 case ICMP_TIMESTAMPREPLY: return "Timestamp Reply";
352 case ICMP_INFO_REQUEST: return "Information Request";
353 case ICMP_INFO_REPLY: return "Information Reply";
354 case ICMP_ADDRESS: return "Address Mask Request";
355 case ICMP_ADDRESSREPLY: return "Address Mask Reply";
356 default: return "unknown ICMP type";
360 static void unpack(char *buf, int sz, struct sockaddr_in *from)
362 struct icmp *icmppkt;
364 struct timeval tv, *tp;
366 unsigned long triptime;
368 gettimeofday(&tv, NULL);
370 /* check IP header */
371 iphdr = (struct iphdr *) buf;
372 hlen = iphdr->ihl << 2;
373 /* discard if too short */
374 if (sz < (datalen + ICMP_MINLEN))
378 icmppkt = (struct icmp *) (buf + hlen);
380 if (icmppkt->icmp_id != myid)
381 return; /* not our ping */
383 if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
385 tp = (struct timeval *) icmppkt->icmp_data;
387 if ((tv.tv_usec -= tp->tv_usec) < 0) {
389 tv.tv_usec += 1000000;
391 tv.tv_sec -= tp->tv_sec;
393 triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
400 if (TST(icmppkt->icmp_seq % MAX_DUP_CHK)) {
405 SET(icmppkt->icmp_seq % MAX_DUP_CHK);
409 if (options & O_QUIET)
412 printf("%d bytes from %s: icmp_seq=%u", sz,
413 inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
415 printf(" ttl=%d", iphdr->ttl);
416 printf(" time=%lu.%lu ms", triptime / 10, triptime % 10);
421 if (icmppkt->icmp_type != ICMP_ECHO)
422 error_msg("Warning: Got ICMP %d (%s)",
423 icmppkt->icmp_type, icmp_type_name (icmppkt->icmp_type));
426 static void ping(const char *host)
428 struct protoent *proto;
430 char buf[MAXHOSTNAMELEN];
431 char packet[datalen + MAXIPLEN + MAXICMPLEN];
434 proto = getprotobyname("icmp");
435 /* if getprotobyname failed, just silently force
436 * proto->p_proto to have the correct value for "icmp" */
437 if ((pingsock = socket(AF_INET, SOCK_RAW,
438 (proto ? proto->p_proto : 1))) < 0) { /* 1 == ICMP */
440 error_msg_and_die("permission denied. (are you root?)");
442 perror_msg_and_die("creating a raw socket");
445 /* drop root privs if running setuid */
448 memset(&pingaddr, 0, sizeof(struct sockaddr_in));
450 pingaddr.sin_family = AF_INET;
451 if (!(h = gethostbyname(host))) {
452 error_msg("unknown host %s", host);
456 if (h->h_addrtype != AF_INET) {
457 error_msg("unknown address type; only AF_INET is currently supported.");
461 pingaddr.sin_family = AF_INET; /* h->h_addrtype */
462 memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
463 strncpy(buf, h->h_name, sizeof(buf) - 1);
466 /* enable broadcast pings */
468 setsockopt(pingsock, SOL_SOCKET, SO_BROADCAST, (char *) &sockopt,
471 /* set recv buf for broadcast pings */
473 setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, (char *) &sockopt,
476 printf("PING %s (%s): %d data bytes\n",
478 inet_ntoa(*(struct in_addr *) &pingaddr.sin_addr.s_addr),
481 signal(SIGINT, pingstats);
483 /* start the ping's going ... */
486 /* listen for replies */
488 struct sockaddr_in from;
489 socklen_t fromlen = (socklen_t) sizeof(from);
492 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
493 (struct sockaddr *) &from, &fromlen)) < 0) {
496 perror_msg("recvfrom");
499 unpack(packet, c, &from);
500 if (pingcount > 0 && nreceived >= pingcount)
506 extern int ping_main(int argc, char **argv)
510 datalen = DEFDATALEN; /* initialized here rather than in global scope to work around gcc bug */
515 /* Parse any options */
516 while (argc >= 1 && **argv == '-') {
527 pingcount = atoi(*argv);
533 datalen = atoi(*argv);
544 myid = getpid() & 0xFFFF;
548 #endif /* ! BB_FEATURE_SIMPLE_PING */
551 * Copyright (c) 1989 The Regents of the University of California.
552 * All rights reserved.
554 * This code is derived from software contributed to Berkeley by
557 * Redistribution and use in source and binary forms, with or without
558 * modification, are permitted provided that the following conditions
560 * 1. Redistributions of source code must retain the above copyright
561 * notice, this list of conditions and the following disclaimer.
562 * 2. Redistributions in binary form must reproduce the above copyright
563 * notice, this list of conditions and the following disclaimer in the
564 * documentation and/or other materials provided with the distribution.
566 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
567 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
569 * 4. Neither the name of the University nor the names of its contributors
570 * may be used to endorse or promote products derived from this software
571 * without specific prior written permission.
573 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
574 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
575 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
576 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
577 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
578 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
579 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
580 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
581 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
582 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF