2 * $Id: ping.c,v 1.6 1999/12/11 08:41:28 andersen Exp $
3 * Mini ping implementation for busybox
5 * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 * This version of ping is adapted from the ping in netkit-base 0.10,
24 * Copyright (c) 1989 The Regents of the University of California.
25 * All rights reserved.
27 * This code is derived from software contributed to Berkeley by
30 * 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>
53 #define MAXPACKET 65468
54 #define MAX_DUP_CHK (8 * 128)
56 #define PINGINTERVAL 1 /* second */
58 #define O_QUIET (1 << 0)
60 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
61 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
62 #define SET(bit) (A(bit) |= B(bit))
63 #define CLR(bit) (A(bit) &= (~B(bit)))
64 #define TST(bit) (A(bit) & B(bit))
67 static int in_cksum(unsigned short *buf, int sz)
71 unsigned short *w = buf;
72 unsigned short ans = 0;
80 *(unsigned char *)(&ans) = *(unsigned char *)w;
84 sum = (sum >> 16) + (sum & 0xFFFF);
92 static const char* ping_usage = "ping host\n\n";
94 static char* hostname = NULL;
96 static void noresp(int ign)
98 printf("No response from %s\n", hostname);
102 static int ping(const char *host)
105 struct sockaddr_in pingaddr;
108 char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
110 if ((pingsock = socket(AF_INET, SOCK_RAW, 1)) < 0) { /* 1 == ICMP */
115 /* drop root privs if running setuid */
118 memset(&pingaddr, 0, sizeof(struct sockaddr_in));
119 pingaddr.sin_family = AF_INET;
120 if (!(h = gethostbyname(host))) {
121 fprintf(stderr, "ping: unknown host %s\n", host);
124 memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
125 hostname = h->h_name;
127 pkt = (struct icmp *)packet;
128 memset(pkt, 0, sizeof(packet));
129 pkt->icmp_type = ICMP_ECHO;
130 pkt->icmp_cksum = in_cksum((unsigned short *)pkt, sizeof(packet));
132 c = sendto(pingsock, packet, sizeof(packet), 0,
133 (struct sockaddr *)&pingaddr, sizeof(struct sockaddr_in));
135 if (c < 0 || c != sizeof(packet)) {
136 if (c < 0) perror("ping");
137 fprintf(stderr, "ping: write incomplete\n");
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) {
150 if (errno == EINTR) continue;
154 if (c >= 76) { /* ip + icmp */
155 struct iphdr *iphdr = (struct iphdr *)packet;
156 pkt = (struct icmp *)(packet + (iphdr->ihl << 2)); /* skip ip hdr */
157 if (pkt->icmp_type == ICMP_ECHOREPLY) break;
160 printf("%s is alive!\n", hostname);
164 extern int ping_main(int argc, char **argv)
168 if (argc < 1) usage(ping_usage);
174 /* full(er) version */
175 static const char* ping_usage = "ping [OPTION]... host\n\n"
176 "Send ICMP ECHO_REQUEST packets to network hosts.\n\n"
178 "\t-q\t\tQuiet mode, only displays output at start and when finished.\n"
179 "\t-c COUNT\tSend only COUNT pings.\n";
181 static char *hostname = NULL;
182 static struct sockaddr_in pingaddr;
183 static int pingsock = -1;
185 static long ntransmitted = 0, nreceived = 0, nrepeats = 0, pingcount = 0;
186 static int myid = 0, options = 0;
187 static unsigned long tmin = ULONG_MAX, tmax = 0, tsum = 0;
188 static char rcvd_tbl[MAX_DUP_CHK / 8];
190 static void sendping(int);
191 static void pingstats(int);
192 static void unpack(char *, int, struct sockaddr_in *);
194 static void ping(char *);
196 /**************************************************************************/
198 static void pingstats(int ign) {
199 signal(SIGINT, SIG_IGN);
201 printf("\n--- %s ping statistics ---\n", hostname);
202 printf("%ld packets transmitted, ", ntransmitted);
203 printf("%ld packets received, ", nreceived);
205 printf("%ld duplicates, ", nrepeats);
207 printf("%ld%% packet loss\n",
208 (ntransmitted - nreceived)*100/ntransmitted);
210 printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n",
212 (tsum/(nreceived+nrepeats))/10,
213 (tsum/(nreceived+nrepeats))%10,
218 static void sendping(int ign)
222 char packet[DEFDATALEN + 8];
224 pkt = (struct icmp *)packet;
226 pkt->icmp_type = ICMP_ECHO;
229 pkt->icmp_seq = ntransmitted++;
231 CLR(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));
239 if (i < 0 || i != sizeof(packet)) {
240 if (i < 0) perror("ping");
241 fprintf(stderr, "ping wrote %d chars; %d expected\n", i, 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 void unpack(char *buf, int sz, struct sockaddr_in *from)
257 struct icmp *icmppkt;
259 struct timeval tv, *tp;
261 unsigned long triptime;
263 gettimeofday(&tv, NULL);
265 /* check IP header */
266 iphdr = (struct iphdr *)buf;
267 hlen = iphdr->ihl << 2;
268 /* discard if too short */
269 if (sz < (DEFDATALEN + ICMP_MINLEN)) return;
272 icmppkt = (struct icmp *)(buf + hlen);
274 if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
275 if (icmppkt->icmp_id != myid) return; /* not our ping */
277 tp = (struct timeval *)icmppkt->icmp_data;
279 if ((tv.tv_usec -= tp->tv_usec) < 0) {
281 tv.tv_usec += 1000000;
283 tv.tv_sec -= tp->tv_sec;
285 triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
287 if (triptime < tmin) tmin = triptime;
288 if (triptime > tmax) tmax = triptime;
290 if (TST(icmppkt->icmp_seq % MAX_DUP_CHK)) {
295 SET(icmppkt->icmp_seq % MAX_DUP_CHK);
299 if (options & O_QUIET) return;
301 printf("%d bytes from %s: icmp_seq=%u", sz,
302 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
304 printf(" ttl=%d", iphdr->ttl);
305 printf(" time=%lu.%lu ms", triptime/10, triptime%10);
306 if (dupflag) printf(" (DUP!)");
309 fprintf(stderr, "Warning: unknown ICMP packet received (not echo-reply)\n");
313 static void ping(char *host)
315 struct protoent *proto;
317 char buf[MAXHOSTNAMELEN];
318 char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
321 if (!(proto = getprotobyname("icmp"))) {
322 fprintf(stderr, "ping: unknown protocol icmp\n");
325 if ((pingsock = socket(AF_INET, SOCK_RAW, proto->p_proto)) < 0) {
326 if (errno == EPERM) {
327 fprintf(stderr, "ping: permission denied. (are you root?)\n");
334 /* drop root privs if running setuid */
337 memset(&pingaddr, 0, sizeof(struct sockaddr_in));
338 pingaddr.sin_family = AF_INET;
339 if (!(h = gethostbyname(host))) {
340 fprintf(stderr, "ping: unknown host %s\n", host);
344 if (h->h_addrtype != AF_INET) {
345 fprintf(stderr, "ping: unknown address type; only AF_INET is currently supported.\n");
349 pingaddr.sin_family = AF_INET; /* h->h_addrtype */
350 memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
351 strncpy(buf, h->h_name, sizeof(buf)-1);
354 /* enable broadcast pings */
356 setsockopt(pingsock, SOL_SOCKET, SO_BROADCAST, (char *)&sockopt, sizeof(sockopt));
358 /* set recv buf for broadcast pings */
360 setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, (char *)&sockopt, sizeof(sockopt));
362 printf("PING %s (%s): %d data bytes\n",
363 hostname, inet_ntoa(*(struct in_addr *)&pingaddr.sin_addr.s_addr),
366 signal(SIGINT, pingstats);
368 /* start the ping's going ... */
371 /* listen for replies */
373 struct sockaddr_in from;
374 size_t fromlen = sizeof(from);
377 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
378 (struct sockaddr *)&from, &fromlen)) < 0) {
379 if (errno == EINTR) continue;
383 unpack(packet, c, &from);
384 if (pingcount > 0 && nreceived >= pingcount) break;
389 extern int ping_main(int argc, char **argv)
396 /* Parse any options */
398 if (**argv != '-') usage(ping_usage);
399 thisarg = *argv; thisarg++;
401 case 'q': options |= O_QUIET; break;
404 pingcount = atoi(*argv);
411 if (argc < 1) usage(ping_usage);
413 myid = getpid() & 0xFFFF;
420 * Copyright (c) 1989 The Regents of the University of California.
421 * All rights reserved.
423 * This code is derived from software contributed to Berkeley by
426 * Redistribution and use in source and binary forms, with or without
427 * modification, are permitted provided that the following conditions
429 * 1. Redistributions of source code must retain the above copyright
430 * notice, this list of conditions and the following disclaimer.
431 * 2. Redistributions in binary form must reproduce the above copyright
432 * notice, this list of conditions and the following disclaimer in the
433 * documentation and/or other materials provided with the distribution.
434 * 3. All advertising materials mentioning features or use of this software
435 * must display the following acknowledgement:
436 * This product includes software developed by the University of
437 * California, Berkeley and its contributors.
438 * 4. Neither the name of the University nor the names of its contributors
439 * may be used to endorse or promote products derived from this software
440 * without specific prior written permission.
442 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
443 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
444 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
445 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
446 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
447 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
448 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
449 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
450 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
451 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF