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