This commit was generated by cvs2svn to track changes on a CVS vendor
[unix-history] / sbin / ping / ping.c
CommitLineData
15637ed4
RG
1/*
2 * Copyright (c) 1989 The Regents of the University of California.
3 * All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Mike Muuss.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37#ifndef lint
38char copyright[] =
39"@(#) Copyright (c) 1989 The Regents of the University of California.\n\
40 All rights reserved.\n";
41#endif /* not lint */
42
43#ifndef lint
44static char sccsid[] = "@(#)ping.c 5.9 (Berkeley) 5/12/91";
45#endif /* not lint */
46
47/*
48 * P I N G . C
49 *
50 * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
51 * measure round-trip-delays and packet loss across network paths.
52 *
53 * Author -
54 * Mike Muuss
55 * U. S. Army Ballistic Research Laboratory
56 * December, 1983
57 *
58 * Status -
59 * Public Domain. Distribution Unlimited.
60 * Bugs -
61 * More statistics could always be gathered.
62 * This program has to run SUID to ROOT to access the ICMP socket.
63 */
64
65#include <sys/param.h>
66#include <sys/socket.h>
67#include <sys/file.h>
68#include <sys/time.h>
69#include <sys/signal.h>
70
71#include <netinet/in_systm.h>
72#include <netinet/in.h>
73#include <netinet/ip.h>
74#include <netinet/ip_icmp.h>
75#include <netinet/ip_var.h>
76#include <netdb.h>
77#include <unistd.h>
78#include <stdio.h>
79#include <ctype.h>
80#include <errno.h>
81#include <string.h>
82
83#define DEFDATALEN (64 - 8) /* default data length */
84#define MAXIPLEN 60
85#define MAXICMPLEN 76
86#define MAXPACKET (65536 - 60 - 8)/* max packet size */
87#define MAXWAIT 10 /* max seconds to wait for response */
88#define NROUTES 9 /* number of record route slots */
89
90#define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
91#define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
92#define SET(bit) (A(bit) |= B(bit))
93#define CLR(bit) (A(bit) &= (~B(bit)))
94#define TST(bit) (A(bit) & B(bit))
95
96/* various options */
97int options;
98#define F_FLOOD 0x001
99#define F_INTERVAL 0x002
100#define F_NUMERIC 0x004
101#define F_PINGFILLED 0x008
102#define F_QUIET 0x010
103#define F_RROUTE 0x020
104#define F_SO_DEBUG 0x040
105#define F_SO_DONTROUTE 0x080
106#define F_VERBOSE 0x100
107
7b7f9fac
JH
108/* multicast options */
109int moptions;
110#define MULTICAST_NOLOOP 0x001
111#define MULTICAST_TTL 0x002
112#define MULTICAST_IF 0x004
113
15637ed4
RG
114/*
115 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
116 * number of received sequence numbers we can keep track of. Change 128
117 * to 8192 for complete accuracy...
118 */
119#define MAX_DUP_CHK (8 * 128)
120int mx_dup_ck = MAX_DUP_CHK;
121char rcvd_tbl[MAX_DUP_CHK / 8];
122
123struct sockaddr whereto; /* who to ping */
124int datalen = DEFDATALEN;
125int s; /* socket file descriptor */
126u_char outpack[MAXPACKET];
127char BSPACE = '\b'; /* characters written for flood */
128char DOT = '.';
129char *hostname;
130int ident; /* process id to identify our packets */
131
132/* counters */
133long npackets; /* max packets to transmit */
134long nreceived; /* # of packets we got back */
135long nrepeats; /* number of duplicates */
136long ntransmitted; /* sequence # for outbound packets = #sent */
137int interval = 1; /* interval between packets */
138
139/* timing */
140int timing; /* flag to do timing */
4d81973d
DG
141double tmin = 1000.0*(double)LONG_MAX; /* minimum round trip time */
142double tmax; /* maximum round trip time */
143double tsum; /* sum of all times, for doing average */
15637ed4
RG
144
145char *pr_addr();
146void catcher(), finish();
147
148main(argc, argv)
149 int argc;
150 char **argv;
151{
152 extern int errno, optind;
153 extern char *optarg;
154 struct timeval timeout;
155 struct hostent *hp;
156 struct sockaddr_in *to;
157 struct protoent *proto;
7b7f9fac
JH
158 struct in_addr ifaddr;
159 int i;
15637ed4
RG
160 int ch, fdmask, hold, packlen, preload;
161 u_char *datap, *packet;
162 char *target, hnamebuf[MAXHOSTNAMELEN], *malloc();
7b7f9fac 163 u_char ttl, loop;
15637ed4
RG
164#ifdef IP_OPTIONS
165 char rspace[3 + 4 * NROUTES + 1]; /* record route space */
166#endif
167
168 preload = 0;
169 datap = &outpack[8 + sizeof(struct timeval)];
7b7f9fac 170 while ((ch = getopt(argc, argv, "I:LRc:dfh:i:l:np:qrs:t:v")) != EOF)
15637ed4
RG
171 switch(ch) {
172 case 'c':
173 npackets = atoi(optarg);
174 if (npackets <= 0) {
175 (void)fprintf(stderr,
176 "ping: bad number of packets to transmit.\n");
177 exit(1);
178 }
179 break;
180 case 'd':
181 options |= F_SO_DEBUG;
182 break;
183 case 'f':
184 if (getuid()) {
185 (void)fprintf(stderr,
186 "ping: %s\n", strerror(EPERM));
187 exit(1);
188 }
189 options |= F_FLOOD;
190 setbuf(stdout, (char *)NULL);
191 break;
192 case 'i': /* wait between sending packets */
193 interval = atoi(optarg);
194 if (interval <= 0) {
195 (void)fprintf(stderr,
196 "ping: bad timing interval.\n");
197 exit(1);
198 }
199 options |= F_INTERVAL;
200 break;
201 case 'l':
202 preload = atoi(optarg);
203 if (preload < 0) {
204 (void)fprintf(stderr,
205 "ping: bad preload value.\n");
206 exit(1);
207 }
208 break;
209 case 'n':
210 options |= F_NUMERIC;
211 break;
212 case 'p': /* fill buffer with user pattern */
213 options |= F_PINGFILLED;
214 fill((char *)datap, optarg);
215 break;
216 case 'q':
217 options |= F_QUIET;
218 break;
219 case 'R':
220 options |= F_RROUTE;
221 break;
222 case 'r':
223 options |= F_SO_DONTROUTE;
224 break;
225 case 's': /* size of packet to send */
226 datalen = atoi(optarg);
227 if (datalen > MAXPACKET) {
228 (void)fprintf(stderr,
229 "ping: packet size too large.\n");
230 exit(1);
231 }
232 if (datalen <= 0) {
233 (void)fprintf(stderr,
234 "ping: illegal packet size.\n");
235 exit(1);
236 }
237 break;
238 case 'v':
239 options |= F_VERBOSE;
240 break;
7b7f9fac
JH
241 case 'L':
242 moptions |= MULTICAST_NOLOOP;
243 loop = 0;
244 break;
245 case 't':
246 moptions |= MULTICAST_TTL;
247 i = atoi(optarg);
248 if (i < 0 || i > 255) {
249 printf("ttl %u out of range\n", i);
250 exit(1);
251 }
252 ttl = i;
253 break;
254 case 'I':
255 moptions |= MULTICAST_IF;
256 {
257 int i1, i2, i3, i4;
258
259 if (sscanf(optarg, "%u.%u.%u.%u%c",
260 &i1, &i2, &i3, &i4, &i) != 4) {
261 printf("bad interface address '%s'\n",
262 optarg);
263 exit(1);
264 }
265 ifaddr.s_addr = (i1<<24)|(i2<<16)|(i3<<8)|i4;
266 ifaddr.s_addr = htonl(ifaddr.s_addr);
267 }
268 break;
15637ed4
RG
269 default:
270 usage();
271 }
272 argc -= optind;
273 argv += optind;
7b7f9fac 274
15637ed4
RG
275 if (argc != 1)
276 usage();
277 target = *argv;
278
279 bzero((char *)&whereto, sizeof(struct sockaddr));
280 to = (struct sockaddr_in *)&whereto;
281 to->sin_family = AF_INET;
282 to->sin_addr.s_addr = inet_addr(target);
283 if (to->sin_addr.s_addr != (u_int)-1)
284 hostname = target;
285 else {
286 hp = gethostbyname(target);
287 if (!hp) {
288 (void)fprintf(stderr,
289 "ping: unknown host %s\n", target);
290 exit(1);
291 }
292 to->sin_family = hp->h_addrtype;
293 bcopy(hp->h_addr, (caddr_t)&to->sin_addr, hp->h_length);
294 (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
295 hostname = hnamebuf;
296 }
297
298 if (options & F_FLOOD && options & F_INTERVAL) {
299 (void)fprintf(stderr,
300 "ping: -f and -i incompatible options.\n");
301 exit(1);
302 }
303
304 if (datalen >= sizeof(struct timeval)) /* can we time transfer */
305 timing = 1;
306 packlen = datalen + MAXIPLEN + MAXICMPLEN;
307 if (!(packet = (u_char *)malloc((u_int)packlen))) {
308 (void)fprintf(stderr, "ping: out of memory.\n");
309 exit(1);
310 }
311 if (!(options & F_PINGFILLED))
312 for (i = 8; i < datalen; ++i)
313 *datap++ = i;
314
315 ident = getpid() & 0xFFFF;
316
317 if (!(proto = getprotobyname("icmp"))) {
318 (void)fprintf(stderr, "ping: unknown protocol icmp.\n");
319 exit(1);
320 }
321 if ((s = socket(AF_INET, SOCK_RAW, proto->p_proto)) < 0) {
322 perror("ping: socket");
323 exit(1);
324 }
325 hold = 1;
326 if (options & F_SO_DEBUG)
327 (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
328 sizeof(hold));
329 if (options & F_SO_DONTROUTE)
330 (void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
331 sizeof(hold));
332
333 /* record route option */
334 if (options & F_RROUTE) {
335#ifdef IP_OPTIONS
336 rspace[IPOPT_OPTVAL] = IPOPT_RR;
337 rspace[IPOPT_OLEN] = sizeof(rspace)-1;
338 rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
339 if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
340 sizeof(rspace)) < 0) {
341 perror("ping: record route");
342 exit(1);
343 }
344#else
345 (void)fprintf(stderr,
346 "ping: record route not available in this implementation.\n");
347 exit(1);
348#endif /* IP_OPTIONS */
349 }
350
351 /*
352 * When pinging the broadcast address, you can get a lot of answers.
353 * Doing something so evil is useful if you are trying to stress the
354 * ethernet, or just want to fill the arp cache to get some stuff for
355 * /etc/ethers.
356 */
357 hold = 48 * 1024;
358 (void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
359 sizeof(hold));
360
7b7f9fac
JH
361 if (moptions & MULTICAST_NOLOOP) {
362 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP,
363 &loop, 1) == -1) {
364 perror ("can't disable multicast loopback");
365 exit(92);
366 }
367 }
368 if (moptions & MULTICAST_TTL) {
369 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
370 &ttl, 1) == -1) {
371 perror ("can't set multicast time-to-live");
372 exit(93);
373 }
374 }
375 if (moptions & MULTICAST_IF) {
376 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF,
377 &ifaddr, sizeof(ifaddr)) == -1) {
378 perror ("can't set multicast source interface");
379 exit(94);
380 }
381 }
382
15637ed4
RG
383 if (to->sin_family == AF_INET)
384 (void)printf("PING %s (%s): %d data bytes\n", hostname,
385 inet_ntoa(*(struct in_addr *)&to->sin_addr.s_addr),
386 datalen);
387 else
388 (void)printf("PING %s: %d data bytes\n", hostname, datalen);
389
390 (void)signal(SIGINT, finish);
391 (void)signal(SIGALRM, catcher);
392
393 while (preload--) /* fire off them quickies */
394 pinger();
395
396 if ((options & F_FLOOD) == 0)
397 catcher(); /* start things going */
398
399 for (;;) {
400 struct sockaddr_in from;
401 register int cc;
402 int fromlen;
403
404 if (options & F_FLOOD) {
405 pinger();
406 timeout.tv_sec = 0;
407 timeout.tv_usec = 10000;
408 fdmask = 1 << s;
409 if (select(s + 1, (fd_set *)&fdmask, (fd_set *)NULL,
410 (fd_set *)NULL, &timeout) < 1)
411 continue;
412 }
413 fromlen = sizeof(from);
414 if ((cc = recvfrom(s, (char *)packet, packlen, 0,
415 (struct sockaddr *)&from, &fromlen)) < 0) {
416 if (errno == EINTR)
417 continue;
418 perror("ping: recvfrom");
419 continue;
420 }
421 pr_pack((char *)packet, cc, &from);
422 if (npackets && nreceived >= npackets)
423 break;
424 }
425 finish();
426 /* NOTREACHED */
427}
428
429/*
430 * catcher --
431 * This routine causes another PING to be transmitted, and then
432 * schedules another SIGALRM for 1 second from now.
433 *
434 * bug --
435 * Our sense of time will slowly skew (i.e., packets will not be
436 * launched exactly at 1-second intervals). This does not affect the
437 * quality of the delay and loss statistics.
438 */
439void
440catcher()
441{
442 int waittime;
443
444 pinger();
445 (void)signal(SIGALRM, catcher);
446 if (!npackets || ntransmitted < npackets)
447 alarm((u_int)interval);
448 else {
449 if (nreceived) {
4d81973d 450 waittime = 2 * tmax / 1000000.0;
15637ed4
RG
451 if (!waittime)
452 waittime = 1;
453 } else
454 waittime = MAXWAIT;
455 (void)signal(SIGALRM, finish);
456 (void)alarm((u_int)waittime);
457 }
458}
459
460/*
461 * pinger --
462 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
463 * will be added on by the kernel. The ID field is our UNIX process ID,
464 * and the sequence number is an ascending integer. The first 8 bytes
465 * of the data portion are used to hold a UNIX "timeval" struct in VAX
466 * byte-order, to compute the round-trip time.
467 */
468pinger()
469{
470 register struct icmp *icp;
471 register int cc;
472 int i;
473
474 icp = (struct icmp *)outpack;
475 icp->icmp_type = ICMP_ECHO;
476 icp->icmp_code = 0;
477 icp->icmp_cksum = 0;
478 icp->icmp_seq = ntransmitted++;
479 icp->icmp_id = ident; /* ID */
480
481 CLR(icp->icmp_seq % mx_dup_ck);
482
483 if (timing)
484 (void)gettimeofday((struct timeval *)&outpack[8],
485 (struct timezone *)NULL);
486
487 cc = datalen + 8; /* skips ICMP portion */
488
489 /* compute ICMP checksum here */
490 icp->icmp_cksum = in_cksum((u_short *)icp, cc);
491
492 i = sendto(s, (char *)outpack, cc, 0, &whereto,
493 sizeof(struct sockaddr));
494
495 if (i < 0 || i != cc) {
496 if (i < 0)
497 perror("ping: sendto");
498 (void)printf("ping: wrote %s %d chars, ret=%d\n",
499 hostname, cc, i);
500 }
501 if (!(options & F_QUIET) && options & F_FLOOD)
502 (void)write(STDOUT_FILENO, &DOT, 1);
503}
504
505/*
506 * pr_pack --
507 * Print out the packet, if it came from us. This logic is necessary
508 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
509 * which arrive ('tis only fair). This permits multiple copies of this
510 * program to be run without having intermingled output (or statistics!).
511 */
512pr_pack(buf, cc, from)
513 char *buf;
514 int cc;
515 struct sockaddr_in *from;
516{
517 register struct icmp *icp;
518 register u_long l;
519 register int i, j;
520 register u_char *cp,*dp;
521 static int old_rrlen;
522 static char old_rr[MAX_IPOPTLEN];
523 struct ip *ip;
524 struct timeval tv, *tp;
4d81973d 525 double triptime;
15637ed4
RG
526 int hlen, dupflag;
527
528 (void)gettimeofday(&tv, (struct timezone *)NULL);
529
530 /* Check the IP header */
531 ip = (struct ip *)buf;
532 hlen = ip->ip_hl << 2;
533 if (cc < hlen + ICMP_MINLEN) {
534 if (options & F_VERBOSE)
535 (void)fprintf(stderr,
536 "ping: packet too short (%d bytes) from %s\n", cc,
537 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr));
538 return;
539 }
540
541 /* Now the ICMP part */
542 cc -= hlen;
543 icp = (struct icmp *)(buf + hlen);
544 if (icp->icmp_type == ICMP_ECHOREPLY) {
545 if (icp->icmp_id != ident)
546 return; /* 'Twas not our ECHO */
547 ++nreceived;
548 if (timing) {
549#ifndef icmp_data
550 tp = (struct timeval *)&icp->icmp_ip;
551#else
552 tp = (struct timeval *)icp->icmp_data;
553#endif
554 tvsub(&tv, tp);
4d81973d 555 triptime = (double) (tv.tv_sec * 1000000 + tv.tv_usec);
15637ed4
RG
556 tsum += triptime;
557 if (triptime < tmin)
558 tmin = triptime;
559 if (triptime > tmax)
560 tmax = triptime;
561 }
562
563 if (TST(icp->icmp_seq % mx_dup_ck)) {
564 ++nrepeats;
565 --nreceived;
566 dupflag = 1;
567 } else {
568 SET(icp->icmp_seq % mx_dup_ck);
569 dupflag = 0;
570 }
571
572 if (options & F_QUIET)
573 return;
574
575 if (options & F_FLOOD)
576 (void)write(STDOUT_FILENO, &BSPACE, 1);
577 else {
578 (void)printf("%d bytes from %s: icmp_seq=%u", cc,
579 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
580 icp->icmp_seq);
581 (void)printf(" ttl=%d", ip->ip_ttl);
582 if (timing)
4d81973d 583 (void)printf(" time=%.3f ms", triptime/1000.0);
15637ed4
RG
584 if (dupflag)
585 (void)printf(" (DUP!)");
586 /* check the data */
587 cp = (u_char*)&icp->icmp_data[8];
588 dp = &outpack[8 + sizeof(struct timeval)];
589 for (i = 8; i < datalen; ++i, ++cp, ++dp) {
590 if (*cp != *dp) {
591 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
592 i, *dp, *cp);
593 cp = (u_char*)&icp->icmp_data[0];
594 for (i = 8; i < datalen; ++i, ++cp) {
595 if ((i % 32) == 8)
596 (void)printf("\n\t");
597 (void)printf("%x ", *cp);
598 }
599 break;
600 }
601 }
602 }
603 } else {
604 /* We've got something other than an ECHOREPLY */
605 if (!(options & F_VERBOSE))
606 return;
607 (void)printf("%d bytes from %s: ", cc,
608 pr_addr(from->sin_addr.s_addr));
609 pr_icmph(icp);
610 }
611
612 /* Display any IP options */
613 cp = (u_char *)buf + sizeof(struct ip);
614
615 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
616 switch (*cp) {
617 case IPOPT_EOL:
618 hlen = 0;
619 break;
620 case IPOPT_LSRR:
621 (void)printf("\nLSRR: ");
622 hlen -= 2;
623 j = *++cp;
624 ++cp;
625 if (j > IPOPT_MINOFF)
626 for (;;) {
627 l = *++cp;
628 l = (l<<8) + *++cp;
629 l = (l<<8) + *++cp;
630 l = (l<<8) + *++cp;
631 if (l == 0)
632 (void)printf("\t0.0.0.0");
633 else
634 (void)printf("\t%s", pr_addr(ntohl(l)));
635 hlen -= 4;
636 j -= 4;
637 if (j <= IPOPT_MINOFF)
638 break;
639 (void)putchar('\n');
640 }
641 break;
642 case IPOPT_RR:
643 j = *++cp; /* get length */
644 i = *++cp; /* and pointer */
645 hlen -= 2;
646 if (i > j)
647 i = j;
648 i -= IPOPT_MINOFF;
649 if (i <= 0)
650 continue;
651 if (i == old_rrlen
652 && cp == (u_char *)buf + sizeof(struct ip) + 2
653 && !bcmp((char *)cp, old_rr, i)
654 && !(options & F_FLOOD)) {
655 (void)printf("\t(same route)");
656 i = ((i + 3) / 4) * 4;
657 hlen -= i;
658 cp += i;
659 break;
660 }
661 old_rrlen = i;
662 bcopy((char *)cp, old_rr, i);
663 (void)printf("\nRR: ");
664 for (;;) {
665 l = *++cp;
666 l = (l<<8) + *++cp;
667 l = (l<<8) + *++cp;
668 l = (l<<8) + *++cp;
669 if (l == 0)
670 (void)printf("\t0.0.0.0");
671 else
672 (void)printf("\t%s", pr_addr(ntohl(l)));
673 hlen -= 4;
674 i -= 4;
675 if (i <= 0)
676 break;
677 (void)putchar('\n');
678 }
679 break;
680 case IPOPT_NOP:
681 (void)printf("\nNOP");
682 break;
683 default:
684 (void)printf("\nunknown option %x", *cp);
685 break;
686 }
687 if (!(options & F_FLOOD)) {
688 (void)putchar('\n');
689 (void)fflush(stdout);
690 }
691}
692
693/*
694 * in_cksum --
695 * Checksum routine for Internet Protocol family headers (C Version)
696 */
697in_cksum(addr, len)
698 u_short *addr;
699 int len;
700{
701 register int nleft = len;
702 register u_short *w = addr;
703 register int sum = 0;
704 u_short answer = 0;
705
706 /*
707 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
708 * sequential 16 bit words to it, and at the end, fold back all the
709 * carry bits from the top 16 bits into the lower 16 bits.
710 */
711 while (nleft > 1) {
712 sum += *w++;
713 nleft -= 2;
714 }
715
716 /* mop up an odd byte, if necessary */
717 if (nleft == 1) {
718 *(u_char *)(&answer) = *(u_char *)w ;
719 sum += answer;
720 }
721
722 /* add back carry outs from top 16 bits to low 16 bits */
723 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
724 sum += (sum >> 16); /* add carry */
725 answer = ~sum; /* truncate to 16 bits */
726 return(answer);
727}
728
729/*
730 * tvsub --
731 * Subtract 2 timeval structs: out = out - in. Out is assumed to
732 * be >= in.
733 */
734tvsub(out, in)
735 register struct timeval *out, *in;
736{
737 if ((out->tv_usec -= in->tv_usec) < 0) {
738 --out->tv_sec;
739 out->tv_usec += 1000000;
740 }
741 out->tv_sec -= in->tv_sec;
742}
743
744/*
745 * finish --
746 * Print out statistics, and give up.
747 */
748void
749finish()
750{
751 (void)signal(SIGINT, SIG_IGN);
752 (void)putchar('\n');
753 (void)fflush(stdout);
754 (void)printf("--- %s ping statistics ---\n", hostname);
755 (void)printf("%ld packets transmitted, ", ntransmitted);
756 (void)printf("%ld packets received, ", nreceived);
757 if (nrepeats)
758 (void)printf("+%ld duplicates, ", nrepeats);
759 if (ntransmitted)
760 if (nreceived > ntransmitted)
761 (void)printf("-- somebody's printing up packets!");
762 else
763 (void)printf("%d%% packet loss",
764 (int) (((ntransmitted - nreceived) * 100) /
765 ntransmitted));
766 (void)putchar('\n');
767 if (nreceived && timing)
4d81973d
DG
768 (void)printf("round-trip min/avg/max = %.3f/%.3f/%.3f ms\n",
769 tmin/1000.0, tsum/(nreceived + nrepeats)/1000.0, tmax/1000.0);
a9fb8543
NW
770
771 /*
772 * 13NOV93 GRS
773 * added code to return 1 if no packets were returned to the receiver.
774 * Originally PING returned 0 regardless of how many packets were
775 * returned, thus the only way to test the return value of PING in a
776 * shell script was to do something like:
777 *
778 * if ping -n -c 1 -r $IP_ADDR | grep '0 packets received' >/dev/null
779 *
780 * now, all that is needed is:
781 *
782 * if ping -n -c 1 -r $IP_ADDR >/dev/null
783 */
784 if (nreceived)
785 exit (0);
786 else
787 exit (1);
15637ed4
RG
788}
789
790#ifdef notdef
791static char *ttab[] = {
792 "Echo Reply", /* ip + seq + udata */
793 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */
794 "Source Quench", /* IP */
795 "Redirect", /* redirect type, gateway, + IP */
796 "Echo",
797 "Time Exceeded", /* transit, frag reassem + IP */
798 "Parameter Problem", /* pointer + IP */
799 "Timestamp", /* id + seq + three timestamps */
800 "Timestamp Reply", /* " */
801 "Info Request", /* id + sq */
802 "Info Reply" /* " */
803};
804#endif
805
806/*
807 * pr_icmph --
808 * Print a descriptive string about an ICMP header.
809 */
810pr_icmph(icp)
811 struct icmp *icp;
812{
813 switch(icp->icmp_type) {
814 case ICMP_ECHOREPLY:
815 (void)printf("Echo Reply\n");
816 /* XXX ID + Seq + Data */
817 break;
818 case ICMP_UNREACH:
819 switch(icp->icmp_code) {
820 case ICMP_UNREACH_NET:
821 (void)printf("Destination Net Unreachable\n");
822 break;
823 case ICMP_UNREACH_HOST:
824 (void)printf("Destination Host Unreachable\n");
825 break;
826 case ICMP_UNREACH_PROTOCOL:
827 (void)printf("Destination Protocol Unreachable\n");
828 break;
829 case ICMP_UNREACH_PORT:
830 (void)printf("Destination Port Unreachable\n");
831 break;
832 case ICMP_UNREACH_NEEDFRAG:
833 (void)printf("frag needed and DF set\n");
834 break;
835 case ICMP_UNREACH_SRCFAIL:
836 (void)printf("Source Route Failed\n");
837 break;
838 default:
839 (void)printf("Dest Unreachable, Bad Code: %d\n",
840 icp->icmp_code);
841 break;
842 }
843 /* Print returned IP header information */
844#ifndef icmp_data
845 pr_retip(&icp->icmp_ip);
846#else
847 pr_retip((struct ip *)icp->icmp_data);
848#endif
849 break;
850 case ICMP_SOURCEQUENCH:
851 (void)printf("Source Quench\n");
852#ifndef icmp_data
853 pr_retip(&icp->icmp_ip);
854#else
855 pr_retip((struct ip *)icp->icmp_data);
856#endif
857 break;
858 case ICMP_REDIRECT:
859 switch(icp->icmp_code) {
860 case ICMP_REDIRECT_NET:
861 (void)printf("Redirect Network");
862 break;
863 case ICMP_REDIRECT_HOST:
864 (void)printf("Redirect Host");
865 break;
866 case ICMP_REDIRECT_TOSNET:
867 (void)printf("Redirect Type of Service and Network");
868 break;
869 case ICMP_REDIRECT_TOSHOST:
870 (void)printf("Redirect Type of Service and Host");
871 break;
872 default:
873 (void)printf("Redirect, Bad Code: %d", icp->icmp_code);
874 break;
875 }
876 (void)printf("(New addr: 0x%08lx)\n", icp->icmp_gwaddr.s_addr);
877#ifndef icmp_data
878 pr_retip(&icp->icmp_ip);
879#else
880 pr_retip((struct ip *)icp->icmp_data);
881#endif
882 break;
883 case ICMP_ECHO:
884 (void)printf("Echo Request\n");
885 /* XXX ID + Seq + Data */
886 break;
887 case ICMP_TIMXCEED:
888 switch(icp->icmp_code) {
889 case ICMP_TIMXCEED_INTRANS:
890 (void)printf("Time to live exceeded\n");
891 break;
892 case ICMP_TIMXCEED_REASS:
893 (void)printf("Frag reassembly time exceeded\n");
894 break;
895 default:
896 (void)printf("Time exceeded, Bad Code: %d\n",
897 icp->icmp_code);
898 break;
899 }
900#ifndef icmp_data
901 pr_retip(&icp->icmp_ip);
902#else
903 pr_retip((struct ip *)icp->icmp_data);
904#endif
905 break;
906 case ICMP_PARAMPROB:
907 (void)printf("Parameter problem: pointer = 0x%02x\n",
908 icp->icmp_hun.ih_pptr);
909#ifndef icmp_data
910 pr_retip(&icp->icmp_ip);
911#else
912 pr_retip((struct ip *)icp->icmp_data);
913#endif
914 break;
915 case ICMP_TSTAMP:
916 (void)printf("Timestamp\n");
917 /* XXX ID + Seq + 3 timestamps */
918 break;
919 case ICMP_TSTAMPREPLY:
920 (void)printf("Timestamp Reply\n");
921 /* XXX ID + Seq + 3 timestamps */
922 break;
923 case ICMP_IREQ:
924 (void)printf("Information Request\n");
925 /* XXX ID + Seq */
926 break;
927 case ICMP_IREQREPLY:
928 (void)printf("Information Reply\n");
929 /* XXX ID + Seq */
930 break;
931#ifdef ICMP_MASKREQ
932 case ICMP_MASKREQ:
933 (void)printf("Address Mask Request\n");
934 break;
935#endif
936#ifdef ICMP_MASKREPLY
937 case ICMP_MASKREPLY:
938 (void)printf("Address Mask Reply\n");
939 break;
940#endif
941 default:
942 (void)printf("Bad ICMP type: %d\n", icp->icmp_type);
943 }
944}
945
946/*
947 * pr_iph --
948 * Print an IP header with options.
949 */
950pr_iph(ip)
951 struct ip *ip;
952{
953 int hlen;
954 u_char *cp;
955
956 hlen = ip->ip_hl << 2;
957 cp = (u_char *)ip + 20; /* point to options */
958
959 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst Data\n");
960 (void)printf(" %1x %1x %02x %04x %04x",
961 ip->ip_v, ip->ip_hl, ip->ip_tos, ip->ip_len, ip->ip_id);
962 (void)printf(" %1x %04x", ((ip->ip_off) & 0xe000) >> 13,
963 (ip->ip_off) & 0x1fff);
964 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p, ip->ip_sum);
965 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
966 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
967 /* dump and option bytes */
968 while (hlen-- > 20) {
969 (void)printf("%02x", *cp++);
970 }
971 (void)putchar('\n');
972}
973
974/*
975 * pr_addr --
976 * Return an ascii host address as a dotted quad and optionally with
977 * a hostname.
978 */
979char *
980pr_addr(l)
981 u_long l;
982{
983 struct hostent *hp;
984 static char buf[80];
985
986 if ((options & F_NUMERIC) ||
987 !(hp = gethostbyaddr((char *)&l, 4, AF_INET)))
988 (void)sprintf(buf, "%s", inet_ntoa(*(struct in_addr *)&l));
989 else
990 (void)sprintf(buf, "%s (%s)", hp->h_name,
991 inet_ntoa(*(struct in_addr *)&l));
992 return(buf);
993}
994
995/*
996 * pr_retip --
997 * Dump some info on a returned (via ICMP) IP packet.
998 */
999pr_retip(ip)
1000 struct ip *ip;
1001{
1002 int hlen;
1003 u_char *cp;
1004
1005 pr_iph(ip);
1006 hlen = ip->ip_hl << 2;
1007 cp = (u_char *)ip + hlen;
1008
1009 if (ip->ip_p == 6)
1010 (void)printf("TCP: from port %u, to port %u (decimal)\n",
1011 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1012 else if (ip->ip_p == 17)
1013 (void)printf("UDP: from port %u, to port %u (decimal)\n",
1014 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1015}
1016
1017fill(bp, patp)
1018 char *bp, *patp;
1019{
1020 register int ii, jj, kk;
1021 int pat[16];
1022 char *cp;
1023
1024 for (cp = patp; *cp; cp++)
1025 if (!isxdigit(*cp)) {
1026 (void)fprintf(stderr,
1027 "ping: patterns must be specified as hex digits.\n");
1028 exit(1);
1029 }
1030 ii = sscanf(patp,
1031 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1032 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1033 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1034 &pat[13], &pat[14], &pat[15]);
1035
1036 if (ii > 0)
1037 for (kk = 0; kk <= MAXPACKET - (8 + ii); kk += ii)
1038 for (jj = 0; jj < ii; ++jj)
1039 bp[jj + kk] = pat[jj];
1040 if (!(options & F_QUIET)) {
1041 (void)printf("PATTERN: 0x");
1042 for (jj = 0; jj < ii; ++jj)
1043 (void)printf("%02x", bp[jj] & 0xFF);
1044 (void)printf("\n");
1045 }
1046}
1047
1048usage()
1049{
1050 (void)fprintf(stderr,
7b7f9fac 1051 "usage: ping [-LRdfnqrv] [-c count] [-i wait] [-l preload]\n\t[-p pattern] [-s packetsize] [-t ttl] [-I interface address] host\n");
15637ed4
RG
1052 exit(1);
1053}