1 /* vi: set sw=4 ts=4: */
3 * $Id: ping.c,v 1.56 2004/03/15 08:28:48 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 static const int DEFDATALEN = 56;
56 static const int MAXIPLEN = 60;
57 static const int MAXICMPLEN = 76;
58 static const int MAXPACKET = 65468;
59 #define MAX_DUP_CHK (8 * 128)
60 static const int MAXWAIT = 10;
61 static const int PINGINTERVAL = 1; /* second */
63 #define O_QUIET (1 << 0)
65 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
66 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
67 #define SET(bit) (A(bit) |= B(bit))
68 #define CLR(bit) (A(bit) &= (~B(bit)))
69 #define TST(bit) (A(bit) & B(bit))
71 static void ping(const char *host);
74 static int in_cksum(unsigned short *buf, int sz)
78 unsigned short *w = buf;
79 unsigned short ans = 0;
87 *(unsigned char *) (&ans) = *(unsigned char *) w;
91 sum = (sum >> 16) + (sum & 0xFFFF);
98 #ifndef CONFIG_FEATURE_FANCY_PING
99 static char *hostname = NULL;
100 static void noresp(int ign)
102 printf("No response from %s\n", hostname);
106 static void ping(const char *host)
109 struct sockaddr_in pingaddr;
112 char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
114 pingsock = create_icmp_socket();
116 memset(&pingaddr, 0, sizeof(struct sockaddr_in));
118 pingaddr.sin_family = AF_INET;
119 h = xgethostbyname(host);
120 memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
121 hostname = h->h_name;
123 pkt = (struct icmp *) packet;
124 memset(pkt, 0, sizeof(packet));
125 pkt->icmp_type = ICMP_ECHO;
126 pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
128 c = sendto(pingsock, packet, sizeof(packet), 0,
129 (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
131 if (c < 0 || c != sizeof(packet))
132 bb_perror_msg_and_die("sendto");
134 signal(SIGALRM, noresp);
135 alarm(5); /* give the host 5000ms to respond */
136 /* listen for replies */
138 struct sockaddr_in from;
139 socklen_t fromlen = sizeof(from);
141 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
142 (struct sockaddr *) &from, &fromlen)) < 0) {
145 bb_perror_msg("recvfrom");
148 if (c >= 76) { /* ip + icmp */
149 struct iphdr *iphdr = (struct iphdr *) packet;
151 pkt = (struct icmp *) (packet + (iphdr->ihl << 2)); /* skip ip hdr */
152 if (pkt->icmp_type == ICMP_ECHOREPLY)
156 printf("%s is alive!\n", hostname);
160 extern int ping_main(int argc, char **argv)
170 #else /* ! CONFIG_FEATURE_FANCY_PING */
171 /* full(er) version */
172 static struct sockaddr_in pingaddr;
173 static int pingsock = -1;
174 static int datalen; /* intentionally uninitialized to work around gcc bug */
176 static long ntransmitted, nreceived, nrepeats, pingcount;
177 static int myid, options;
178 static unsigned long tmin = ULONG_MAX, tmax, tsum;
179 static char rcvd_tbl[MAX_DUP_CHK / 8];
181 #ifndef CONFIG_FEATURE_FANCY_PING6
184 struct hostent *hostent;
186 static void sendping(int);
187 static void pingstats(int);
188 static void unpack(char *, int, struct sockaddr_in *);
190 /**************************************************************************/
192 static void pingstats(int junk)
196 signal(SIGINT, SIG_IGN);
198 printf("\n--- %s ping statistics ---\n", hostent->h_name);
199 printf("%ld packets transmitted, ", ntransmitted);
200 printf("%ld packets received, ", nreceived);
202 printf("%ld duplicates, ", nrepeats);
204 printf("%ld%% packet loss\n",
205 (ntransmitted - nreceived) * 100 / ntransmitted);
207 printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n",
208 tmin / 10, tmin % 10,
209 (tsum / (nreceived + nrepeats)) / 10,
210 (tsum / (nreceived + nrepeats)) % 10, tmax / 10, tmax % 10);
212 status = EXIT_SUCCESS;
214 status = EXIT_FAILURE;
218 static void sendping(int junk)
222 char packet[datalen + 8];
224 pkt = (struct icmp *) packet;
226 pkt->icmp_type = ICMP_ECHO;
229 pkt->icmp_seq = htons(ntransmitted++);
231 CLR(ntohs(pkt->icmp_seq) % MAX_DUP_CHK);
233 gettimeofday((struct timeval *) &packet[8], NULL);
234 pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
236 i = sendto(pingsock, packet, sizeof(packet), 0,
237 (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
240 bb_perror_msg_and_die("sendto");
241 else if ((size_t)i != sizeof(packet))
242 bb_error_msg_and_die("ping wrote %d chars; %d expected", i,
243 (int)sizeof(packet));
245 signal(SIGALRM, sendping);
246 if (pingcount == 0 || ntransmitted < pingcount) { /* schedule next in 1s */
248 } else { /* done, wait for the last ping to come back */
249 /* todo, don't necessarily need to wait so long... */
250 signal(SIGALRM, pingstats);
255 static char *icmp_type_name (int id)
258 case ICMP_ECHOREPLY: return "Echo Reply";
259 case ICMP_DEST_UNREACH: return "Destination Unreachable";
260 case ICMP_SOURCE_QUENCH: return "Source Quench";
261 case ICMP_REDIRECT: return "Redirect (change route)";
262 case ICMP_ECHO: return "Echo Request";
263 case ICMP_TIME_EXCEEDED: return "Time Exceeded";
264 case ICMP_PARAMETERPROB: return "Parameter Problem";
265 case ICMP_TIMESTAMP: return "Timestamp Request";
266 case ICMP_TIMESTAMPREPLY: return "Timestamp Reply";
267 case ICMP_INFO_REQUEST: return "Information Request";
268 case ICMP_INFO_REPLY: return "Information Reply";
269 case ICMP_ADDRESS: return "Address Mask Request";
270 case ICMP_ADDRESSREPLY: return "Address Mask Reply";
271 default: return "unknown ICMP type";
275 static void unpack(char *buf, int sz, struct sockaddr_in *from)
277 struct icmp *icmppkt;
279 struct timeval tv, *tp;
281 unsigned long triptime;
283 gettimeofday(&tv, NULL);
285 /* check IP header */
286 iphdr = (struct iphdr *) buf;
287 hlen = iphdr->ihl << 2;
288 /* discard if too short */
289 if (sz < (datalen + ICMP_MINLEN))
293 icmppkt = (struct icmp *) (buf + hlen);
295 if (icmppkt->icmp_id != myid)
296 return; /* not our ping */
298 if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
299 u_int16_t recv_seq = ntohs(icmppkt->icmp_seq);
301 tp = (struct timeval *) icmppkt->icmp_data;
303 if ((tv.tv_usec -= tp->tv_usec) < 0) {
305 tv.tv_usec += 1000000;
307 tv.tv_sec -= tp->tv_sec;
309 triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
316 if (TST(recv_seq % MAX_DUP_CHK)) {
321 SET(recv_seq % MAX_DUP_CHK);
325 if (options & O_QUIET)
328 printf("%d bytes from %s: icmp_seq=%u", sz,
329 inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
331 printf(" ttl=%d", iphdr->ttl);
332 printf(" time=%lu.%lu ms", triptime / 10, triptime % 10);
337 if (icmppkt->icmp_type != ICMP_ECHO)
338 bb_error_msg("Warning: Got ICMP %d (%s)",
339 icmppkt->icmp_type, icmp_type_name (icmppkt->icmp_type));
342 static void ping(const char *host)
344 char packet[datalen + MAXIPLEN + MAXICMPLEN];
347 pingsock = create_icmp_socket();
349 memset(&pingaddr, 0, sizeof(struct sockaddr_in));
351 pingaddr.sin_family = AF_INET;
352 hostent = xgethostbyname(host);
353 if (hostent->h_addrtype != AF_INET)
354 bb_error_msg_and_die("unknown address type; only AF_INET is currently supported.");
356 memcpy(&pingaddr.sin_addr, hostent->h_addr, sizeof(pingaddr.sin_addr));
358 /* enable broadcast pings */
360 setsockopt(pingsock, SOL_SOCKET, SO_BROADCAST, (char *) &sockopt,
363 /* set recv buf for broadcast pings */
365 setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, (char *) &sockopt,
368 printf("PING %s (%s): %d data bytes\n",
370 inet_ntoa(*(struct in_addr *) &pingaddr.sin_addr.s_addr),
373 signal(SIGINT, pingstats);
375 /* start the ping's going ... */
378 /* listen for replies */
380 struct sockaddr_in from;
381 socklen_t fromlen = (socklen_t) sizeof(from);
384 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
385 (struct sockaddr *) &from, &fromlen)) < 0) {
388 bb_perror_msg("recvfrom");
391 unpack(packet, c, &from);
392 if (pingcount > 0 && nreceived >= pingcount)
398 extern int ping_main(int argc, char **argv)
402 datalen = DEFDATALEN; /* initialized here rather than in global scope to work around gcc bug */
407 /* Parse any options */
408 while (argc >= 1 && **argv == '-') {
419 pingcount = atoi(*argv);
425 datalen = atoi(*argv);
436 myid = getpid() & 0xFFFF;
440 #endif /* ! CONFIG_FEATURE_FANCY_PING */
443 * Copyright (c) 1989 The Regents of the University of California.
444 * All rights reserved.
446 * This code is derived from software contributed to Berkeley by
449 * Redistribution and use in source and binary forms, with or without
450 * modification, are permitted provided that the following conditions
452 * 1. Redistributions of source code must retain the above copyright
453 * notice, this list of conditions and the following disclaimer.
454 * 2. Redistributions in binary form must reproduce the above copyright
455 * notice, this list of conditions and the following disclaimer in the
456 * documentation and/or other materials provided with the distribution.
458 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
459 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
461 * 4. Neither the name of the University nor the names of its contributors
462 * may be used to endorse or promote products derived from this software
463 * without specific prior written permission.
465 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
466 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
467 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
468 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
469 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
470 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
471 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
472 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
473 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
474 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF