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