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>
81 # define NCURSES_OPAQUE 1
82 /* http://newsgroups.derkeiler.com/Archive/Rec/rec.games.roguelike.development/2010-09/msg00050.html */
83 # define _X_OPEN_SOURCE_EXTENDED
85 # if HAVE_NCURSESW_NCURSES_H
86 # include <ncursesw/ncurses.h>
91 # define OPING_GREEN 1
92 # define OPING_YELLOW 2
94 # define OPING_GREEN_HIST 4
95 # define OPING_YELLOW_HIST 5
96 # define OPING_RED_HIST 6
98 static char const * const hist_symbols_utf8[] = {
99 "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" };
100 static size_t const hist_symbols_utf8_num = sizeof (hist_symbols_utf8)
101 / sizeof (hist_symbols_utf8[0]);
103 /* scancodes for 6 levels of horizontal bars, ncurses-specific */
104 /* those are not the usual constants because those are not constant */
105 static int const hist_symbols_acs[] = {
106 115, /* ACS_S9 "⎽" */
107 114, /* ACS_S7 "⎼" */
108 113, /* ACS_S5 "─" */
109 112, /* ACS_S3 "⎻" */
112 static size_t const hist_symbols_acs_num = sizeof (hist_symbols_acs)
113 / sizeof (hist_symbols_acs[0]);
115 /* use different colors without a background for scancodes */
116 static int const hist_colors_utf8[] = {
117 OPING_GREEN_HIST, OPING_YELLOW_HIST, OPING_RED_HIST };
118 static int const hist_colors_acs[] = {
119 OPING_GREEN, OPING_YELLOW, OPING_RED };
120 /* assuming that both arrays are the same size */
121 static size_t const hist_colors_num = sizeof (hist_colors_utf8)
122 / sizeof (hist_colors_utf8[0]);
127 #ifndef _POSIX_SAVED_IDS
128 # define _POSIX_SAVED_IDS 0
131 /* Remove GNU specific __attribute__ settings when using another compiler */
133 # define __attribute__(x) /**/
136 typedef struct ping_context
138 char host[NI_MAXHOST];
139 char addr[NI_MAXHOST];
147 double latency_total;
148 double latency_total_square;
155 static double opt_interval = 1.0;
156 static int opt_addrfamily = PING_DEF_AF;
157 static char *opt_srcaddr = NULL;
158 static char *opt_device = NULL;
159 static char *opt_filename = NULL;
160 static int opt_count = -1;
161 static int opt_send_ttl = 64;
162 static uint8_t opt_send_qos = 0;
164 static int opt_utf8 = 0;
167 static int host_num = 0;
170 static WINDOW *main_win = NULL;
173 static void sigint_handler (int signal) /* {{{ */
175 /* Make compiler happy */
179 } /* }}} void sigint_handler */
181 static ping_context_t *context_create (void) /* {{{ */
185 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
188 memset (ret, '\0', sizeof (ping_context_t));
190 ret->latency_min = -1.0;
191 ret->latency_max = -1.0;
192 ret->latency_total = 0.0;
193 ret->latency_total_square = 0.0;
200 } /* }}} ping_context_t *context_create */
202 static void context_destroy (ping_context_t *context) /* {{{ */
208 if (context->window != NULL)
210 delwin (context->window);
211 context->window = NULL;
216 } /* }}} void context_destroy */
218 static double context_get_average (ping_context_t *ctx) /* {{{ */
225 if (ctx->req_rcvd < 1)
228 num_total = (double) ctx->req_rcvd;
229 return (ctx->latency_total / num_total);
230 } /* }}} double context_get_average */
232 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
239 if (ctx->req_rcvd < 1)
241 else if (ctx->req_rcvd < 2)
244 num_total = (double) ctx->req_rcvd;
245 return (sqrt (((num_total * ctx->latency_total_square)
246 - (ctx->latency_total * ctx->latency_total))
247 / (num_total * (num_total - 1.0))));
248 } /* }}} double context_get_stddev */
250 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
255 if (ctx->req_sent < 1)
258 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
259 / ((double) ctx->req_sent));
260 } /* }}} double context_get_packet_loss */
262 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
264 pingobj_iter_t *iter;
271 for (iter = ping_iterator_get (ping);
273 iter = ping_iterator_next (iter))
275 ping_context_t *context;
278 context = context_create ();
279 context->index = index;
281 buffer_size = sizeof (context->host);
282 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
284 buffer_size = sizeof (context->addr);
285 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
287 ping_iterator_set_context (iter, (void *) context);
293 } /* }}} int ping_initialize_contexts */
295 static void usage_exit (const char *name, int status) /* {{{ */
297 fprintf (stderr, "Usage: %s [OPTIONS] "
298 "-f filename | host [host [host ...]]\n"
300 "\nAvailable options:\n"
301 " -4|-6 force the use of IPv4 or IPv6\n"
302 " -c count number of ICMP packets to send\n"
303 " -i interval interval with which to send ICMP packets\n"
304 " -t ttl time to live for each ICMP packet\n"
305 " -Q qos Quality of Service (QoS) of outgoing packets\n"
306 " Use \"-Q help\" for a list of valid options.\n"
307 " -I srcaddr source address\n"
308 " -D device outgoing interface name\n"
309 " -f filename filename to read hosts from\n"
311 " -u / -U force / disable UTF-8 output\n"
314 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
315 "by Florian octo Forster <octo@verplant.org>\n"
316 "for contributions see `AUTHORS'\n",
319 } /* }}} void usage_exit */
321 __attribute__((noreturn))
322 static void usage_qos_exit (const char *arg, int status) /* {{{ */
325 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
327 fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
329 " Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
331 " be Best Effort (BE, default PHB).\n"
332 " ef Expedited Forwarding (EF) PHB group (RFC 3246).\n"
333 " (low delay, low loss, low jitter)\n"
334 " va Voice Admit (VA) DSCP (RFC 5865).\n"
335 " (capacity-admitted traffic)\n"
336 " af[1-4][1-3] Assured Forwarding (AF) PHB group (RFC 2597).\n"
337 " For example: \"af12\" (class 1, precedence 2)\n"
338 " cs[0-7] Class Selector (CS) PHB group (RFC 2474).\n"
339 " For example: \"cs1\" (priority traffic)\n"
341 " Type of Service (IPv4, RFC 1349, obsolete)\n"
343 " lowdelay (%#04x) minimize delay\n"
344 " throughput (%#04x) maximize throughput\n"
345 " reliability (%#04x) maximize reliability\n"
346 " mincost (%#04x) minimize monetary cost\n"
348 " Specify manually\n"
350 " 0x00 - 0xff Hexadecimal numeric specification.\n"
351 " 0 - 255 Decimal numeric specification.\n"
353 (unsigned int) IPTOS_LOWDELAY,
354 (unsigned int) IPTOS_THROUGHPUT,
355 (unsigned int) IPTOS_RELIABILITY,
356 (unsigned int) IPTOS_MINCOST);
359 } /* }}} void usage_qos_exit */
361 static int set_opt_send_qos (const char *opt) /* {{{ */
366 if (strcasecmp ("help", opt) == 0)
367 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
368 /* DiffServ (RFC 2474): */
369 /* - Best effort (BE) */
370 else if (strcasecmp ("be", opt) == 0)
372 /* - Expedited Forwarding (EF, RFC 3246) */
373 else if (strcasecmp ("ef", opt) == 0)
374 opt_send_qos = 0xB8; /* == 0x2E << 2 */
375 /* - Voice Admit (VA, RFC 5865) */
376 else if (strcasecmp ("va", opt) == 0)
377 opt_send_qos = 0xB0; /* == 0x2D << 2 */
378 /* - Assured Forwarding (AF, RFC 2597) */
379 else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
380 && (strlen (opt) == 4))
386 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
389 else if (opt[2] == '2')
391 else if (opt[2] == '3')
393 else if (opt[2] == '4')
396 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
398 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
401 else if (opt[3] == '2')
403 else if (opt[3] == '3')
406 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
408 dscp = (8 * class) + (2 * prec);
409 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
410 opt_send_qos = dscp << 2;
412 /* - Class Selector (CS) */
413 else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
414 && (strlen (opt) == 3))
418 if ((opt[2] < '0') || (opt[2] > '7'))
419 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
421 /* Not exactly legal by the C standard, but I don't know of any
422 * system not supporting this hack. */
423 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
424 opt_send_qos = class << 5;
426 /* Type of Service (RFC 1349) */
427 else if (strcasecmp ("lowdelay", opt) == 0)
428 opt_send_qos = IPTOS_LOWDELAY;
429 else if (strcasecmp ("throughput", opt) == 0)
430 opt_send_qos = IPTOS_THROUGHPUT;
431 else if (strcasecmp ("reliability", opt) == 0)
432 opt_send_qos = IPTOS_RELIABILITY;
433 else if (strcasecmp ("mincost", opt) == 0)
434 opt_send_qos = IPTOS_MINCOST;
443 value = strtoul (opt, &endptr, /* base = */ 0);
444 if ((errno != 0) || (endptr == opt)
445 || (endptr == NULL) || (*endptr != 0)
447 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
449 opt_send_qos = (uint8_t) value;
453 } /* }}} int set_opt_send_qos */
455 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
467 case 0x00: dscp_str = "be"; break;
468 case 0x2e: dscp_str = "ef"; break;
469 case 0x2d: dscp_str = "va"; break;
470 case 0x0a: dscp_str = "af11"; break;
471 case 0x0c: dscp_str = "af12"; break;
472 case 0x0e: dscp_str = "af13"; break;
473 case 0x12: dscp_str = "af21"; break;
474 case 0x14: dscp_str = "af22"; break;
475 case 0x16: dscp_str = "af23"; break;
476 case 0x1a: dscp_str = "af31"; break;
477 case 0x1c: dscp_str = "af32"; break;
478 case 0x1e: dscp_str = "af33"; break;
479 case 0x22: dscp_str = "af41"; break;
480 case 0x24: dscp_str = "af42"; break;
481 case 0x26: dscp_str = "af43"; break;
482 case 0x08: dscp_str = "cs1"; break;
483 case 0x10: dscp_str = "cs2"; break;
484 case 0x18: dscp_str = "cs3"; break;
485 case 0x20: dscp_str = "cs4"; break;
486 case 0x28: dscp_str = "cs5"; break;
487 case 0x30: dscp_str = "cs6"; break;
488 case 0x38: dscp_str = "cs7"; break;
489 default: dscp_str = NULL;
494 case 0x01: ecn_str = ",ecn(1)"; break;
495 case 0x02: ecn_str = ",ecn(0)"; break;
496 case 0x03: ecn_str = ",ce"; break;
497 default: ecn_str = "";
500 if (dscp_str == NULL)
501 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
503 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
504 buffer[buffer_size - 1] = 0;
507 } /* }}} char *format_qos */
509 static int read_options (int argc, char **argv) /* {{{ */
515 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:"
528 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
534 new_count = atoi (optarg);
536 opt_count = new_count;
538 fprintf(stderr, "Ignoring invalid count: %s\n",
545 if (opt_filename != NULL)
547 opt_filename = strdup (optarg);
554 new_interval = atof (optarg);
555 if (new_interval < 0.001)
556 fprintf (stderr, "Ignoring invalid interval: %s\n",
559 opt_interval = new_interval;
564 if (opt_srcaddr != NULL)
566 opt_srcaddr = strdup (optarg);
577 new_send_ttl = atoi (optarg);
578 if ((new_send_ttl > 0) && (new_send_ttl < 256))
579 opt_send_ttl = new_send_ttl;
581 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
587 set_opt_send_qos (optarg);
600 usage_exit (argv[0], 0);
603 usage_exit (argv[0], 1);
608 } /* }}} read_options */
610 static void time_normalize (struct timespec *ts) /* {{{ */
612 while (ts->tv_nsec < 0)
621 ts->tv_nsec += 1000000000;
624 while (ts->tv_nsec >= 1000000000)
627 ts->tv_nsec -= 1000000000;
629 } /* }}} void time_normalize */
631 static void time_calc (struct timespec *ts_dest, /* {{{ */
632 const struct timespec *ts_int,
633 const struct timeval *tv_begin,
634 const struct timeval *tv_end)
636 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
637 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
638 time_normalize (ts_dest);
640 /* Assure that `(begin + interval) > end'.
641 * This may seem overly complicated, but `tv_sec' is of type `time_t'
642 * which may be `unsigned. *sigh* */
643 if ((tv_end->tv_sec > ts_dest->tv_sec)
644 || ((tv_end->tv_sec == ts_dest->tv_sec)
645 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
648 ts_dest->tv_nsec = 0;
652 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
653 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
654 time_normalize (ts_dest);
655 } /* }}} void time_calc */
658 static _Bool has_utf8() /* {{{ */
660 # if HAVE_NCURSESW_NCURSES_H
663 /* Automatically determine */
664 if (strcasecmp ("UTF-8", nl_langinfo (CODESET)) == 0)
669 return ((_Bool) (opt_utf8 - 1));
673 } /* }}} _Bool has_utf8 */
675 static int update_prettyping_graph (ping_context_t *ctx, /* {{{ */
676 double latency, unsigned int sequence)
678 int color = OPING_RED;
679 char const *symbol = "!";
681 size_t hist_symbols_num;
682 size_t index_symbols;
687 x_max = getmaxx (ctx->window);
688 x_pos = ((sequence - 1) % (x_max - 4)) + 2;
692 hist_symbols_num = hist_symbols_utf8_num;
695 hist_symbols_num = hist_symbols_acs_num;
704 ratio = latency / PING_DEF_TTL;
709 intensity = (size_t) ((ratio * hist_symbols_num
710 * hist_colors_num) - 1);
712 index_colors = intensity / hist_symbols_num;
713 assert (index_colors < hist_colors_num);
715 index_symbols = intensity % hist_symbols_num;
718 color = hist_colors_utf8[index_colors];
719 symbol = hist_symbols_utf8[index_symbols];
723 color = hist_colors_acs[index_colors];
724 symbolc = hist_symbols_acs[index_symbols] | A_ALTCHARSET;
727 else /* if (!(latency >= 0.0)) */
728 wattron (ctx->window, A_BOLD);
730 wattron (ctx->window, COLOR_PAIR(color));
733 mvwprintw (ctx->window,
739 mvwaddch (ctx->window,
744 wattroff (ctx->window, COLOR_PAIR(color));
746 /* Use negation here to handle NaN correctly. */
747 if (!(latency >= 0.0))
748 wattroff (ctx->window, A_BOLD);
750 wprintw (ctx->window, " ");
752 } /* }}} int update_prettyping_graph */
754 static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter) /* {{{ */
756 double latency = -1.0;
757 size_t buffer_len = sizeof (latency);
759 ping_iterator_get_info (iter, PING_INFO_LATENCY,
760 &latency, &buffer_len);
762 unsigned int sequence = 0;
763 buffer_len = sizeof (sequence);
764 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
765 &sequence, &buffer_len);
768 if ((ctx == NULL) || (ctx->window == NULL))
771 /* werase (ctx->window); */
773 box (ctx->window, 0, 0);
774 wattron (ctx->window, A_BOLD);
775 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
777 wattroff (ctx->window, A_BOLD);
778 wprintw (ctx->window, "ping statistics ");
779 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
780 "%i packets transmitted, %i received, %.2f%% packet "
782 ctx->req_sent, ctx->req_rcvd,
783 context_get_packet_loss (ctx),
785 if (ctx->req_rcvd != 0)
790 average = context_get_average (ctx);
791 deviation = context_get_stddev (ctx);
793 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
794 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
801 if (has_colors () == TRUE)
802 update_prettyping_graph (ctx, latency, sequence);
804 wrefresh (ctx->window);
807 } /* }}} int update_stats_from_context */
809 static int on_resize (pingobj_t *ping) /* {{{ */
811 pingobj_iter_t *iter;
816 getmaxyx (stdscr, height, width);
817 if ((height < 1) || (width < 1))
820 main_win_height = height - (5 * host_num);
821 wresize (main_win, main_win_height, /* width = */ width);
822 /* Allow scrolling */
823 scrollok (main_win, TRUE);
824 /* wsetscrreg (main_win, 0, main_win_height - 1); */
825 /* Allow hardware accelerated scrolling. */
826 idlok (main_win, TRUE);
829 for (iter = ping_iterator_get (ping);
831 iter = ping_iterator_next (iter))
833 ping_context_t *context;
835 context = ping_iterator_get_context (iter);
839 if (context->window != NULL)
841 delwin (context->window);
842 context->window = NULL;
844 context->window = newwin (/* height = */ 5,
846 /* y = */ main_win_height + (5 * context->index),
853 static int check_resize (pingobj_t *ping) /* {{{ */
859 int key = wgetch (stdscr);
862 else if (key == KEY_RESIZE)
867 return (on_resize (ping));
870 } /* }}} int check_resize */
872 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
874 pingobj_iter_t *iter;
882 nodelay (stdscr, TRUE);
884 getmaxyx (stdscr, height, width);
885 if ((height < 1) || (width < 1))
888 if (has_colors () == TRUE)
891 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
892 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
893 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
894 init_pair (OPING_GREEN_HIST, COLOR_GREEN, COLOR_BLACK);
895 init_pair (OPING_YELLOW_HIST, COLOR_YELLOW, COLOR_GREEN);
896 init_pair (OPING_RED_HIST, COLOR_RED, COLOR_YELLOW);
899 main_win_height = height - (5 * host_num);
900 main_win = newwin (/* height = */ main_win_height,
902 /* y = */ 0, /* x = */ 0);
903 /* Allow scrolling */
904 scrollok (main_win, TRUE);
905 /* wsetscrreg (main_win, 0, main_win_height - 1); */
906 /* Allow hardware accelerated scrolling. */
907 idlok (main_win, TRUE);
908 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
911 for (iter = ping_iterator_get (ping);
913 iter = ping_iterator_next (iter))
915 ping_context_t *context;
917 context = ping_iterator_get_context (iter);
921 if (context->window != NULL)
923 delwin (context->window);
924 context->window = NULL;
926 context->window = newwin (/* height = */ 5,
928 /* y = */ main_win_height + (5 * context->index),
933 /* Don't know what good this does exactly, but without this code
934 * "check_resize" will be called right after startup and *somehow*
935 * this leads to display errors. If we purge all initial characters
936 * here, the problem goes away. "wgetch" is non-blocking due to
937 * "nodelay" (see above). */
938 while (wgetch (stdscr) != ERR)
940 /* eat up characters */;
944 } /* }}} int pre_loop_hook */
946 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
948 return (check_resize (ping));
949 } /* }}} int pre_sleep_hook */
951 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
953 return (check_resize (ping));
954 } /* }}} int pre_sleep_hook */
955 #else /* if !USE_NCURSES */
956 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
958 pingobj_iter_t *iter;
960 for (iter = ping_iterator_get (ping);
962 iter = ping_iterator_next (iter))
967 ctx = ping_iterator_get_context (iter);
972 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
974 printf ("PING %s (%s) %zu bytes of data.\n",
975 ctx->host, ctx->addr, buffer_size);
979 } /* }}} int pre_loop_hook */
981 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
986 } /* }}} int pre_sleep_hook */
988 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
991 } /* }}} int post_sleep_hook */
994 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
995 __attribute__((unused)) int index)
998 unsigned int sequence;
1001 char recv_qos_str[16];
1004 ping_context_t *context;
1007 buffer_len = sizeof (latency);
1008 ping_iterator_get_info (iter, PING_INFO_LATENCY,
1009 &latency, &buffer_len);
1012 buffer_len = sizeof (sequence);
1013 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1014 &sequence, &buffer_len);
1017 buffer_len = sizeof (recv_ttl);
1018 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
1019 &recv_ttl, &buffer_len);
1022 buffer_len = sizeof (recv_qos);
1023 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
1024 &recv_qos, &buffer_len);
1027 ping_iterator_get_info (iter, PING_INFO_DATA,
1030 context = (ping_context_t *) ping_iterator_get_context (iter);
1033 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
1035 # define HOST_PRINTF(...) printf(__VA_ARGS__)
1038 context->req_sent++;
1041 context->req_rcvd++;
1042 context->latency_total += latency;
1043 context->latency_total_square += (latency * latency);
1045 if ((context->latency_max < 0.0) || (context->latency_max < latency))
1046 context->latency_max = latency;
1047 if ((context->latency_min < 0.0) || (context->latency_min > latency))
1048 context->latency_min = latency;
1051 if (has_colors () == TRUE)
1053 int color = OPING_GREEN;
1054 double average = context_get_average (context);
1055 double stddev = context_get_stddev (context);
1057 if ((latency < (average - (2 * stddev)))
1058 || (latency > (average + (2 * stddev))))
1060 else if ((latency < (average - stddev))
1061 || (latency > (average + stddev)))
1062 color = OPING_YELLOW;
1064 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1065 data_len, context->host, context->addr,
1067 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1068 if ((recv_qos != 0) || (opt_send_qos != 0))
1070 HOST_PRINTF ("qos=%s ",
1071 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1073 HOST_PRINTF ("time=");
1074 wattron (main_win, COLOR_PAIR(color));
1075 HOST_PRINTF ("%.2f", latency);
1076 wattroff (main_win, COLOR_PAIR(color));
1077 HOST_PRINTF (" ms\n");
1082 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1084 context->host, context->addr,
1085 sequence, recv_ttl);
1086 if ((recv_qos != 0) || (opt_send_qos != 0))
1088 HOST_PRINTF ("qos=%s ",
1089 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1091 HOST_PRINTF ("time=%.2f ms\n", latency);
1099 if (has_colors () == TRUE)
1101 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
1102 context->host, context->addr,
1104 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1105 HOST_PRINTF ("timeout");
1106 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1112 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
1113 context->host, context->addr,
1121 update_stats_from_context (context, iter);
1122 wrefresh (main_win);
1124 } /* }}} void update_host_hook */
1126 static int post_loop_hook (pingobj_t *ping) /* {{{ */
1128 pingobj_iter_t *iter;
1134 for (iter = ping_iterator_get (ping);
1136 iter = ping_iterator_next (iter))
1138 ping_context_t *context;
1140 context = ping_iterator_get_context (iter);
1142 printf ("\n--- %s ping statistics ---\n"
1143 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
1144 context->host, context->req_sent, context->req_rcvd,
1145 context_get_packet_loss (context),
1146 context->latency_total);
1148 if (context->req_rcvd != 0)
1153 average = context_get_average (context);
1154 deviation = context_get_stddev (context);
1156 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
1157 context->latency_min,
1159 context->latency_max,
1163 ping_iterator_set_context (iter, NULL);
1164 context_destroy (context);
1168 } /* }}} int post_loop_hook */
1170 int main (int argc, char **argv) /* {{{ */
1173 pingobj_iter_t *iter;
1175 struct sigaction sigint_action;
1177 struct timeval tv_begin;
1178 struct timeval tv_end;
1179 struct timespec ts_wait;
1180 struct timespec ts_int;
1185 #if _POSIX_SAVED_IDS
1186 uid_t saved_set_uid;
1188 /* Save the old effective user id */
1189 saved_set_uid = geteuid ();
1190 /* Set the effective user ID to the real user ID without changing the
1191 * saved set-user ID */
1192 status = seteuid (getuid ());
1195 fprintf (stderr, "Temporarily dropping privileges "
1196 "failed: %s\n", strerror (errno));
1197 exit (EXIT_FAILURE);
1201 setlocale(LC_ALL, "");
1202 optind = read_options (argc, argv);
1204 #if !_POSIX_SAVED_IDS
1205 /* Cannot temporarily drop privileges -> reject every file but "-". */
1206 if ((opt_filename != NULL)
1207 && (strcmp ("-", opt_filename) != 0)
1208 && (getuid () != geteuid ()))
1210 fprintf (stderr, "Your real and effective user IDs don't "
1211 "match. Reading from a file (option '-f')\n"
1212 "is therefore too risky. You can still read "
1213 "from STDIN using '-f -' if you like.\n"
1215 exit (EXIT_FAILURE);
1219 if ((optind >= argc) && (opt_filename == NULL)) {
1220 usage_exit (argv[0], 1);
1223 if ((ping = ping_construct ()) == NULL)
1225 fprintf (stderr, "ping_construct failed\n");
1229 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1231 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1232 opt_send_ttl, ping_get_error (ping));
1235 if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1237 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1238 opt_send_qos, ping_get_error (ping));
1245 temp_nsec = modf (opt_interval, &temp_sec);
1246 ts_int.tv_sec = (time_t) temp_sec;
1247 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1249 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1252 if (opt_addrfamily != PING_DEF_AF)
1253 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1255 if (opt_srcaddr != NULL)
1257 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1259 fprintf (stderr, "Setting source address failed: %s\n",
1260 ping_get_error (ping));
1264 if (opt_device != NULL)
1266 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1268 fprintf (stderr, "Setting device failed: %s\n",
1269 ping_get_error (ping));
1273 if (opt_filename != NULL)
1279 if (strcmp (opt_filename, "-") == 0)
1281 infile = fdopen(0, "r");
1283 infile = fopen(opt_filename, "r");
1287 fprintf (stderr, "Opening %s failed: %s\n",
1288 (strcmp (opt_filename, "-") == 0)
1289 ? "STDIN" : opt_filename,
1294 #if _POSIX_SAVED_IDS
1295 /* Regain privileges */
1296 status = seteuid (saved_set_uid);
1299 fprintf (stderr, "Temporarily re-gaining privileges "
1300 "failed: %s\n", strerror (errno));
1301 exit (EXIT_FAILURE);
1305 while (fgets(line, sizeof(line), infile))
1307 /* Strip whitespace */
1308 if (sscanf(line, "%s", host) != 1)
1311 if ((host[0] == 0) || (host[0] == '#'))
1314 if (ping_host_add(ping, host) < 0)
1316 const char *errmsg = ping_get_error (ping);
1318 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1327 #if _POSIX_SAVED_IDS
1328 /* Drop privileges */
1329 status = seteuid (getuid ());
1332 fprintf (stderr, "Temporarily dropping privileges "
1333 "failed: %s\n", strerror (errno));
1334 exit (EXIT_FAILURE);
1341 #if _POSIX_SAVED_IDS
1342 /* Regain privileges */
1343 status = seteuid (saved_set_uid);
1346 fprintf (stderr, "Temporarily re-gaining privileges "
1347 "failed: %s\n", strerror (errno));
1348 exit (EXIT_FAILURE);
1352 for (i = optind; i < argc; i++)
1354 if (ping_host_add (ping, argv[i]) < 0)
1356 const char *errmsg = ping_get_error (ping);
1358 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1367 /* Permanently drop root privileges if we're setuid-root. */
1368 status = setuid (getuid ());
1371 fprintf (stderr, "Dropping privileges failed: %s\n",
1373 exit (EXIT_FAILURE);
1376 #if _POSIX_SAVED_IDS
1377 saved_set_uid = (uid_t) -1;
1380 ping_initialize_contexts (ping);
1385 memset (&sigint_action, '\0', sizeof (sigint_action));
1386 sigint_action.sa_handler = sigint_handler;
1387 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1389 perror ("sigaction");
1393 pre_loop_hook (ping);
1395 while (opt_count != 0)
1400 if (gettimeofday (&tv_begin, NULL) < 0)
1402 perror ("gettimeofday");
1406 if (ping_send (ping) < 0)
1408 fprintf (stderr, "ping_send failed: %s\n",
1409 ping_get_error (ping));
1414 for (iter = ping_iterator_get (ping);
1416 iter = ping_iterator_next (iter))
1418 update_host_hook (iter, index);
1422 pre_sleep_hook (ping);
1424 /* Don't sleep in the last iteration */
1428 if (gettimeofday (&tv_end, NULL) < 0)
1430 perror ("gettimeofday");
1434 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1436 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1437 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1441 perror ("nanosleep");
1444 else if (opt_count == 0)
1451 post_sleep_hook (ping);
1455 } /* while (opt_count != 0) */
1457 post_loop_hook (ping);
1459 ping_destroy (ping);
1462 } /* }}} int main */
1464 /* vim: set fdm=marker : */