1 /* vi: set sw=4 ts=4: */
3 * $Id: ping.c,v 1.14 2000/04/25 23:24:55 erik 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>
54 #define MAXPACKET 65468
55 #define MAX_DUP_CHK (8 * 128)
57 #define PINGINTERVAL 1 /* second */
59 #define O_QUIET (1 << 0)
61 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
62 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
63 #define SET(bit) (A(bit) |= B(bit))
64 #define CLR(bit) (A(bit) &= (~B(bit)))
65 #define TST(bit) (A(bit) & B(bit))
68 static int in_cksum(unsigned short *buf, int sz)
72 unsigned short *w = buf;
73 unsigned short ans = 0;
81 *(unsigned char *) (&ans) = *(unsigned char *) w;
85 sum = (sum >> 16) + (sum & 0xFFFF);
93 static const char *ping_usage = "ping host\n\n";
95 static char *hostname = NULL;
97 static void noresp(int ign)
99 printf("No response from %s\n", hostname);
103 static int ping(const char *host)
106 struct sockaddr_in pingaddr;
109 char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
111 if ((pingsock = socket(AF_INET, SOCK_RAW, 1)) < 0) { /* 1 == ICMP */
116 /* drop root privs if running setuid */
119 memset(&pingaddr, 0, sizeof(struct sockaddr_in));
121 pingaddr.sin_family = AF_INET;
122 if (!(h = gethostbyname(host))) {
123 fprintf(stderr, "ping: unknown host %s\n", host);
126 memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
127 hostname = h->h_name;
129 pkt = (struct icmp *) packet;
130 memset(pkt, 0, sizeof(packet));
131 pkt->icmp_type = ICMP_ECHO;
132 pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
134 c = sendto(pingsock, packet, sizeof(packet), 0,
135 (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
137 if (c < 0 || c != sizeof(packet)) {
140 fprintf(stderr, "ping: write incomplete\n");
144 signal(SIGALRM, noresp);
145 alarm(5); /* give the host 5000ms to respond */
146 /* listen for replies */
148 struct sockaddr_in from;
149 size_t fromlen = sizeof(from);
151 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
152 (struct sockaddr *) &from, &fromlen)) < 0) {
158 if (c >= 76) { /* ip + icmp */
159 struct iphdr *iphdr = (struct iphdr *) packet;
161 pkt = (struct icmp *) (packet + (iphdr->ihl << 2)); /* skip ip hdr */
162 if (pkt->icmp_type == ICMP_ECHOREPLY)
166 printf("%s is alive!\n", hostname);
170 extern int ping_main(int argc, char **argv)
181 /* full(er) version */
182 static const char *ping_usage = "ping [OPTION]... host\n\n"
183 "Send ICMP ECHO_REQUEST packets to network hosts.\n\n"
185 "\t-c COUNT\tSend only COUNT pings.\n"
186 "\t-q\t\tQuiet mode, only displays output at start\n"
187 "\t\t\tand when finished.\n";
189 static char *hostname = NULL;
190 static struct sockaddr_in pingaddr;
191 static int pingsock = -1;
193 static long ntransmitted = 0, nreceived = 0, nrepeats = 0, pingcount = 0;
194 static int myid = 0, options = 0;
195 static unsigned long tmin = ULONG_MAX, tmax = 0, tsum = 0;
196 static char rcvd_tbl[MAX_DUP_CHK / 8];
198 static void sendping(int);
199 static void pingstats(int);
200 static void unpack(char *, int, struct sockaddr_in *);
202 static void ping(char *);
204 /**************************************************************************/
206 static void pingstats(int ign)
208 signal(SIGINT, SIG_IGN);
210 printf("\n--- %s ping statistics ---\n", hostname);
211 printf("%ld packets transmitted, ", ntransmitted);
212 printf("%ld packets received, ", nreceived);
214 printf("%ld duplicates, ", nrepeats);
216 printf("%ld%% packet loss\n",
217 (ntransmitted - nreceived) * 100 / ntransmitted);
219 printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n",
220 tmin / 10, tmin % 10,
221 (tsum / (nreceived + nrepeats)) / 10,
222 (tsum / (nreceived + nrepeats)) % 10, tmax / 10, tmax % 10);
226 static void sendping(int ign)
230 char packet[DEFDATALEN + 8];
232 pkt = (struct icmp *) packet;
234 pkt->icmp_type = ICMP_ECHO;
237 pkt->icmp_seq = ntransmitted++;
239 CLR(pkt->icmp_seq % MAX_DUP_CHK);
241 gettimeofday((struct timeval *) &packet[8], NULL);
242 pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
244 i = sendto(pingsock, packet, sizeof(packet), 0,
245 (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
247 if (i < 0 || i != sizeof(packet)) {
250 fprintf(stderr, "ping wrote %d chars; %d expected\n", i,
251 (int)sizeof(packet));
255 signal(SIGALRM, sendping);
256 if (pingcount == 0 || ntransmitted < pingcount) { /* schedule next in 1s */
258 } else { /* done, wait for the last ping to come back */
259 /* todo, don't necessarily need to wait so long... */
260 signal(SIGALRM, pingstats);
265 static char *icmp_type_name (int id)
268 case ICMP_ECHOREPLY: return "Echo Reply";
269 case ICMP_DEST_UNREACH: return "Destination Unreachable";
270 case ICMP_SOURCE_QUENCH: return "Source Quench";
271 case ICMP_REDIRECT: return "Redirect (change route)";
272 case ICMP_ECHO: return "Echo Request";
273 case ICMP_TIME_EXCEEDED: return "Time Exceeded";
274 case ICMP_PARAMETERPROB: return "Parameter Problem";
275 case ICMP_TIMESTAMP: return "Timestamp Request";
276 case ICMP_TIMESTAMPREPLY: return "Timestamp Reply";
277 case ICMP_INFO_REQUEST: return "Information Request";
278 case ICMP_INFO_REPLY: return "Information Reply";
279 case ICMP_ADDRESS: return "Address Mask Request";
280 case ICMP_ADDRESSREPLY: return "Address Mask Reply";
281 default: return "unknown ICMP type";
285 static void unpack(char *buf, int sz, struct sockaddr_in *from)
287 struct icmp *icmppkt;
289 struct timeval tv, *tp;
291 unsigned long triptime;
293 gettimeofday(&tv, NULL);
295 /* check IP header */
296 iphdr = (struct iphdr *) buf;
297 hlen = iphdr->ihl << 2;
298 /* discard if too short */
299 if (sz < (DEFDATALEN + ICMP_MINLEN))
303 icmppkt = (struct icmp *) (buf + hlen);
305 if (icmppkt->icmp_id != myid)
306 return; /* not our ping */
308 if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
310 tp = (struct timeval *) icmppkt->icmp_data;
312 if ((tv.tv_usec -= tp->tv_usec) < 0) {
314 tv.tv_usec += 1000000;
316 tv.tv_sec -= tp->tv_sec;
318 triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
325 if (TST(icmppkt->icmp_seq % MAX_DUP_CHK)) {
330 SET(icmppkt->icmp_seq % MAX_DUP_CHK);
334 if (options & O_QUIET)
337 printf("%d bytes from %s: icmp_seq=%u", sz,
338 inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
340 printf(" ttl=%d", iphdr->ttl);
341 printf(" time=%lu.%lu ms", triptime / 10, triptime % 10);
346 if (icmppkt->icmp_type != ICMP_ECHO)
348 "Warning: Got ICMP %d (%s)\n",
349 icmppkt->icmp_type, icmp_type_name (icmppkt->icmp_type));
352 static void ping(char *host)
354 struct protoent *proto;
356 char buf[MAXHOSTNAMELEN];
357 char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
360 proto = getprotobyname("icmp");
361 /* if getprotobyname failed, just silently force
362 * proto->p_proto to have the correct value for "icmp" */
363 if ((pingsock = socket(AF_INET, SOCK_RAW,
364 (proto ? proto->p_proto : 1))) < 0) { /* 1 == ICMP */
365 if (errno == EPERM) {
366 fprintf(stderr, "ping: permission denied. (are you root?)\n");
373 /* drop root privs if running setuid */
376 memset(&pingaddr, 0, sizeof(struct sockaddr_in));
378 pingaddr.sin_family = AF_INET;
379 if (!(h = gethostbyname(host))) {
380 fprintf(stderr, "ping: unknown host %s\n", host);
384 if (h->h_addrtype != AF_INET) {
386 "ping: unknown address type; only AF_INET is currently supported.\n");
390 pingaddr.sin_family = AF_INET; /* h->h_addrtype */
391 memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
392 strncpy(buf, h->h_name, sizeof(buf) - 1);
395 /* enable broadcast pings */
397 setsockopt(pingsock, SOL_SOCKET, SO_BROADCAST, (char *) &sockopt,
400 /* set recv buf for broadcast pings */
402 setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, (char *) &sockopt,
405 printf("PING %s (%s): %d data bytes\n",
407 inet_ntoa(*(struct in_addr *) &pingaddr.sin_addr.s_addr),
410 signal(SIGINT, pingstats);
412 /* start the ping's going ... */
415 /* listen for replies */
417 struct sockaddr_in from;
418 socklen_t fromlen = (socklen_t) sizeof(from);
421 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
422 (struct sockaddr *) &from, &fromlen)) < 0) {
428 unpack(packet, c, &from);
429 if (pingcount > 0 && nreceived >= pingcount)
435 extern int ping_main(int argc, char **argv)
442 /* Parse any options */
443 while (argc >= 1 && **argv == '-') {
453 pingcount = atoi(*argv);
464 myid = getpid() & 0xFFFF;
471 * Copyright (c) 1989 The Regents of the University of California.
472 * All rights reserved.
474 * This code is derived from software contributed to Berkeley by
477 * Redistribution and use in source and binary forms, with or without
478 * modification, are permitted provided that the following conditions
480 * 1. Redistributions of source code must retain the above copyright
481 * notice, this list of conditions and the following disclaimer.
482 * 2. Redistributions in binary form must reproduce the above copyright
483 * notice, this list of conditions and the following disclaimer in the
484 * documentation and/or other materials provided with the distribution.
485 * 3. All advertising materials mentioning features or use of this software
486 * must display the following acknowledgement:
487 * This product includes software developed by the University of
488 * California, Berkeley and its contributors.
489 * 4. Neither the name of the University nor the names of its contributors
490 * may be used to endorse or promote products derived from this software
491 * without specific prior written permission.
493 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
494 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
495 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
496 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
497 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
498 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
499 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
500 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
501 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
502 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF