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