1 /* vi: set sw=4 ts=4: */
3 * $Id: ping.c,v 1.39 2001/03/14 01:23:07 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.
34 #include <sys/param.h>
35 #include <sys/socket.h>
38 #include <sys/times.h>
39 #include <sys/signal.h>
41 #include <netinet/in.h>
42 #include <netinet/ip.h>
43 #include <netinet/ip_icmp.h>
44 #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 static const int ICMP_MINLEN = 8; /* abs minimum */
63 u_int32_t ira_preference;
69 u_int8_t icmp_type; /* type of message, see below */
70 u_int8_t icmp_code; /* type sub code */
71 u_int16_t icmp_cksum; /* ones complement checksum of struct */
74 u_char ih_pptr; /* ICMP_PARAMPROB */
75 struct in_addr ih_gwaddr; /* gateway address */
76 struct ih_idseq /* echo datagram */
83 /* ICMP_UNREACH_NEEDFRAG -- Path MTU Discovery (RFC1191) */
87 u_int16_t ipm_nextmtu;
92 u_int8_t irt_num_addrs;
94 u_int16_t irt_lifetime;
97 #define icmp_pptr icmp_hun.ih_pptr
98 #define icmp_gwaddr icmp_hun.ih_gwaddr
99 #define icmp_id icmp_hun.ih_idseq.icd_id
100 #define icmp_seq icmp_hun.ih_idseq.icd_seq
101 #define icmp_void icmp_hun.ih_void
102 #define icmp_pmvoid icmp_hun.ih_pmtu.ipm_void
103 #define icmp_nextmtu icmp_hun.ih_pmtu.ipm_nextmtu
104 #define icmp_num_addrs icmp_hun.ih_rtradv.irt_num_addrs
105 #define icmp_wpa icmp_hun.ih_rtradv.irt_wpa
106 #define icmp_lifetime icmp_hun.ih_rtradv.irt_lifetime
118 /* options and then 64 bits of data */
120 struct icmp_ra_addr id_radv;
124 #define icmp_otime icmp_dun.id_ts.its_otime
125 #define icmp_rtime icmp_dun.id_ts.its_rtime
126 #define icmp_ttime icmp_dun.id_ts.its_ttime
127 #define icmp_ip icmp_dun.id_ip.idi_ip
128 #define icmp_radv icmp_dun.id_radv
129 #define icmp_mask icmp_dun.id_mask
130 #define icmp_data icmp_dun.id_data
134 static const int DEFDATALEN = 56;
135 static const int MAXIPLEN = 60;
136 static const int MAXICMPLEN = 76;
137 static const int MAXPACKET = 65468;
138 #define MAX_DUP_CHK (8 * 128)
139 static const int MAXWAIT = 10;
140 static const int PINGINTERVAL = 1; /* second */
142 #define O_QUIET (1 << 0)
144 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
145 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
146 #define SET(bit) (A(bit) |= B(bit))
147 #define CLR(bit) (A(bit) &= (~B(bit)))
148 #define TST(bit) (A(bit) & B(bit))
150 static void ping(const char *host);
152 /* common routines */
153 static int in_cksum(unsigned short *buf, int sz)
157 unsigned short *w = buf;
158 unsigned short ans = 0;
166 *(unsigned char *) (&ans) = *(unsigned char *) w;
170 sum = (sum >> 16) + (sum & 0xFFFF);
177 #ifdef BB_FEATURE_SIMPLE_PING
178 static char *hostname = NULL;
180 static void noresp(int ign)
182 printf("No response from %s\n", hostname);
186 static void ping(const char *host)
189 struct sockaddr_in pingaddr;
192 char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
194 if ((pingsock = socket(AF_INET, SOCK_RAW, 1)) < 0) /* 1 == ICMP */
195 perror_msg_and_die("creating a raw socket");
197 /* drop root privs if running setuid */
200 memset(&pingaddr, 0, sizeof(struct sockaddr_in));
202 pingaddr.sin_family = AF_INET;
203 if (!(h = gethostbyname(host))) {
204 error_msg("unknown host %s", host);
207 memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
208 hostname = h->h_name;
210 pkt = (struct icmp *) packet;
211 memset(pkt, 0, sizeof(packet));
212 pkt->icmp_type = ICMP_ECHO;
213 pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
215 c = sendto(pingsock, packet, sizeof(packet), 0,
216 (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
218 if (c < 0 || c != sizeof(packet))
219 perror_msg_and_die("sendto");
221 signal(SIGALRM, noresp);
222 alarm(5); /* give the host 5000ms to respond */
223 /* listen for replies */
225 struct sockaddr_in from;
226 size_t fromlen = sizeof(from);
228 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
229 (struct sockaddr *) &from, &fromlen)) < 0) {
232 perror_msg("recvfrom");
235 if (c >= 76) { /* ip + icmp */
236 struct iphdr *iphdr = (struct iphdr *) packet;
238 pkt = (struct icmp *) (packet + (iphdr->ihl << 2)); /* skip ip hdr */
239 if (pkt->icmp_type == ICMP_ECHOREPLY)
243 printf("%s is alive!\n", hostname);
247 extern int ping_main(int argc, char **argv)
257 #else /* ! BB_FEATURE_SIMPLE_PING */
258 /* full(er) version */
259 static char *hostname = NULL;
260 static struct sockaddr_in pingaddr;
261 static int pingsock = -1;
262 static int datalen; /* intentionally uninitialized to work around gcc bug */
264 static long ntransmitted = 0, nreceived = 0, nrepeats = 0, pingcount = 0;
265 static int myid = 0, options = 0;
266 static unsigned long tmin = ULONG_MAX, tmax = 0, tsum = 0;
267 static char rcvd_tbl[MAX_DUP_CHK / 8];
269 static void sendping(int);
270 static void pingstats(int);
271 static void unpack(char *, int, struct sockaddr_in *);
273 /**************************************************************************/
275 static void pingstats(int junk)
279 signal(SIGINT, SIG_IGN);
281 printf("\n--- %s ping statistics ---\n", hostname);
282 printf("%ld packets transmitted, ", ntransmitted);
283 printf("%ld packets received, ", nreceived);
285 printf("%ld duplicates, ", nrepeats);
287 printf("%ld%% packet loss\n",
288 (ntransmitted - nreceived) * 100 / ntransmitted);
290 printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n",
291 tmin / 10, tmin % 10,
292 (tsum / (nreceived + nrepeats)) / 10,
293 (tsum / (nreceived + nrepeats)) % 10, tmax / 10, tmax % 10);
295 status = EXIT_SUCCESS;
297 status = EXIT_FAILURE;
301 static void sendping(int junk)
305 char packet[datalen + 8];
307 pkt = (struct icmp *) packet;
309 pkt->icmp_type = ICMP_ECHO;
312 pkt->icmp_seq = ntransmitted++;
314 CLR(pkt->icmp_seq % MAX_DUP_CHK);
316 gettimeofday((struct timeval *) &packet[8], NULL);
317 pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
319 i = sendto(pingsock, packet, sizeof(packet), 0,
320 (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
323 perror_msg_and_die("sendto");
324 else if ((size_t)i != sizeof(packet))
325 error_msg_and_die("ping wrote %d chars; %d expected", i,
326 (int)sizeof(packet));
328 signal(SIGALRM, sendping);
329 if (pingcount == 0 || ntransmitted < pingcount) { /* schedule next in 1s */
331 } else { /* done, wait for the last ping to come back */
332 /* todo, don't necessarily need to wait so long... */
333 signal(SIGALRM, pingstats);
338 static char *icmp_type_name (int id)
341 case ICMP_ECHOREPLY: return "Echo Reply";
342 case ICMP_DEST_UNREACH: return "Destination Unreachable";
343 case ICMP_SOURCE_QUENCH: return "Source Quench";
344 case ICMP_REDIRECT: return "Redirect (change route)";
345 case ICMP_ECHO: return "Echo Request";
346 case ICMP_TIME_EXCEEDED: return "Time Exceeded";
347 case ICMP_PARAMETERPROB: return "Parameter Problem";
348 case ICMP_TIMESTAMP: return "Timestamp Request";
349 case ICMP_TIMESTAMPREPLY: return "Timestamp Reply";
350 case ICMP_INFO_REQUEST: return "Information Request";
351 case ICMP_INFO_REPLY: return "Information Reply";
352 case ICMP_ADDRESS: return "Address Mask Request";
353 case ICMP_ADDRESSREPLY: return "Address Mask Reply";
354 default: return "unknown ICMP type";
358 static void unpack(char *buf, int sz, struct sockaddr_in *from)
360 struct icmp *icmppkt;
362 struct timeval tv, *tp;
364 unsigned long triptime;
366 gettimeofday(&tv, NULL);
368 /* check IP header */
369 iphdr = (struct iphdr *) buf;
370 hlen = iphdr->ihl << 2;
371 /* discard if too short */
372 if (sz < (datalen + ICMP_MINLEN))
376 icmppkt = (struct icmp *) (buf + hlen);
378 if (icmppkt->icmp_id != myid)
379 return; /* not our ping */
381 if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
383 tp = (struct timeval *) icmppkt->icmp_data;
385 if ((tv.tv_usec -= tp->tv_usec) < 0) {
387 tv.tv_usec += 1000000;
389 tv.tv_sec -= tp->tv_sec;
391 triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
398 if (TST(icmppkt->icmp_seq % MAX_DUP_CHK)) {
403 SET(icmppkt->icmp_seq % MAX_DUP_CHK);
407 if (options & O_QUIET)
410 printf("%d bytes from %s: icmp_seq=%u", sz,
411 inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
413 printf(" ttl=%d", iphdr->ttl);
414 printf(" time=%lu.%lu ms", triptime / 10, triptime % 10);
419 if (icmppkt->icmp_type != ICMP_ECHO)
420 error_msg("Warning: Got ICMP %d (%s)",
421 icmppkt->icmp_type, icmp_type_name (icmppkt->icmp_type));
424 static void ping(const char *host)
426 struct protoent *proto;
428 char buf[MAXHOSTNAMELEN];
429 char packet[datalen + MAXIPLEN + MAXICMPLEN];
432 proto = getprotobyname("icmp");
433 /* if getprotobyname failed, just silently force
434 * proto->p_proto to have the correct value for "icmp" */
435 if ((pingsock = socket(AF_INET, SOCK_RAW,
436 (proto ? proto->p_proto : 1))) < 0) { /* 1 == ICMP */
438 error_msg_and_die("permission denied. (are you root?)");
440 perror_msg_and_die("creating a raw socket");
443 /* drop root privs if running setuid */
446 memset(&pingaddr, 0, sizeof(struct sockaddr_in));
448 pingaddr.sin_family = AF_INET;
449 if (!(h = gethostbyname(host))) {
450 error_msg("unknown host %s", host);
454 if (h->h_addrtype != AF_INET) {
455 error_msg("unknown address type; only AF_INET is currently supported.");
459 pingaddr.sin_family = AF_INET; /* h->h_addrtype */
460 memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
461 strncpy(buf, h->h_name, sizeof(buf) - 1);
464 /* enable broadcast pings */
466 setsockopt(pingsock, SOL_SOCKET, SO_BROADCAST, (char *) &sockopt,
469 /* set recv buf for broadcast pings */
471 setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, (char *) &sockopt,
474 printf("PING %s (%s): %d data bytes\n",
476 inet_ntoa(*(struct in_addr *) &pingaddr.sin_addr.s_addr),
479 signal(SIGINT, pingstats);
481 /* start the ping's going ... */
484 /* listen for replies */
486 struct sockaddr_in from;
487 socklen_t fromlen = (socklen_t) sizeof(from);
490 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
491 (struct sockaddr *) &from, &fromlen)) < 0) {
494 perror_msg("recvfrom");
497 unpack(packet, c, &from);
498 if (pingcount > 0 && nreceived >= pingcount)
504 extern int ping_main(int argc, char **argv)
508 datalen = DEFDATALEN; /* initialized here rather than in global scope to work around gcc bug */
513 /* Parse any options */
514 while (argc >= 1 && **argv == '-') {
525 pingcount = atoi(*argv);
531 datalen = atoi(*argv);
542 myid = getpid() & 0xFFFF;
546 #endif /* ! BB_FEATURE_SIMPLE_PING */
549 * Copyright (c) 1989 The Regents of the University of California.
550 * All rights reserved.
552 * This code is derived from software contributed to Berkeley by
555 * Redistribution and use in source and binary forms, with or without
556 * modification, are permitted provided that the following conditions
558 * 1. Redistributions of source code must retain the above copyright
559 * notice, this list of conditions and the following disclaimer.
560 * 2. Redistributions in binary form must reproduce the above copyright
561 * notice, this list of conditions and the following disclaimer in the
562 * documentation and/or other materials provided with the distribution.
564 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
565 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
567 * 4. Neither the name of the University nor the names of its contributors
568 * may be used to endorse or promote products derived from this software
569 * without specific prior written permission.
571 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
572 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
573 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
574 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
575 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
576 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
577 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
578 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
579 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
580 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF