2 * Object oriented C module to send ICMP and ICMPv6 `echo's.
3 * Copyright (C) 2006-2010 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)
126 static void usage_exit (const char *name, int status)
130 name_length = (int) strlen (name);
132 fprintf (stderr, "Usage: %s [OPTIONS] "
133 "-f filename | host [host [host ...]]\n"
135 "\nAvailable options:\n"
136 " -4|-6 force the use of IPv4 or IPv6\n"
137 " -c count number of ICMP packets to send\n"
138 " -i interval interval with which to send ICMP packets\n"
139 " -t ttl time to live for each ICMP packet\n"
140 " -I srcaddr source address\n"
141 " -D device outgoing interface name\n"
142 " -f filename filename to read hosts from\n"
144 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
145 "by Florian octo Forster <octo@verplant.org>\n"
146 "for contributions see `AUTHORS'\n",
151 static int read_options (int argc, char **argv)
157 optchar = getopt (argc, argv, "46c:hi:I:t:f:D:");
166 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
172 new_count = atoi (optarg);
174 opt_count = new_count;
176 fprintf(stderr, "Ignoring invalid count: %s\n",
183 if (opt_filename != NULL)
185 opt_filename = strdup (optarg);
192 new_interval = atof (optarg);
193 if (new_interval < 0.001)
194 fprintf (stderr, "Ignoring invalid interval: %s\n",
197 opt_interval = new_interval;
202 if (opt_srcaddr != NULL)
204 opt_srcaddr = strdup (optarg);
215 new_send_ttl = atoi (optarg);
216 if ((new_send_ttl > 0) && (new_send_ttl < 256))
217 opt_send_ttl = new_send_ttl;
219 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
225 usage_exit (argv[0], 0);
228 usage_exit (argv[0], 1);
235 static void print_host (pingobj_iter_t *iter)
238 unsigned int sequence;
242 ping_context_t *context;
245 buffer_len = sizeof (latency);
246 ping_iterator_get_info (iter, PING_INFO_LATENCY,
247 &latency, &buffer_len);
250 buffer_len = sizeof (sequence);
251 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
252 &sequence, &buffer_len);
255 buffer_len = sizeof (recv_ttl);
256 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
257 &recv_ttl, &buffer_len);
260 ping_iterator_get_info (iter, PING_INFO_DATA,
263 context = (ping_context_t *) ping_iterator_get_context (iter);
269 context->latency_total += latency;
270 context->latency_total_square += (latency * latency);
272 if ((context->latency_max < 0.0) || (context->latency_max < latency))
273 context->latency_max = latency;
274 if ((context->latency_min < 0.0) || (context->latency_min > latency))
275 context->latency_min = latency;
277 printf ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i time=%.2f ms\n",
279 context->host, context->addr,
280 sequence, recv_ttl, latency);
284 printf ("echo reply from %s (%s): icmp_seq=%u timeout\n",
285 context->host, context->addr,
290 static void time_normalize (struct timespec *ts)
292 while (ts->tv_nsec < 0)
301 ts->tv_nsec += 1000000000;
304 while (ts->tv_nsec >= 1000000000)
307 ts->tv_nsec -= 1000000000;
311 static void time_calc (struct timespec *ts_dest, /* {{{ */
312 const struct timespec *ts_int,
313 const struct timeval *tv_begin,
314 const struct timeval *tv_end)
316 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
317 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
318 time_normalize (ts_dest);
320 /* Assure that `(begin + interval) > end'.
321 * This may seem overly complicated, but `tv_sec' is of type `time_t'
322 * which may be `unsigned. *sigh* */
323 if ((tv_end->tv_sec > ts_dest->tv_sec)
324 || ((tv_end->tv_sec == ts_dest->tv_sec)
325 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
328 ts_dest->tv_nsec = 0;
332 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
333 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
334 time_normalize (ts_dest);
335 } /* }}} void time_calc */
337 static int print_header (pingobj_t *ping) /* {{{ */
339 pingobj_iter_t *iter;
343 for (iter = ping_iterator_get (ping);
345 iter = ping_iterator_next (iter))
347 ping_context_t *context;
350 context = context_create ();
352 buffer_size = sizeof (context->host);
353 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
355 buffer_size = sizeof (context->addr);
356 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
359 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
361 printf ("PING %s (%s) %zu bytes of data.\n",
362 context->host, context->addr, buffer_size);
364 ping_iterator_set_context (iter, (void *) context);
370 } /* }}} int print_header */
372 static int print_footer (pingobj_t *ping)
374 pingobj_iter_t *iter;
376 for (iter = ping_iterator_get (ping);
378 iter = ping_iterator_next (iter))
380 ping_context_t *context;
382 context = ping_iterator_get_context (iter);
384 printf ("\n--- %s ping statistics ---\n"
385 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
386 context->host, context->req_sent, context->req_rcvd,
387 100.0 * (context->req_sent - context->req_rcvd) / ((double) context->req_sent),
388 context->latency_total);
390 if (context->req_rcvd != 0)
396 num_total = (double) context->req_rcvd;
398 average = context->latency_total / num_total;
399 deviation = sqrt (((num_total * context->latency_total_square) - (context->latency_total * context->latency_total))
400 / (num_total * (num_total - 1.0)));
402 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
403 context->latency_min,
405 context->latency_max,
409 ping_iterator_set_context (iter, NULL);
410 context_destroy (context);
414 } /* }}} int print_footer */
416 int main (int argc, char **argv) /* {{{ */
419 pingobj_iter_t *iter;
421 struct sigaction sigint_action;
423 struct timeval tv_begin;
424 struct timeval tv_end;
425 struct timespec ts_wait;
426 struct timespec ts_int;
434 /* Save the old effective user id */
435 saved_set_uid = geteuid ();
436 /* Set the effective user ID to the real user ID without changing the
437 * saved set-user ID */
438 status = seteuid (getuid ());
441 fprintf (stderr, "Temporarily dropping privileges "
442 "failed: %s\n", strerror (errno));
447 optind = read_options (argc, argv);
449 #if !_POSIX_SAVED_IDS
450 /* Cannot temporarily drop privileges -> reject every file but "-". */
451 if ((opt_filename != NULL)
452 && (strcmp ("-", opt_filename) != 0)
453 && (getuid () != geteuid ()))
455 fprintf (stderr, "Your real and effective user IDs don't "
456 "match. Reading from a file (option '-f')\n"
457 "is therefore too risky. You can still read "
458 "from STDIN using '-f -' if you like.\n"
464 if ((optind >= argc) && (opt_filename == NULL)) {
465 usage_exit (argv[0], 1);
468 if ((ping = ping_construct ()) == NULL)
470 fprintf (stderr, "ping_construct failed\n");
474 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
476 fprintf (stderr, "Setting TTL to %i failed: %s\n",
477 opt_send_ttl, ping_get_error (ping));
484 temp_nsec = modf (opt_interval, &temp_sec);
485 ts_int.tv_sec = (time_t) temp_sec;
486 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
488 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
491 if (opt_addrfamily != PING_DEF_AF)
492 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
494 if (opt_srcaddr != NULL)
496 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
498 fprintf (stderr, "Setting source address failed: %s\n",
499 ping_get_error (ping));
503 if (opt_device != NULL)
505 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
507 fprintf (stderr, "Setting device failed: %s\n",
508 ping_get_error (ping));
512 if (opt_filename != NULL)
518 if (strcmp (opt_filename, "-") == 0)
520 infile = fdopen(0, "r");
522 infile = fopen(opt_filename, "r");
526 fprintf (stderr, "Opening %s failed: %s\n",
527 (strcmp (opt_filename, "-") == 0)
528 ? "STDIN" : opt_filename,
534 /* Regain privileges */
535 status = seteuid (saved_set_uid);
538 fprintf (stderr, "Temporarily re-gaining privileges "
539 "failed: %s\n", strerror (errno));
544 while (fgets(line, sizeof(line), infile))
546 /* Strip whitespace */
547 if (sscanf(line, "%s", host) != 1)
550 if ((host[0] == 0) || (host[0] == '#'))
553 if (ping_host_add(ping, host) < 0)
555 const char *errmsg = ping_get_error (ping);
557 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
563 /* Drop privileges */
564 status = seteuid (getuid ());
567 fprintf (stderr, "Temporarily dropping privileges "
568 "failed: %s\n", strerror (errno));
577 /* Regain privileges */
578 status = seteuid (saved_set_uid);
581 fprintf (stderr, "Temporarily re-gaining privileges "
582 "failed: %s\n", strerror (errno));
587 for (i = optind; i < argc; i++)
589 if (ping_host_add (ping, argv[i]) < 0)
591 const char *errmsg = ping_get_error (ping);
593 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
598 /* Permanently drop root privileges if we're setuid-root. */
599 status = setuid (getuid ());
602 fprintf (stderr, "Dropping privileges failed: %s\n",
608 saved_set_uid = (uid_t) -1;
616 memset (&sigint_action, '\0', sizeof (sigint_action));
617 sigint_action.sa_handler = sigint_handler;
618 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
620 perror ("sigaction");
624 while (opt_count != 0)
628 if (gettimeofday (&tv_begin, NULL) < 0)
630 perror ("gettimeofday");
634 if (ping_send (ping) < 0)
636 fprintf (stderr, "ping_send failed: %s\n",
637 ping_get_error (ping));
641 for (iter = ping_iterator_get (ping);
643 iter = ping_iterator_next (iter))
649 /* Don't sleep in the last iteration */
653 if (gettimeofday (&tv_end, NULL) < 0)
655 perror ("gettimeofday");
659 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
661 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
662 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
666 perror ("nanosleep");
669 else if (opt_count == 0)
678 } /* while (opt_count != 0) */
687 /* vim: set fdm=marker : */