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