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