2 * Object oriented C module to send ICMP and ICMPv6 `echo's.
3 * Copyright (C) 2006 Florian octo Forster <octo at verplant.org>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; only version 2 of the License is
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
31 # error "You don't have the standard C99 header files installed"
32 #endif /* STDC_HEADERS */
42 #if TIME_WITH_SYS_TIME
43 # include <sys/time.h>
47 # include <sys/time.h>
54 # include <netdb.h> /* NI_MAXHOST */
62 #include <sys/types.h>
67 #ifndef _POSIX_SAVED_IDS
68 # define _POSIX_SAVED_IDS 0
71 typedef struct ping_context
73 char host[NI_MAXHOST];
74 char addr[NI_MAXHOST];
82 double latency_total_square;
85 static double opt_interval = 1.0;
86 static int opt_addrfamily = PING_DEF_AF;
87 static char *opt_srcaddr = NULL;
88 static char *opt_device = NULL;
89 static char *opt_filename = NULL;
90 static int opt_count = -1;
91 static int opt_send_ttl = 64;
93 static void sigint_handler (int signal)
95 /* Make compiler happy */
101 static ping_context_t *context_create (void)
105 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
108 memset (ret, '\0', sizeof (ping_context_t));
110 ret->latency_min = -1.0;
111 ret->latency_max = -1.0;
112 ret->latency_total = 0.0;
113 ret->latency_total_square = 0.0;
118 static void context_destroy (ping_context_t *context)
123 static void usage_exit (const char *name, int status)
127 name_length = (int) strlen (name);
129 fprintf (stderr, "Usage: %s [OPTIONS] "
130 "-f filename | host [host [host ...]]\n"
132 "\nAvailable options:\n"
133 " -4|-6 force the use of IPv4 or IPv6\n"
134 " -c count number of ICMP packets to send\n"
135 " -i interval interval with which to send ICMP packets\n"
136 " -t ttl time to live for each ICMP packet\n"
137 " -I srcaddr source address\n"
138 " -D device outgoing interface name\n"
139 " -f filename filename to read hosts from\n"
141 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
142 "by Florian octo Forster <octo@verplant.org>\n"
143 "for contributions see `AUTHORS'\n",
148 static int read_options (int argc, char **argv)
154 optchar = getopt (argc, argv, "46c:hi:I:t:f:D:");
163 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
169 new_count = atoi (optarg);
171 opt_count = new_count;
173 fprintf(stderr, "Ignoring invalid count: %s\n",
180 if (opt_filename != NULL)
182 opt_filename = strdup (optarg);
189 new_interval = atof (optarg);
190 if (new_interval < 0.001)
191 fprintf (stderr, "Ignoring invalid interval: %s\n",
194 opt_interval = new_interval;
199 if (opt_srcaddr != NULL)
201 opt_srcaddr = strdup (optarg);
212 new_send_ttl = atoi (optarg);
213 if ((new_send_ttl > 0) && (new_send_ttl < 256))
214 opt_send_ttl = new_send_ttl;
216 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
222 usage_exit (argv[0], 0);
225 usage_exit (argv[0], 1);
232 static void print_host (pingobj_iter_t *iter)
235 unsigned int sequence;
239 ping_context_t *context;
242 buffer_len = sizeof (latency);
243 ping_iterator_get_info (iter, PING_INFO_LATENCY,
244 &latency, &buffer_len);
247 buffer_len = sizeof (sequence);
248 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
249 &sequence, &buffer_len);
252 buffer_len = sizeof (recv_ttl);
253 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
254 &recv_ttl, &buffer_len);
257 ping_iterator_get_info (iter, PING_INFO_DATA,
260 context = (ping_context_t *) ping_iterator_get_context (iter);
266 context->latency_total += latency;
267 context->latency_total_square += (latency * latency);
269 if ((context->latency_max < 0.0) || (context->latency_max < latency))
270 context->latency_max = latency;
271 if ((context->latency_min < 0.0) || (context->latency_min > latency))
272 context->latency_min = latency;
274 printf ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i time=%.2f ms\n",
276 context->host, context->addr,
277 sequence, recv_ttl, latency);
281 printf ("echo reply from %s (%s): icmp_seq=%u timeout\n",
282 context->host, context->addr,
287 static void time_normalize (struct timespec *ts)
289 while (ts->tv_nsec < 0)
298 ts->tv_nsec += 1000000000;
301 while (ts->tv_nsec >= 1000000000)
304 ts->tv_nsec -= 1000000000;
308 static void time_calc (struct timespec *ts_dest,
309 const struct timespec *ts_int,
310 const struct timeval *tv_begin,
311 const struct timeval *tv_end)
313 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
314 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
315 time_normalize (ts_dest);
317 /* Assure that `(begin + interval) > end'.
318 * This may seem overly complicated, but `tv_sec' is of type `time_t'
319 * which may be `unsigned. *sigh* */
320 if ((tv_end->tv_sec > ts_dest->tv_sec)
321 || ((tv_end->tv_sec == ts_dest->tv_sec)
322 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
325 ts_dest->tv_nsec = 0;
329 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
330 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
331 time_normalize (ts_dest);
334 int main (int argc, char **argv)
337 pingobj_iter_t *iter;
339 struct sigaction sigint_action;
341 struct timeval tv_begin;
342 struct timeval tv_end;
343 struct timespec ts_wait;
344 struct timespec ts_int;
352 /* Save the old effective user id */
353 saved_set_uid = geteuid ();
354 /* Set the effective user ID to the real user ID without changing the
355 * saved set-user ID */
356 status = seteuid (getuid ());
359 fprintf (stderr, "Temporarily dropping privileges "
360 "failed: %s\n", strerror (errno));
365 optind = read_options (argc, argv);
367 #if !_POSIX_SAVED_IDS
368 /* Cannot temporarily drop privileges -> reject every file but "-". */
369 if ((opt_filename != NULL)
370 && (strcmp ("-", opt_filename) != 0)
371 && (getuid () != geteuid ()))
373 fprintf (stderr, "Your real and effective user IDs don't "
374 "match. Reading from a file (option '-f')\n"
375 "is therefore too risky. You can still read "
376 "from STDIN using '-f -' if you like.\n"
382 if ((optind >= argc) && (opt_filename == NULL)) {
383 usage_exit (argv[0], 1);
386 if ((ping = ping_construct ()) == NULL)
388 fprintf (stderr, "ping_construct failed\n");
392 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
394 fprintf (stderr, "Setting TTL to %i failed: %s\n",
395 opt_send_ttl, ping_get_error (ping));
402 temp_nsec = modf (opt_interval, &temp_sec);
403 ts_int.tv_sec = (time_t) temp_sec;
404 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
406 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
409 if (opt_addrfamily != PING_DEF_AF)
410 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
412 if (opt_srcaddr != NULL)
414 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
416 fprintf (stderr, "Setting source address failed: %s\n",
417 ping_get_error (ping));
421 if (opt_device != NULL)
423 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
425 fprintf (stderr, "Setting device failed: %s\n",
426 ping_get_error (ping));
430 if (opt_filename != NULL)
436 if (strcmp (opt_filename, "-") == 0)
438 infile = fdopen(0, "r");
440 infile = fopen(opt_filename, "r");
444 fprintf (stderr, "Opening %s failed: %s\n",
445 (strcmp (opt_filename, "-") == 0)
446 ? "STDIN" : opt_filename,
452 /* Regain privileges */
453 status = seteuid (saved_set_uid);
456 fprintf (stderr, "Temporarily re-gaining privileges "
457 "failed: %s\n", strerror (errno));
462 while (fgets(line, sizeof(line), infile))
464 /* Strip whitespace */
465 if (sscanf(line, "%s", host) != 1)
468 if ((host[0] == 0) || (host[0] == '#'))
471 if (ping_host_add(ping, host) < 0)
473 const char *errmsg = ping_get_error (ping);
475 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
481 /* Drop privileges */
482 status = seteuid (getuid ());
485 fprintf (stderr, "Temporarily dropping privileges "
486 "failed: %s\n", strerror (errno));
495 /* Regain privileges */
496 status = seteuid (saved_set_uid);
499 fprintf (stderr, "Temporarily re-gaining privileges "
500 "failed: %s\n", strerror (errno));
505 for (i = optind; i < argc; i++)
507 if (ping_host_add (ping, argv[i]) < 0)
509 const char *errmsg = ping_get_error (ping);
511 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
516 /* Permanently drop root privileges if we're setuid-root. */
517 status = setuid (getuid ());
520 fprintf (stderr, "Dropping privileges failed: %s\n",
526 saved_set_uid = (uid_t) -1;
530 for (iter = ping_iterator_get (ping);
532 iter = ping_iterator_next (iter))
534 ping_context_t *context;
537 context = context_create ();
539 buffer_size = sizeof (context->host);
540 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
542 buffer_size = sizeof (context->addr);
543 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
546 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
548 printf ("PING %s (%s) %zu bytes of data.\n",
549 context->host, context->addr, buffer_size);
551 ping_iterator_set_context (iter, (void *) context);
559 memset (&sigint_action, '\0', sizeof (sigint_action));
560 sigint_action.sa_handler = sigint_handler;
561 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
563 perror ("sigaction");
567 while (opt_count != 0)
571 if (gettimeofday (&tv_begin, NULL) < 0)
573 perror ("gettimeofday");
577 if (ping_send (ping) < 0)
579 fprintf (stderr, "ping_send failed: %s\n",
580 ping_get_error (ping));
584 for (iter = ping_iterator_get (ping);
586 iter = ping_iterator_next (iter))
592 /* Don't sleep in the last iteration */
596 if (gettimeofday (&tv_end, NULL) < 0)
598 perror ("gettimeofday");
602 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
604 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
605 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
609 perror ("nanosleep");
612 else if (opt_count == 0)
621 } /* while (opt_count != 0) */
623 for (iter = ping_iterator_get (ping);
625 iter = ping_iterator_next (iter))
627 ping_context_t *context;
629 context = ping_iterator_get_context (iter);
631 printf ("\n--- %s ping statistics ---\n"
632 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
633 context->host, context->req_sent, context->req_rcvd,
634 100.0 * (context->req_sent - context->req_rcvd) / ((double) context->req_sent),
635 context->latency_total);
637 if (context->req_rcvd != 0)
643 num_total = (double) context->req_rcvd;
645 average = context->latency_total / num_total;
646 deviation = sqrt (((num_total * context->latency_total_square) - (context->latency_total * context->latency_total))
647 / (num_total * (num_total - 1.0)));
649 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
650 context->latency_min,
652 context->latency_max,
656 ping_iterator_set_context (iter, NULL);
657 context_destroy (context);