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
88 # define OPING_GREEN_HIST 4
89 # define OPING_YELLOW_HIST 5
90 # define OPING_RED_HIST 6
95 const char *bars[BARS_LEN] = { "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" };
97 #ifndef _POSIX_SAVED_IDS
98 # define _POSIX_SAVED_IDS 0
101 /* Remove GNU specific __attribute__ settings when using another compiler */
103 # define __attribute__(x) /**/
106 typedef struct ping_context
108 char host[NI_MAXHOST];
109 char addr[NI_MAXHOST];
117 double latency_total;
118 double latency_total_square;
125 static double opt_interval = 1.0;
126 static int opt_addrfamily = PING_DEF_AF;
127 static char *opt_srcaddr = NULL;
128 static char *opt_device = NULL;
129 static char *opt_filename = NULL;
130 static int opt_count = -1;
131 static int opt_send_ttl = 64;
132 static uint8_t opt_send_qos = 0;
134 static int host_num = 0;
137 static WINDOW *main_win = NULL;
140 static void sigint_handler (int signal) /* {{{ */
142 /* Make compiler happy */
146 } /* }}} void sigint_handler */
148 static ping_context_t *context_create (void) /* {{{ */
152 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
155 memset (ret, '\0', sizeof (ping_context_t));
157 ret->latency_min = -1.0;
158 ret->latency_max = -1.0;
159 ret->latency_total = 0.0;
160 ret->latency_total_square = 0.0;
167 } /* }}} ping_context_t *context_create */
169 static void context_destroy (ping_context_t *context) /* {{{ */
175 if (context->window != NULL)
177 delwin (context->window);
178 context->window = NULL;
183 } /* }}} void context_destroy */
185 static double context_get_average (ping_context_t *ctx) /* {{{ */
192 if (ctx->req_rcvd < 1)
195 num_total = (double) ctx->req_rcvd;
196 return (ctx->latency_total / num_total);
197 } /* }}} double context_get_average */
199 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
206 if (ctx->req_rcvd < 1)
208 else if (ctx->req_rcvd < 2)
211 num_total = (double) ctx->req_rcvd;
212 return (sqrt (((num_total * ctx->latency_total_square)
213 - (ctx->latency_total * ctx->latency_total))
214 / (num_total * (num_total - 1.0))));
215 } /* }}} double context_get_stddev */
217 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
222 if (ctx->req_sent < 1)
225 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
226 / ((double) ctx->req_sent));
227 } /* }}} double context_get_packet_loss */
229 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
231 pingobj_iter_t *iter;
238 for (iter = ping_iterator_get (ping);
240 iter = ping_iterator_next (iter))
242 ping_context_t *context;
245 context = context_create ();
246 context->index = index;
248 buffer_size = sizeof (context->host);
249 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
251 buffer_size = sizeof (context->addr);
252 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
254 ping_iterator_set_context (iter, (void *) context);
260 } /* }}} int ping_initialize_contexts */
262 static void usage_exit (const char *name, int status) /* {{{ */
264 fprintf (stderr, "Usage: %s [OPTIONS] "
265 "-f filename | host [host [host ...]]\n"
267 "\nAvailable options:\n"
268 " -4|-6 force the use of IPv4 or IPv6\n"
269 " -c count number of ICMP packets to send\n"
270 " -i interval interval with which to send ICMP packets\n"
271 " -t ttl time to live for each ICMP packet\n"
272 " -Q qos Quality of Service (QoS) of outgoing packets\n"
273 " Use \"-Q help\" for a list of valid options.\n"
274 " -I srcaddr source address\n"
275 " -D device outgoing interface name\n"
276 " -f filename filename to read hosts from\n"
278 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
279 "by Florian octo Forster <octo@verplant.org>\n"
280 "for contributions see `AUTHORS'\n",
283 } /* }}} void usage_exit */
285 __attribute__((noreturn))
286 static void usage_qos_exit (const char *arg, int status) /* {{{ */
289 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
291 fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
293 " Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
295 " be Best Effort (BE, default PHB).\n"
296 " ef Expedited Forwarding (EF) PHB group (RFC 3246).\n"
297 " (low delay, low loss, low jitter)\n"
298 " va Voice Admit (VA) DSCP (RFC 5865).\n"
299 " (capacity-admitted traffic)\n"
300 " af[1-4][1-3] Assured Forwarding (AF) PHB group (RFC 2597).\n"
301 " For example: \"af12\" (class 1, precedence 2)\n"
302 " cs[0-7] Class Selector (CS) PHB group (RFC 2474).\n"
303 " For example: \"cs1\" (priority traffic)\n"
305 " Type of Service (IPv4, RFC 1349, obsolete)\n"
307 " lowdelay (%#04x) minimize delay\n"
308 " throughput (%#04x) maximize throughput\n"
309 " reliability (%#04x) maximize reliability\n"
310 " mincost (%#04x) minimize monetary cost\n"
312 " Specify manually\n"
314 " 0x00 - 0xff Hexadecimal numeric specification.\n"
315 " 0 - 255 Decimal numeric specification.\n"
317 (unsigned int) IPTOS_LOWDELAY,
318 (unsigned int) IPTOS_THROUGHPUT,
319 (unsigned int) IPTOS_RELIABILITY,
320 (unsigned int) IPTOS_MINCOST);
323 } /* }}} void usage_qos_exit */
325 static int set_opt_send_qos (const char *opt) /* {{{ */
330 if (strcasecmp ("help", opt) == 0)
331 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
332 /* DiffServ (RFC 2474): */
333 /* - Best effort (BE) */
334 else if (strcasecmp ("be", opt) == 0)
336 /* - Expedited Forwarding (EF, RFC 3246) */
337 else if (strcasecmp ("ef", opt) == 0)
338 opt_send_qos = 0xB8; /* == 0x2E << 2 */
339 /* - Voice Admit (VA, RFC 5865) */
340 else if (strcasecmp ("va", opt) == 0)
341 opt_send_qos = 0xB0; /* == 0x2D << 2 */
342 /* - Assured Forwarding (AF, RFC 2597) */
343 else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
344 && (strlen (opt) == 4))
350 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
353 else if (opt[2] == '2')
355 else if (opt[2] == '3')
357 else if (opt[2] == '4')
360 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
362 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
365 else if (opt[3] == '2')
367 else if (opt[3] == '3')
370 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
372 dscp = (8 * class) + (2 * prec);
373 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
374 opt_send_qos = dscp << 2;
376 /* - Class Selector (CS) */
377 else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
378 && (strlen (opt) == 3))
382 if ((opt[2] < '0') || (opt[2] > '7'))
383 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
385 /* Not exactly legal by the C standard, but I don't know of any
386 * system not supporting this hack. */
387 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
388 opt_send_qos = class << 5;
390 /* Type of Service (RFC 1349) */
391 else if (strcasecmp ("lowdelay", opt) == 0)
392 opt_send_qos = IPTOS_LOWDELAY;
393 else if (strcasecmp ("throughput", opt) == 0)
394 opt_send_qos = IPTOS_THROUGHPUT;
395 else if (strcasecmp ("reliability", opt) == 0)
396 opt_send_qos = IPTOS_RELIABILITY;
397 else if (strcasecmp ("mincost", opt) == 0)
398 opt_send_qos = IPTOS_MINCOST;
407 value = strtoul (opt, &endptr, /* base = */ 0);
408 if ((errno != 0) || (endptr == opt)
409 || (endptr == NULL) || (*endptr != 0)
411 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
413 opt_send_qos = (uint8_t) value;
417 } /* }}} int set_opt_send_qos */
419 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
431 case 0x00: dscp_str = "be"; break;
432 case 0x2e: dscp_str = "ef"; break;
433 case 0x2d: dscp_str = "va"; break;
434 case 0x0a: dscp_str = "af11"; break;
435 case 0x0c: dscp_str = "af12"; break;
436 case 0x0e: dscp_str = "af13"; break;
437 case 0x12: dscp_str = "af21"; break;
438 case 0x14: dscp_str = "af22"; break;
439 case 0x16: dscp_str = "af23"; break;
440 case 0x1a: dscp_str = "af31"; break;
441 case 0x1c: dscp_str = "af32"; break;
442 case 0x1e: dscp_str = "af33"; break;
443 case 0x22: dscp_str = "af41"; break;
444 case 0x24: dscp_str = "af42"; break;
445 case 0x26: dscp_str = "af43"; break;
446 case 0x08: dscp_str = "cs1"; break;
447 case 0x10: dscp_str = "cs2"; break;
448 case 0x18: dscp_str = "cs3"; break;
449 case 0x20: dscp_str = "cs4"; break;
450 case 0x28: dscp_str = "cs5"; break;
451 case 0x30: dscp_str = "cs6"; break;
452 case 0x38: dscp_str = "cs7"; break;
453 default: dscp_str = NULL;
458 case 0x01: ecn_str = ",ecn(1)"; break;
459 case 0x02: ecn_str = ",ecn(0)"; break;
460 case 0x03: ecn_str = ",ce"; break;
461 default: ecn_str = "";
464 if (dscp_str == NULL)
465 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
467 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
468 buffer[buffer_size - 1] = 0;
471 } /* }}} char *format_qos */
473 static int read_options (int argc, char **argv) /* {{{ */
479 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:");
488 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
494 new_count = atoi (optarg);
496 opt_count = new_count;
498 fprintf(stderr, "Ignoring invalid count: %s\n",
505 if (opt_filename != NULL)
507 opt_filename = strdup (optarg);
514 new_interval = atof (optarg);
515 if (new_interval < 0.001)
516 fprintf (stderr, "Ignoring invalid interval: %s\n",
519 opt_interval = new_interval;
524 if (opt_srcaddr != NULL)
526 opt_srcaddr = strdup (optarg);
537 new_send_ttl = atoi (optarg);
538 if ((new_send_ttl > 0) && (new_send_ttl < 256))
539 opt_send_ttl = new_send_ttl;
541 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
547 set_opt_send_qos (optarg);
551 usage_exit (argv[0], 0);
554 usage_exit (argv[0], 1);
559 } /* }}} read_options */
561 static void time_normalize (struct timespec *ts) /* {{{ */
563 while (ts->tv_nsec < 0)
572 ts->tv_nsec += 1000000000;
575 while (ts->tv_nsec >= 1000000000)
578 ts->tv_nsec -= 1000000000;
580 } /* }}} void time_normalize */
582 static void time_calc (struct timespec *ts_dest, /* {{{ */
583 const struct timespec *ts_int,
584 const struct timeval *tv_begin,
585 const struct timeval *tv_end)
587 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
588 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
589 time_normalize (ts_dest);
591 /* Assure that `(begin + interval) > end'.
592 * This may seem overly complicated, but `tv_sec' is of type `time_t'
593 * which may be `unsigned. *sigh* */
594 if ((tv_end->tv_sec > ts_dest->tv_sec)
595 || ((tv_end->tv_sec == ts_dest->tv_sec)
596 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
599 ts_dest->tv_nsec = 0;
603 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
604 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
605 time_normalize (ts_dest);
606 } /* }}} void time_calc */
609 static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter) /* {{{ */
611 double latency = -1.0;
612 size_t buffer_len = sizeof (latency);
614 getmaxyx(ctx->window, maxx, maxx);
616 ping_iterator_get_info (iter, PING_INFO_LATENCY,
617 &latency, &buffer_len);
619 unsigned int sequence = 0;
620 buffer_len = sizeof (sequence);
621 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
622 &sequence, &buffer_len);
625 if ((ctx == NULL) || (ctx->window == NULL))
628 /* werase (ctx->window); */
630 box (ctx->window, 0, 0);
631 wattron (ctx->window, A_BOLD);
632 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
634 wattroff (ctx->window, A_BOLD);
635 wprintw (ctx->window, "ping statistics ");
636 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
637 "%i packets transmitted, %i received, %.2f%% packet "
639 ctx->req_sent, ctx->req_rcvd,
640 context_get_packet_loss (ctx),
642 if (ctx->req_rcvd != 0)
647 average = context_get_average (ctx);
648 deviation = context_get_stddev (ctx);
650 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
651 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
660 if (has_colors () == TRUE)
662 int color = OPING_GREEN_HIST;
666 ratio = latency / PING_DEF_TTL;
671 color = OPING_RED_HIST;
673 else if (ratio > 1/3.0) {
674 color = OPING_YELLOW_HIST;
676 index = (int) (ratio * BARS_LEN * 3); /* 3 colors */
677 /* HOST_PRINTF ("%%r%f-ia%d-", ratio, index); */
678 index = index % (BARS_LEN-1);
679 /* HOST_PRINTF ("im%d-", index); */
681 index = 0; /* safety check */
683 if (index >= BARS_LEN) {
684 index = BARS_LEN -1; /* safety check */
686 wattron (ctx->window, COLOR_PAIR(color));
687 mvwprintw (ctx->window,
689 /* x = */ (1 + sequence) % maxx,
691 wattroff (ctx->window, COLOR_PAIR(color));
698 wattron (ctx->window, COLOR_PAIR(OPING_RED) | A_BOLD);
699 mvwprintw (ctx->window,
701 /* x = */ (1 + sequence) % maxx,
703 wattroff (ctx->window, COLOR_PAIR(OPING_RED) | A_BOLD);
705 wrefresh (ctx->window);
708 } /* }}} int update_stats_from_context */
710 static int on_resize (pingobj_t *ping) /* {{{ */
712 pingobj_iter_t *iter;
717 getmaxyx (stdscr, height, width);
718 if ((height < 1) || (width < 1))
721 main_win_height = height - (5 * host_num);
722 wresize (main_win, main_win_height, /* width = */ width);
723 /* Allow scrolling */
724 scrollok (main_win, TRUE);
725 /* wsetscrreg (main_win, 0, main_win_height - 1); */
726 /* Allow hardware accelerated scrolling. */
727 idlok (main_win, TRUE);
730 for (iter = ping_iterator_get (ping);
732 iter = ping_iterator_next (iter))
734 ping_context_t *context;
736 context = ping_iterator_get_context (iter);
740 if (context->window != NULL)
742 delwin (context->window);
743 context->window = NULL;
745 context->window = newwin (/* height = */ 5,
747 /* y = */ main_win_height + (5 * context->index),
754 static int check_resize (pingobj_t *ping) /* {{{ */
760 int key = wgetch (stdscr);
763 else if (key == KEY_RESIZE)
768 return (on_resize (ping));
771 } /* }}} int check_resize */
773 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
775 pingobj_iter_t *iter;
783 nodelay (stdscr, TRUE);
785 getmaxyx (stdscr, height, width);
786 if ((height < 1) || (width < 1))
789 if (has_colors () == TRUE)
792 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
793 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
794 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
795 init_pair (OPING_GREEN_HIST, COLOR_GREEN, COLOR_BLACK);
796 init_pair (OPING_YELLOW_HIST, COLOR_YELLOW, COLOR_GREEN);
797 init_pair (OPING_RED_HIST, COLOR_RED, COLOR_YELLOW);
800 main_win_height = height - (5 * host_num);
801 main_win = newwin (/* height = */ main_win_height,
803 /* y = */ 0, /* x = */ 0);
804 /* Allow scrolling */
805 scrollok (main_win, TRUE);
806 /* wsetscrreg (main_win, 0, main_win_height - 1); */
807 /* Allow hardware accelerated scrolling. */
808 idlok (main_win, TRUE);
809 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
812 for (iter = ping_iterator_get (ping);
814 iter = ping_iterator_next (iter))
816 ping_context_t *context;
818 context = ping_iterator_get_context (iter);
822 if (context->window != NULL)
824 delwin (context->window);
825 context->window = NULL;
827 context->window = newwin (/* height = */ 5,
829 /* y = */ main_win_height + (5 * context->index),
834 /* Don't know what good this does exactly, but without this code
835 * "check_resize" will be called right after startup and *somehow*
836 * this leads to display errors. If we purge all initial characters
837 * here, the problem goes away. "wgetch" is non-blocking due to
838 * "nodelay" (see above). */
839 while (wgetch (stdscr) != ERR)
841 /* eat up characters */;
845 } /* }}} int pre_loop_hook */
847 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
849 return (check_resize (ping));
850 } /* }}} int pre_sleep_hook */
852 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
854 return (check_resize (ping));
855 } /* }}} int pre_sleep_hook */
856 #else /* if !USE_NCURSES */
857 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
859 pingobj_iter_t *iter;
861 for (iter = ping_iterator_get (ping);
863 iter = ping_iterator_next (iter))
868 ctx = ping_iterator_get_context (iter);
873 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
875 printf ("PING %s (%s) %zu bytes of data.\n",
876 ctx->host, ctx->addr, buffer_size);
880 } /* }}} int pre_loop_hook */
882 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
887 } /* }}} int pre_sleep_hook */
889 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
892 } /* }}} int post_sleep_hook */
895 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
896 __attribute__((unused)) int index)
899 unsigned int sequence;
902 char recv_qos_str[16];
905 ping_context_t *context;
908 buffer_len = sizeof (latency);
909 ping_iterator_get_info (iter, PING_INFO_LATENCY,
910 &latency, &buffer_len);
913 buffer_len = sizeof (sequence);
914 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
915 &sequence, &buffer_len);
918 buffer_len = sizeof (recv_ttl);
919 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
920 &recv_ttl, &buffer_len);
923 buffer_len = sizeof (recv_qos);
924 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
925 &recv_qos, &buffer_len);
928 ping_iterator_get_info (iter, PING_INFO_DATA,
931 context = (ping_context_t *) ping_iterator_get_context (iter);
934 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
936 # define HOST_PRINTF(...) printf(__VA_ARGS__)
943 context->latency_total += latency;
944 context->latency_total_square += (latency * latency);
946 if ((context->latency_max < 0.0) || (context->latency_max < latency))
947 context->latency_max = latency;
948 if ((context->latency_min < 0.0) || (context->latency_min > latency))
949 context->latency_min = latency;
952 if (has_colors () == TRUE)
954 int color = OPING_GREEN;
955 double average = context_get_average (context);
956 double stddev = context_get_stddev (context);
958 if ((latency < (average - (2 * stddev)))
959 || (latency > (average + (2 * stddev))))
961 else if ((latency < (average - stddev))
962 || (latency > (average + stddev)))
963 color = OPING_YELLOW;
965 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
966 data_len, context->host, context->addr,
968 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
969 if ((recv_qos != 0) || (opt_send_qos != 0))
971 HOST_PRINTF ("qos=%s ",
972 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
974 HOST_PRINTF ("time=");
975 wattron (main_win, COLOR_PAIR(color));
976 HOST_PRINTF ("%.2f", latency);
977 wattroff (main_win, COLOR_PAIR(color));
978 HOST_PRINTF (" ms\n");
983 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
985 context->host, context->addr,
987 if ((recv_qos != 0) || (opt_send_qos != 0))
989 HOST_PRINTF ("qos=%s ",
990 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
992 HOST_PRINTF ("time=%.2f ms\n", latency);
1000 if (has_colors () == TRUE)
1002 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
1003 context->host, context->addr,
1005 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1006 HOST_PRINTF ("timeout");
1007 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1013 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
1014 context->host, context->addr,
1022 update_stats_from_context (context, iter);
1023 wrefresh (main_win);
1025 } /* }}} void update_host_hook */
1027 static int post_loop_hook (pingobj_t *ping) /* {{{ */
1029 pingobj_iter_t *iter;
1035 for (iter = ping_iterator_get (ping);
1037 iter = ping_iterator_next (iter))
1039 ping_context_t *context;
1041 context = ping_iterator_get_context (iter);
1043 printf ("\n--- %s ping statistics ---\n"
1044 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
1045 context->host, context->req_sent, context->req_rcvd,
1046 context_get_packet_loss (context),
1047 context->latency_total);
1049 if (context->req_rcvd != 0)
1054 average = context_get_average (context);
1055 deviation = context_get_stddev (context);
1057 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
1058 context->latency_min,
1060 context->latency_max,
1064 ping_iterator_set_context (iter, NULL);
1065 context_destroy (context);
1069 } /* }}} int post_loop_hook */
1071 int main (int argc, char **argv) /* {{{ */
1074 pingobj_iter_t *iter;
1076 struct sigaction sigint_action;
1078 struct timeval tv_begin;
1079 struct timeval tv_end;
1080 struct timespec ts_wait;
1081 struct timespec ts_int;
1086 #if _POSIX_SAVED_IDS
1087 uid_t saved_set_uid;
1089 /* Save the old effective user id */
1090 saved_set_uid = geteuid ();
1091 /* Set the effective user ID to the real user ID without changing the
1092 * saved set-user ID */
1093 status = seteuid (getuid ());
1096 fprintf (stderr, "Temporarily dropping privileges "
1097 "failed: %s\n", strerror (errno));
1098 exit (EXIT_FAILURE);
1102 setlocale(LC_ALL, "");
1103 optind = read_options (argc, argv);
1105 #if !_POSIX_SAVED_IDS
1106 /* Cannot temporarily drop privileges -> reject every file but "-". */
1107 if ((opt_filename != NULL)
1108 && (strcmp ("-", opt_filename) != 0)
1109 && (getuid () != geteuid ()))
1111 fprintf (stderr, "Your real and effective user IDs don't "
1112 "match. Reading from a file (option '-f')\n"
1113 "is therefore too risky. You can still read "
1114 "from STDIN using '-f -' if you like.\n"
1116 exit (EXIT_FAILURE);
1120 if ((optind >= argc) && (opt_filename == NULL)) {
1121 usage_exit (argv[0], 1);
1124 if ((ping = ping_construct ()) == NULL)
1126 fprintf (stderr, "ping_construct failed\n");
1130 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1132 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1133 opt_send_ttl, ping_get_error (ping));
1136 if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1138 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1139 opt_send_qos, ping_get_error (ping));
1146 temp_nsec = modf (opt_interval, &temp_sec);
1147 ts_int.tv_sec = (time_t) temp_sec;
1148 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1150 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1153 if (opt_addrfamily != PING_DEF_AF)
1154 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1156 if (opt_srcaddr != NULL)
1158 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1160 fprintf (stderr, "Setting source address failed: %s\n",
1161 ping_get_error (ping));
1165 if (opt_device != NULL)
1167 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1169 fprintf (stderr, "Setting device failed: %s\n",
1170 ping_get_error (ping));
1174 if (opt_filename != NULL)
1180 if (strcmp (opt_filename, "-") == 0)
1182 infile = fdopen(0, "r");
1184 infile = fopen(opt_filename, "r");
1188 fprintf (stderr, "Opening %s failed: %s\n",
1189 (strcmp (opt_filename, "-") == 0)
1190 ? "STDIN" : opt_filename,
1195 #if _POSIX_SAVED_IDS
1196 /* Regain privileges */
1197 status = seteuid (saved_set_uid);
1200 fprintf (stderr, "Temporarily re-gaining privileges "
1201 "failed: %s\n", strerror (errno));
1202 exit (EXIT_FAILURE);
1206 while (fgets(line, sizeof(line), infile))
1208 /* Strip whitespace */
1209 if (sscanf(line, "%s", host) != 1)
1212 if ((host[0] == 0) || (host[0] == '#'))
1215 if (ping_host_add(ping, host) < 0)
1217 const char *errmsg = ping_get_error (ping);
1219 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1228 #if _POSIX_SAVED_IDS
1229 /* Drop privileges */
1230 status = seteuid (getuid ());
1233 fprintf (stderr, "Temporarily dropping privileges "
1234 "failed: %s\n", strerror (errno));
1235 exit (EXIT_FAILURE);
1242 #if _POSIX_SAVED_IDS
1243 /* Regain privileges */
1244 status = seteuid (saved_set_uid);
1247 fprintf (stderr, "Temporarily re-gaining privileges "
1248 "failed: %s\n", strerror (errno));
1249 exit (EXIT_FAILURE);
1253 for (i = optind; i < argc; i++)
1255 if (ping_host_add (ping, argv[i]) < 0)
1257 const char *errmsg = ping_get_error (ping);
1259 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1268 /* Permanently drop root privileges if we're setuid-root. */
1269 status = setuid (getuid ());
1272 fprintf (stderr, "Dropping privileges failed: %s\n",
1274 exit (EXIT_FAILURE);
1277 #if _POSIX_SAVED_IDS
1278 saved_set_uid = (uid_t) -1;
1281 ping_initialize_contexts (ping);
1286 memset (&sigint_action, '\0', sizeof (sigint_action));
1287 sigint_action.sa_handler = sigint_handler;
1288 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1290 perror ("sigaction");
1294 pre_loop_hook (ping);
1296 while (opt_count != 0)
1301 if (gettimeofday (&tv_begin, NULL) < 0)
1303 perror ("gettimeofday");
1307 if (ping_send (ping) < 0)
1309 fprintf (stderr, "ping_send failed: %s\n",
1310 ping_get_error (ping));
1315 for (iter = ping_iterator_get (ping);
1317 iter = ping_iterator_next (iter))
1319 update_host_hook (iter, index);
1323 pre_sleep_hook (ping);
1325 /* Don't sleep in the last iteration */
1329 if (gettimeofday (&tv_end, NULL) < 0)
1331 perror ("gettimeofday");
1335 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1337 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1338 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1342 perror ("nanosleep");
1345 else if (opt_count == 0)
1352 post_sleep_hook (ping);
1356 } /* while (opt_count != 0) */
1358 post_loop_hook (ping);
1360 ping_destroy (ping);
1363 } /* }}} int main */
1365 /* vim: set fdm=marker : */