1 /* vi: set sw=4 ts=4: */
3 * $Id: ping.c,v 1.55 2003/07/22 08:56:51 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 PING_PID_FILE "/var/pingPid"
66 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
67 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
68 #define SET(bit) (A(bit) |= B(bit))
69 #define CLR(bit) (A(bit) &= (~B(bit)))
70 #define TST(bit) (A(bit) & B(bit))
73 /* store ping statistics to a file */
78 static void ping(const char *host);
81 static int in_cksum(unsigned short *buf, int sz)
85 unsigned short *w = buf;
86 unsigned short ans = 0;
94 *(unsigned char *) (&ans) = *(unsigned char *) w;
98 sum = (sum >> 16) + (sum & 0xFFFF);
105 #ifndef CONFIG_FEATURE_FANCY_PING
106 static char *hostname = NULL;
107 static void noresp(int ign)
109 printf("No response from %s\n", hostname);
113 static void ping(const char *host)
116 struct sockaddr_in pingaddr;
119 char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
121 pingsock = create_icmp_socket();
123 memset(&pingaddr, 0, sizeof(struct sockaddr_in));
125 pingaddr.sin_family = AF_INET;
126 h = xgethostbyname(host);
127 memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
128 hostname = h->h_name;
130 pkt = (struct icmp *) packet;
131 memset(pkt, 0, sizeof(packet));
132 pkt->icmp_type = ICMP_ECHO;
133 pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
135 c = sendto(pingsock, packet, sizeof(packet), 0,
136 (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
138 if (c < 0 || c != sizeof(packet))
139 bb_perror_msg_and_die("sendto");
141 signal(SIGALRM, noresp);
142 alarm(5); /* give the host 5000ms to respond */
143 /* listen for replies */
145 struct sockaddr_in from;
146 size_t fromlen = sizeof(from);
148 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
149 (struct sockaddr *) &from, &fromlen)) < 0) {
152 bb_perror_msg("recvfrom");
155 if (c >= 76) { /* ip + icmp */
156 struct iphdr *iphdr = (struct iphdr *) packet;
158 pkt = (struct icmp *) (packet + (iphdr->ihl << 2)); /* skip ip hdr */
159 if (pkt->icmp_type == ICMP_ECHOREPLY)
163 printf("%s is alive!\n", hostname);
167 extern int ping_main(int argc, char **argv)
177 #else /* ! CONFIG_FEATURE_FANCY_PING */
178 /* full(er) version */
179 static struct sockaddr_in pingaddr;
180 static int pingsock = -1;
181 static int datalen; /* intentionally uninitialized to work around gcc bug */
183 // brcm: changed default value of pingcount from 0 to 4.
184 static long ntransmitted, nreceived, nrepeats, pingcount=4;
185 static int myid, options;
186 static unsigned long tmin = ULONG_MAX, tmax, tsum;
187 static char rcvd_tbl[MAX_DUP_CHK / 8];
189 struct hostent *hostent;
191 static void sendping(int);
192 static void pingstats(int);
193 static void unpack(char *, int, struct sockaddr_in *);
195 static void logStat(int finish)
200 pingFile = fopen ("/var/pingStats", "w");
201 if (pingFile == NULL)
205 if ((finish) && (ntransmitted == 0))
206 fprintf(pingFile,"%d\n",-1);
208 fprintf(pingFile,"%d\n",finish);
210 memcpy(&addr, hostent->h_addr, sizeof(ip));
211 strncpy(ip,inet_ntoa(addr),16);
212 /* IP, sent, receive, lost, min, max, average */
214 fprintf(pingFile,"IP = %s Sent = %ld Receive = %ld Lost = %ld Min = %lu.%lu ms Max = %lu.%lu ms Average = %lu.%lu ms \n",
215 ip, ntransmitted, nreceived, (ntransmitted-nreceived),
216 (tmin / 10), (tmin % 10),
217 (tmax / 10), (tmax % 10),
218 ((tsum / (nreceived + nrepeats)) / 10),
219 ((tsum / (nreceived + nrepeats)) % 10));
221 fprintf(pingFile,"IP = %s Sent = %ld Receive = %ld Lost = %ld Min = %lu.%lu ms Max = %lu.%lu ms Average = %lu.%lu ms \n",
222 ip, ntransmitted, nreceived, (ntransmitted-nreceived),
223 (tmin / 10), (tmin % 10),
224 (tmin / 10), (tmin % 10),
225 (tmin / 10), (tmin % 10));
229 /**************************************************************************/
231 static void pingstats(int junk)
235 signal(SIGINT, SIG_IGN);
236 printf("\n--- %s ping statistics ---\n", hostent->h_name);
237 printf("%ld packets transmitted, ", ntransmitted);
238 printf("%ld packets received, ", nreceived);
240 printf("%ld duplicates, ", nrepeats);
242 printf("%ld%% packet loss\n",
243 (ntransmitted - nreceived) * 100 / ntransmitted);
245 printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n",
246 tmin / 10, tmin % 10,
247 (tsum / (nreceived + nrepeats)) / 10,
248 (tsum / (nreceived + nrepeats)) % 10, tmax / 10, tmax % 10);
250 status = EXIT_SUCCESS;
252 status = EXIT_FAILURE;
255 if (options & O_LOG) {
257 remove_file(PING_PID_FILE,FILEUTILS_FORCE);
264 static void sendping(int junk)
268 char packet[datalen + 8];
270 pkt = (struct icmp *) packet;
272 pkt->icmp_type = ICMP_ECHO;
275 pkt->icmp_seq = ntransmitted++;
277 CLR(pkt->icmp_seq % MAX_DUP_CHK);
279 gettimeofday((struct timeval *) &packet[8], NULL);
280 pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
282 i = sendto(pingsock, packet, sizeof(packet), 0,
283 (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
286 bb_perror_msg_and_die("sendto");
287 else if ((size_t)i != sizeof(packet))
288 bb_error_msg_and_die("ping wrote %d chars; %d expected", i,
289 (int)sizeof(packet));
291 signal(SIGALRM, sendping);
292 if (pingcount == 0 || ntransmitted < pingcount) { /* schedule next in 1s */
294 } else { /* done, wait for the last ping to come back */
295 /* todo, don't necessarily need to wait so long... */
296 signal(SIGALRM, pingstats);
301 static char *icmp_type_name (int id)
304 case ICMP_ECHOREPLY: return "Echo Reply";
305 case ICMP_DEST_UNREACH: return "Destination Unreachable";
306 case ICMP_SOURCE_QUENCH: return "Source Quench";
307 case ICMP_REDIRECT: return "Redirect (change route)";
308 case ICMP_ECHO: return "Echo Request";
309 case ICMP_TIME_EXCEEDED: return "Time Exceeded";
310 case ICMP_PARAMETERPROB: return "Parameter Problem";
311 case ICMP_TIMESTAMP: return "Timestamp Request";
312 case ICMP_TIMESTAMPREPLY: return "Timestamp Reply";
313 case ICMP_INFO_REQUEST: return "Information Request";
314 case ICMP_INFO_REPLY: return "Information Reply";
315 case ICMP_ADDRESS: return "Address Mask Request";
316 case ICMP_ADDRESSREPLY: return "Address Mask Reply";
317 default: return "unknown ICMP type";
321 static void unpack(char *buf, int sz, struct sockaddr_in *from)
323 struct icmp *icmppkt;
325 struct timeval tv, *tp;
327 unsigned long triptime;
329 gettimeofday(&tv, NULL);
331 /* check IP header */
332 iphdr = (struct iphdr *) buf;
333 hlen = iphdr->ihl << 2;
334 /* discard if too short */
335 if (sz < (datalen + ICMP_MINLEN))
339 icmppkt = (struct icmp *) (buf + hlen);
341 if (icmppkt->icmp_id != myid)
342 return; /* not our ping */
344 if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
346 tp = (struct timeval *) icmppkt->icmp_data;
348 if ((tv.tv_usec -= tp->tv_usec) < 0) {
350 tv.tv_usec += 1000000;
352 tv.tv_sec -= tp->tv_sec;
354 triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
361 if (TST(icmppkt->icmp_seq % MAX_DUP_CHK)) {
366 SET(icmppkt->icmp_seq % MAX_DUP_CHK);
370 if (options & O_LOG) {
376 if (options & O_QUIET)
379 /*brcm: changed display message to show actually receive data bytes length
380 rather than ICMP packet length which is ICMP_MINLEN+dataLen */
381 printf("%d bytes from %s: icmp_seq=%u", (sz-ICMP_MINLEN),
382 inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
384 printf(" ttl=%d", iphdr->ttl);
385 printf(" time=%lu.%lu ms", triptime / 10, triptime % 10);
390 if (icmppkt->icmp_type != ICMP_ECHO)
391 bb_error_msg("Warning: Got ICMP %d (%s)",
392 icmppkt->icmp_type, icmp_type_name (icmppkt->icmp_type));
395 static void ping(const char *host)
397 char packet[datalen + MAXIPLEN + MAXICMPLEN];
400 pingsock = create_icmp_socket();
402 memset(&pingaddr, 0, sizeof(struct sockaddr_in));
404 pingaddr.sin_family = AF_INET;
405 hostent = xgethostbyname(host);
407 if (hostent->h_addrtype != AF_INET)
408 bb_error_msg_and_die("unknown address type; only AF_INET is currently supported.");
410 memcpy(&pingaddr.sin_addr, hostent->h_addr, sizeof(pingaddr.sin_addr));
412 /* enable broadcast pings */
414 setsockopt(pingsock, SOL_SOCKET, SO_BROADCAST, (char *) &sockopt,
417 /* set recv buf for broadcast pings */
419 setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, (char *) &sockopt,
422 printf("PING %s (%s): %d data bytes\n",
424 inet_ntoa(*(struct in_addr *) &pingaddr.sin_addr.s_addr),
427 signal(SIGINT, pingstats);
429 /* start the ping's going ... */
432 /* listen for replies */
434 struct sockaddr_in from;
435 socklen_t fromlen = (socklen_t) sizeof(from);
438 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
439 (struct sockaddr *) &from, &fromlen)) < 0) {
442 bb_perror_msg("recvfrom");
445 unpack(packet, c, &from);
446 if (pingcount > 0 && nreceived >= pingcount)
452 extern int ping_main(int argc, char **argv)
457 datalen = DEFDATALEN; /* initialized here rather than in global scope to work around gcc bug */
462 /* Parse any options */
463 while (argc >= 1 && **argv == '-') {
474 pingcount = atoi(*argv);
480 datalen = atoi(*argv);
484 if ((pingPid = fopen (PING_PID_FILE, "w")) != NULL) {
485 fprintf(pingPid,"%d\n",getpid());
486 (void)fclose(pingPid);
488 /* log statistics to file */
501 myid = getpid() & 0xFFFF;
504 if (options & O_LOG) {
505 remove_file(PING_PID_FILE,FILEUTILS_FORCE);
509 #endif /* ! CONFIG_FEATURE_FANCY_PING */
512 * Copyright (c) 1989 The Regents of the University of California.
513 * All rights reserved.
515 * This code is derived from software contributed to Berkeley by
518 * Redistribution and use in source and binary forms, with or without
519 * modification, are permitted provided that the following conditions
521 * 1. Redistributions of source code must retain the above copyright
522 * notice, this list of conditions and the following disclaimer.
523 * 2. Redistributions in binary form must reproduce the above copyright
524 * notice, this list of conditions and the following disclaimer in the
525 * documentation and/or other materials provided with the distribution.
527 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
528 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
530 * 4. Neither the name of the University nor the names of its contributors
531 * may be used to endorse or promote products derived from this software
532 * without specific prior written permission.
534 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
535 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
536 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
537 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
538 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
539 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
540 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
541 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
542 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
543 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF