2 * Object oriented C module to send ICMP and ICMPv6 `echo's.
3 * Copyright (C) 2006-2011 Florian octo Forster <ff at octo.it>
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
29 # include <inttypes.h>
33 # error "You don't have the standard C99 header files installed"
34 #endif /* STDC_HEADERS */
44 #if TIME_WITH_SYS_TIME
45 # include <sys/time.h>
49 # include <sys/time.h>
56 # include <sys/socket.h>
59 # include <netinet/in.h>
62 # include <netinet/ip.h>
66 # include <netdb.h> /* NI_MAXHOST */
74 #include <sys/types.h>
80 # define NCURSES_OPAQUE 1
81 /* http://newsgroups.derkeiler.com/Archive/Rec/rec.games.roguelike.development/2010-09/msg00050.html */
82 # define _X_OPEN_SOURCE_EXTENDED
83 # include <ncursesw/ncurses.h>
85 # define OPING_GREEN 1
86 # define OPING_YELLOW 2
92 const char *bars[BARS_LEN] = { "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" };
94 #ifndef _POSIX_SAVED_IDS
95 # define _POSIX_SAVED_IDS 0
98 /* Remove GNU specific __attribute__ settings when using another compiler */
100 # define __attribute__(x) /**/
103 typedef struct ping_context
105 char host[NI_MAXHOST];
106 char addr[NI_MAXHOST];
114 double latency_total;
115 double latency_total_square;
122 static double opt_interval = 1.0;
123 static int opt_addrfamily = PING_DEF_AF;
124 static char *opt_srcaddr = NULL;
125 static char *opt_device = NULL;
126 static char *opt_filename = NULL;
127 static int opt_count = -1;
128 static int opt_send_ttl = 64;
129 static uint8_t opt_send_qos = 0;
131 static int host_num = 0;
134 static WINDOW *main_win = NULL;
137 static void sigint_handler (int signal) /* {{{ */
139 /* Make compiler happy */
143 } /* }}} void sigint_handler */
145 static ping_context_t *context_create (void) /* {{{ */
149 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
152 memset (ret, '\0', sizeof (ping_context_t));
154 ret->latency_min = -1.0;
155 ret->latency_max = -1.0;
156 ret->latency_total = 0.0;
157 ret->latency_total_square = 0.0;
164 } /* }}} ping_context_t *context_create */
166 static void context_destroy (ping_context_t *context) /* {{{ */
172 if (context->window != NULL)
174 delwin (context->window);
175 context->window = NULL;
180 } /* }}} void context_destroy */
182 static double context_get_average (ping_context_t *ctx) /* {{{ */
189 if (ctx->req_rcvd < 1)
192 num_total = (double) ctx->req_rcvd;
193 return (ctx->latency_total / num_total);
194 } /* }}} double context_get_average */
196 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
203 if (ctx->req_rcvd < 1)
205 else if (ctx->req_rcvd < 2)
208 num_total = (double) ctx->req_rcvd;
209 return (sqrt (((num_total * ctx->latency_total_square)
210 - (ctx->latency_total * ctx->latency_total))
211 / (num_total * (num_total - 1.0))));
212 } /* }}} double context_get_stddev */
214 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
219 if (ctx->req_sent < 1)
222 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
223 / ((double) ctx->req_sent));
224 } /* }}} double context_get_packet_loss */
226 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
228 pingobj_iter_t *iter;
235 for (iter = ping_iterator_get (ping);
237 iter = ping_iterator_next (iter))
239 ping_context_t *context;
242 context = context_create ();
243 context->index = index;
245 buffer_size = sizeof (context->host);
246 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
248 buffer_size = sizeof (context->addr);
249 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
251 ping_iterator_set_context (iter, (void *) context);
257 } /* }}} int ping_initialize_contexts */
259 static void usage_exit (const char *name, int status) /* {{{ */
261 fprintf (stderr, "Usage: %s [OPTIONS] "
262 "-f filename | host [host [host ...]]\n"
264 "\nAvailable options:\n"
265 " -4|-6 force the use of IPv4 or IPv6\n"
266 " -c count number of ICMP packets to send\n"
267 " -i interval interval with which to send ICMP packets\n"
268 " -t ttl time to live for each ICMP packet\n"
269 " -Q qos Quality of Service (QoS) of outgoing packets\n"
270 " Use \"-Q help\" for a list of valid options.\n"
271 " -I srcaddr source address\n"
272 " -D device outgoing interface name\n"
273 " -f filename filename to read hosts from\n"
275 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
276 "by Florian octo Forster <octo@verplant.org>\n"
277 "for contributions see `AUTHORS'\n",
280 } /* }}} void usage_exit */
282 __attribute__((noreturn))
283 static void usage_qos_exit (const char *arg, int status) /* {{{ */
286 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
288 fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
290 " Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
292 " be Best Effort (BE, default PHB).\n"
293 " ef Expedited Forwarding (EF) PHB group (RFC 3246).\n"
294 " (low delay, low loss, low jitter)\n"
295 " va Voice Admit (VA) DSCP (RFC 5865).\n"
296 " (capacity-admitted traffic)\n"
297 " af[1-4][1-3] Assured Forwarding (AF) PHB group (RFC 2597).\n"
298 " For example: \"af12\" (class 1, precedence 2)\n"
299 " cs[0-7] Class Selector (CS) PHB group (RFC 2474).\n"
300 " For example: \"cs1\" (priority traffic)\n"
302 " Type of Service (IPv4, RFC 1349, obsolete)\n"
304 " lowdelay (%#04x) minimize delay\n"
305 " throughput (%#04x) maximize throughput\n"
306 " reliability (%#04x) maximize reliability\n"
307 " mincost (%#04x) minimize monetary cost\n"
309 " Specify manually\n"
311 " 0x00 - 0xff Hexadecimal numeric specification.\n"
312 " 0 - 255 Decimal numeric specification.\n"
314 (unsigned int) IPTOS_LOWDELAY,
315 (unsigned int) IPTOS_THROUGHPUT,
316 (unsigned int) IPTOS_RELIABILITY,
317 (unsigned int) IPTOS_MINCOST);
320 } /* }}} void usage_qos_exit */
322 static int set_opt_send_qos (const char *opt) /* {{{ */
327 if (strcasecmp ("help", opt) == 0)
328 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
329 /* DiffServ (RFC 2474): */
330 /* - Best effort (BE) */
331 else if (strcasecmp ("be", opt) == 0)
333 /* - Expedited Forwarding (EF, RFC 3246) */
334 else if (strcasecmp ("ef", opt) == 0)
335 opt_send_qos = 0xB8; /* == 0x2E << 2 */
336 /* - Voice Admit (VA, RFC 5865) */
337 else if (strcasecmp ("va", opt) == 0)
338 opt_send_qos = 0xB0; /* == 0x2D << 2 */
339 /* - Assured Forwarding (AF, RFC 2597) */
340 else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
341 && (strlen (opt) == 4))
347 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
350 else if (opt[2] == '2')
352 else if (opt[2] == '3')
354 else if (opt[2] == '4')
357 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
359 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
362 else if (opt[3] == '2')
364 else if (opt[3] == '3')
367 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
369 dscp = (8 * class) + (2 * prec);
370 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
371 opt_send_qos = dscp << 2;
373 /* - Class Selector (CS) */
374 else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
375 && (strlen (opt) == 3))
379 if ((opt[2] < '0') || (opt[2] > '7'))
380 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
382 /* Not exactly legal by the C standard, but I don't know of any
383 * system not supporting this hack. */
384 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
385 opt_send_qos = class << 5;
387 /* Type of Service (RFC 1349) */
388 else if (strcasecmp ("lowdelay", opt) == 0)
389 opt_send_qos = IPTOS_LOWDELAY;
390 else if (strcasecmp ("throughput", opt) == 0)
391 opt_send_qos = IPTOS_THROUGHPUT;
392 else if (strcasecmp ("reliability", opt) == 0)
393 opt_send_qos = IPTOS_RELIABILITY;
394 else if (strcasecmp ("mincost", opt) == 0)
395 opt_send_qos = IPTOS_MINCOST;
404 value = strtoul (opt, &endptr, /* base = */ 0);
405 if ((errno != 0) || (endptr == opt)
406 || (endptr == NULL) || (*endptr != 0)
408 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
410 opt_send_qos = (uint8_t) value;
414 } /* }}} int set_opt_send_qos */
416 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
428 case 0x00: dscp_str = "be"; break;
429 case 0x2e: dscp_str = "ef"; break;
430 case 0x2d: dscp_str = "va"; break;
431 case 0x0a: dscp_str = "af11"; break;
432 case 0x0c: dscp_str = "af12"; break;
433 case 0x0e: dscp_str = "af13"; break;
434 case 0x12: dscp_str = "af21"; break;
435 case 0x14: dscp_str = "af22"; break;
436 case 0x16: dscp_str = "af23"; break;
437 case 0x1a: dscp_str = "af31"; break;
438 case 0x1c: dscp_str = "af32"; break;
439 case 0x1e: dscp_str = "af33"; break;
440 case 0x22: dscp_str = "af41"; break;
441 case 0x24: dscp_str = "af42"; break;
442 case 0x26: dscp_str = "af43"; break;
443 case 0x08: dscp_str = "cs1"; break;
444 case 0x10: dscp_str = "cs2"; break;
445 case 0x18: dscp_str = "cs3"; break;
446 case 0x20: dscp_str = "cs4"; break;
447 case 0x28: dscp_str = "cs5"; break;
448 case 0x30: dscp_str = "cs6"; break;
449 case 0x38: dscp_str = "cs7"; break;
450 default: dscp_str = NULL;
455 case 0x01: ecn_str = ",ecn(1)"; break;
456 case 0x02: ecn_str = ",ecn(0)"; break;
457 case 0x03: ecn_str = ",ce"; break;
458 default: ecn_str = "";
461 if (dscp_str == NULL)
462 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
464 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
465 buffer[buffer_size - 1] = 0;
468 } /* }}} char *format_qos */
470 static int read_options (int argc, char **argv) /* {{{ */
476 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:");
485 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
491 new_count = atoi (optarg);
493 opt_count = new_count;
495 fprintf(stderr, "Ignoring invalid count: %s\n",
502 if (opt_filename != NULL)
504 opt_filename = strdup (optarg);
511 new_interval = atof (optarg);
512 if (new_interval < 0.001)
513 fprintf (stderr, "Ignoring invalid interval: %s\n",
516 opt_interval = new_interval;
521 if (opt_srcaddr != NULL)
523 opt_srcaddr = strdup (optarg);
534 new_send_ttl = atoi (optarg);
535 if ((new_send_ttl > 0) && (new_send_ttl < 256))
536 opt_send_ttl = new_send_ttl;
538 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
544 set_opt_send_qos (optarg);
548 usage_exit (argv[0], 0);
551 usage_exit (argv[0], 1);
556 } /* }}} read_options */
558 static void time_normalize (struct timespec *ts) /* {{{ */
560 while (ts->tv_nsec < 0)
569 ts->tv_nsec += 1000000000;
572 while (ts->tv_nsec >= 1000000000)
575 ts->tv_nsec -= 1000000000;
577 } /* }}} void time_normalize */
579 static void time_calc (struct timespec *ts_dest, /* {{{ */
580 const struct timespec *ts_int,
581 const struct timeval *tv_begin,
582 const struct timeval *tv_end)
584 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
585 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
586 time_normalize (ts_dest);
588 /* Assure that `(begin + interval) > end'.
589 * This may seem overly complicated, but `tv_sec' is of type `time_t'
590 * which may be `unsigned. *sigh* */
591 if ((tv_end->tv_sec > ts_dest->tv_sec)
592 || ((tv_end->tv_sec == ts_dest->tv_sec)
593 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
596 ts_dest->tv_nsec = 0;
600 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
601 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
602 time_normalize (ts_dest);
603 } /* }}} void time_calc */
606 static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter) /* {{{ */
608 double latency = -1.0;
609 size_t buffer_len = sizeof (latency);
610 ping_iterator_get_info (iter, PING_INFO_LATENCY,
611 &latency, &buffer_len);
613 unsigned int sequence = 0;
614 buffer_len = sizeof (sequence);
615 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
616 &sequence, &buffer_len);
619 if ((ctx == NULL) || (ctx->window == NULL))
622 /* werase (ctx->window); */
624 box (ctx->window, 0, 0);
625 wattron (ctx->window, A_BOLD);
626 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
628 wattroff (ctx->window, A_BOLD);
629 wprintw (ctx->window, "ping statistics ");
630 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
631 "%i packets transmitted, %i received, %.2f%% packet "
633 ctx->req_sent, ctx->req_rcvd,
634 context_get_packet_loss (ctx),
636 if (ctx->req_rcvd != 0)
641 average = context_get_average (ctx);
642 deviation = context_get_stddev (ctx);
644 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
645 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
654 if (has_colors () == TRUE)
656 int color = OPING_GREEN;
660 ratio = latency / PING_DEF_TTL;
664 else if (ratio > 1/3.0) {
665 color = OPING_YELLOW;
667 index = (int) (ratio * BARS_LEN * 3); /* 3 colors */
668 /* HOST_PRINTF ("%%r%f-ia%d-", ratio, index); */
669 index = index % (BARS_LEN-1);
670 /* HOST_PRINTF ("im%d-", index); */
671 if (index < 0 || index >= BARS_LEN) {
672 index = 0; /* safety check */
674 wattron (ctx->window, COLOR_PAIR(color));
675 mvwprintw (ctx->window,
676 /* y = */ 3, /* x = */ 1 + sequence,
678 wattroff (ctx->window, COLOR_PAIR(color));
685 wattron (ctx->window, COLOR_PAIR(OPING_RED) | A_BOLD);
686 mvwprintw (ctx->window,
687 /* y = */ 3, /* x = */ 1 + sequence,
689 wattroff (ctx->window, COLOR_PAIR(OPING_RED) | A_BOLD);
691 wrefresh (ctx->window);
694 } /* }}} int update_stats_from_context */
696 static int on_resize (pingobj_t *ping) /* {{{ */
698 pingobj_iter_t *iter;
703 getmaxyx (stdscr, height, width);
704 if ((height < 1) || (width < 1))
707 main_win_height = height - (5 * host_num);
708 wresize (main_win, main_win_height, /* width = */ width);
709 /* Allow scrolling */
710 scrollok (main_win, TRUE);
711 /* wsetscrreg (main_win, 0, main_win_height - 1); */
712 /* Allow hardware accelerated scrolling. */
713 idlok (main_win, TRUE);
716 for (iter = ping_iterator_get (ping);
718 iter = ping_iterator_next (iter))
720 ping_context_t *context;
722 context = ping_iterator_get_context (iter);
726 if (context->window != NULL)
728 delwin (context->window);
729 context->window = NULL;
731 context->window = newwin (/* height = */ 5,
733 /* y = */ main_win_height + (5 * context->index),
740 static int check_resize (pingobj_t *ping) /* {{{ */
746 int key = wgetch (stdscr);
749 else if (key == KEY_RESIZE)
754 return (on_resize (ping));
757 } /* }}} int check_resize */
759 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
761 pingobj_iter_t *iter;
769 nodelay (stdscr, TRUE);
771 getmaxyx (stdscr, height, width);
772 if ((height < 1) || (width < 1))
775 if (has_colors () == TRUE)
778 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
779 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
780 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
783 main_win_height = height - (5 * host_num);
784 main_win = newwin (/* height = */ main_win_height,
786 /* y = */ 0, /* x = */ 0);
787 /* Allow scrolling */
788 scrollok (main_win, TRUE);
789 /* wsetscrreg (main_win, 0, main_win_height - 1); */
790 /* Allow hardware accelerated scrolling. */
791 idlok (main_win, TRUE);
792 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
795 for (iter = ping_iterator_get (ping);
797 iter = ping_iterator_next (iter))
799 ping_context_t *context;
801 context = ping_iterator_get_context (iter);
805 if (context->window != NULL)
807 delwin (context->window);
808 context->window = NULL;
810 context->window = newwin (/* height = */ 5,
812 /* y = */ main_win_height + (5 * context->index),
817 /* Don't know what good this does exactly, but without this code
818 * "check_resize" will be called right after startup and *somehow*
819 * this leads to display errors. If we purge all initial characters
820 * here, the problem goes away. "wgetch" is non-blocking due to
821 * "nodelay" (see above). */
822 while (wgetch (stdscr) != ERR)
824 /* eat up characters */;
828 } /* }}} int pre_loop_hook */
830 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
832 return (check_resize (ping));
833 } /* }}} int pre_sleep_hook */
835 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
837 return (check_resize (ping));
838 } /* }}} int pre_sleep_hook */
839 #else /* if !USE_NCURSES */
840 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
842 pingobj_iter_t *iter;
844 for (iter = ping_iterator_get (ping);
846 iter = ping_iterator_next (iter))
851 ctx = ping_iterator_get_context (iter);
856 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
858 printf ("PING %s (%s) %zu bytes of data.\n",
859 ctx->host, ctx->addr, buffer_size);
863 } /* }}} int pre_loop_hook */
865 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
870 } /* }}} int pre_sleep_hook */
872 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
875 } /* }}} int post_sleep_hook */
878 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
879 __attribute__((unused)) int index)
882 unsigned int sequence;
885 char recv_qos_str[16];
888 ping_context_t *context;
891 buffer_len = sizeof (latency);
892 ping_iterator_get_info (iter, PING_INFO_LATENCY,
893 &latency, &buffer_len);
896 buffer_len = sizeof (sequence);
897 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
898 &sequence, &buffer_len);
901 buffer_len = sizeof (recv_ttl);
902 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
903 &recv_ttl, &buffer_len);
906 buffer_len = sizeof (recv_qos);
907 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
908 &recv_qos, &buffer_len);
911 ping_iterator_get_info (iter, PING_INFO_DATA,
914 context = (ping_context_t *) ping_iterator_get_context (iter);
917 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
919 # define HOST_PRINTF(...) printf(__VA_ARGS__)
926 context->latency_total += latency;
927 context->latency_total_square += (latency * latency);
929 if ((context->latency_max < 0.0) || (context->latency_max < latency))
930 context->latency_max = latency;
931 if ((context->latency_min < 0.0) || (context->latency_min > latency))
932 context->latency_min = latency;
935 if (has_colors () == TRUE)
937 int color = OPING_GREEN;
938 double average = context_get_average (context);
939 double stddev = context_get_stddev (context);
941 if ((latency < (average - (2 * stddev)))
942 || (latency > (average + (2 * stddev))))
944 else if ((latency < (average - stddev))
945 || (latency > (average + stddev)))
946 color = OPING_YELLOW;
948 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
949 data_len, context->host, context->addr,
951 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
952 if ((recv_qos != 0) || (opt_send_qos != 0))
954 HOST_PRINTF ("qos=%s ",
955 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
957 HOST_PRINTF ("time=");
958 wattron (main_win, COLOR_PAIR(color));
959 HOST_PRINTF ("%.2f", latency);
960 wattroff (main_win, COLOR_PAIR(color));
961 HOST_PRINTF (" ms\n");
966 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
968 context->host, context->addr,
970 if ((recv_qos != 0) || (opt_send_qos != 0))
972 HOST_PRINTF ("qos=%s ",
973 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
975 HOST_PRINTF ("time=%.2f ms\n", latency);
983 if (has_colors () == TRUE)
985 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
986 context->host, context->addr,
988 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
989 HOST_PRINTF ("timeout");
990 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
996 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
997 context->host, context->addr,
1005 update_stats_from_context (context, iter);
1006 wrefresh (main_win);
1008 } /* }}} void update_host_hook */
1010 static int post_loop_hook (pingobj_t *ping) /* {{{ */
1012 pingobj_iter_t *iter;
1018 for (iter = ping_iterator_get (ping);
1020 iter = ping_iterator_next (iter))
1022 ping_context_t *context;
1024 context = ping_iterator_get_context (iter);
1026 printf ("\n--- %s ping statistics ---\n"
1027 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
1028 context->host, context->req_sent, context->req_rcvd,
1029 context_get_packet_loss (context),
1030 context->latency_total);
1032 if (context->req_rcvd != 0)
1037 average = context_get_average (context);
1038 deviation = context_get_stddev (context);
1040 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
1041 context->latency_min,
1043 context->latency_max,
1047 ping_iterator_set_context (iter, NULL);
1048 context_destroy (context);
1052 } /* }}} int post_loop_hook */
1054 int main (int argc, char **argv) /* {{{ */
1057 pingobj_iter_t *iter;
1059 struct sigaction sigint_action;
1061 struct timeval tv_begin;
1062 struct timeval tv_end;
1063 struct timespec ts_wait;
1064 struct timespec ts_int;
1069 #if _POSIX_SAVED_IDS
1070 uid_t saved_set_uid;
1072 /* Save the old effective user id */
1073 saved_set_uid = geteuid ();
1074 /* Set the effective user ID to the real user ID without changing the
1075 * saved set-user ID */
1076 status = seteuid (getuid ());
1079 fprintf (stderr, "Temporarily dropping privileges "
1080 "failed: %s\n", strerror (errno));
1081 exit (EXIT_FAILURE);
1085 setlocale(LC_ALL, "");
1086 optind = read_options (argc, argv);
1088 #if !_POSIX_SAVED_IDS
1089 /* Cannot temporarily drop privileges -> reject every file but "-". */
1090 if ((opt_filename != NULL)
1091 && (strcmp ("-", opt_filename) != 0)
1092 && (getuid () != geteuid ()))
1094 fprintf (stderr, "Your real and effective user IDs don't "
1095 "match. Reading from a file (option '-f')\n"
1096 "is therefore too risky. You can still read "
1097 "from STDIN using '-f -' if you like.\n"
1099 exit (EXIT_FAILURE);
1103 if ((optind >= argc) && (opt_filename == NULL)) {
1104 usage_exit (argv[0], 1);
1107 if ((ping = ping_construct ()) == NULL)
1109 fprintf (stderr, "ping_construct failed\n");
1113 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1115 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1116 opt_send_ttl, ping_get_error (ping));
1119 if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1121 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1122 opt_send_qos, ping_get_error (ping));
1129 temp_nsec = modf (opt_interval, &temp_sec);
1130 ts_int.tv_sec = (time_t) temp_sec;
1131 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1133 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1136 if (opt_addrfamily != PING_DEF_AF)
1137 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1139 if (opt_srcaddr != NULL)
1141 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1143 fprintf (stderr, "Setting source address failed: %s\n",
1144 ping_get_error (ping));
1148 if (opt_device != NULL)
1150 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1152 fprintf (stderr, "Setting device failed: %s\n",
1153 ping_get_error (ping));
1157 if (opt_filename != NULL)
1163 if (strcmp (opt_filename, "-") == 0)
1165 infile = fdopen(0, "r");
1167 infile = fopen(opt_filename, "r");
1171 fprintf (stderr, "Opening %s failed: %s\n",
1172 (strcmp (opt_filename, "-") == 0)
1173 ? "STDIN" : opt_filename,
1178 #if _POSIX_SAVED_IDS
1179 /* Regain privileges */
1180 status = seteuid (saved_set_uid);
1183 fprintf (stderr, "Temporarily re-gaining privileges "
1184 "failed: %s\n", strerror (errno));
1185 exit (EXIT_FAILURE);
1189 while (fgets(line, sizeof(line), infile))
1191 /* Strip whitespace */
1192 if (sscanf(line, "%s", host) != 1)
1195 if ((host[0] == 0) || (host[0] == '#'))
1198 if (ping_host_add(ping, host) < 0)
1200 const char *errmsg = ping_get_error (ping);
1202 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1211 #if _POSIX_SAVED_IDS
1212 /* Drop privileges */
1213 status = seteuid (getuid ());
1216 fprintf (stderr, "Temporarily dropping privileges "
1217 "failed: %s\n", strerror (errno));
1218 exit (EXIT_FAILURE);
1225 #if _POSIX_SAVED_IDS
1226 /* Regain privileges */
1227 status = seteuid (saved_set_uid);
1230 fprintf (stderr, "Temporarily re-gaining privileges "
1231 "failed: %s\n", strerror (errno));
1232 exit (EXIT_FAILURE);
1236 for (i = optind; i < argc; i++)
1238 if (ping_host_add (ping, argv[i]) < 0)
1240 const char *errmsg = ping_get_error (ping);
1242 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1251 /* Permanently drop root privileges if we're setuid-root. */
1252 status = setuid (getuid ());
1255 fprintf (stderr, "Dropping privileges failed: %s\n",
1257 exit (EXIT_FAILURE);
1260 #if _POSIX_SAVED_IDS
1261 saved_set_uid = (uid_t) -1;
1264 ping_initialize_contexts (ping);
1269 memset (&sigint_action, '\0', sizeof (sigint_action));
1270 sigint_action.sa_handler = sigint_handler;
1271 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1273 perror ("sigaction");
1277 pre_loop_hook (ping);
1279 while (opt_count != 0)
1284 if (gettimeofday (&tv_begin, NULL) < 0)
1286 perror ("gettimeofday");
1290 if (ping_send (ping) < 0)
1292 fprintf (stderr, "ping_send failed: %s\n",
1293 ping_get_error (ping));
1298 for (iter = ping_iterator_get (ping);
1300 iter = ping_iterator_next (iter))
1302 update_host_hook (iter, index);
1306 pre_sleep_hook (ping);
1308 /* Don't sleep in the last iteration */
1312 if (gettimeofday (&tv_end, NULL) < 0)
1314 perror ("gettimeofday");
1318 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1320 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1321 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1325 perror ("nanosleep");
1328 else if (opt_count == 0)
1335 post_sleep_hook (ping);
1339 } /* while (opt_count != 0) */
1341 post_loop_hook (ping);
1343 ping_destroy (ping);
1346 } /* }}} int main */
1348 /* vim: set fdm=marker : */