Code

src/oping.c: Allow shorter interval settings.
[liboping.git] / src / oping.c
1 /**
2  * Object oriented C module to send ICMP and ICMPv6 `echo's.
3  * Copyright (C) 2006  Florian octo Forster <octo at verplant.org>
4  *
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
8  * applicable.
9  *
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.
14  *
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
18  */
20 #if HAVE_CONFIG_H
21 # include <config.h>
22 #endif
24 #if STDC_HEADERS
25 # include <stdlib.h>
26 # include <stdio.h>
27 # include <string.h>
28 # include <errno.h>
29 # include <assert.h>
30 #else
31 # error "You don't have the standard C99 header files installed"
32 #endif /* STDC_HEADERS */
34 #if HAVE_MATH_H
35 # include <math.h>
36 #endif
38 #if TIME_WITH_SYS_TIME
39 # include <sys/time.h>
40 # include <time.h>
41 #else
42 # if HAVE_SYS_TIME_H
43 #  include <sys/time.h>
44 # else
45 #  include <time.h>
46 # endif
47 #endif
49 #if HAVE_NETDB_H
50 # include <netdb.h> /* NI_MAXHOST */
51 #endif
53 #if HAVE_SIGNAL_H
54 # include <signal.h>
55 #endif
57 #include "oping.h"
59 typedef struct ping_context
60 {
61         char host[NI_MAXHOST];
62         char addr[NI_MAXHOST];
64         int req_sent;
65         int req_rcvd;
66         
67         double latency_min;
68         double latency_max;
69         double latency_total;
70         double latency_total_square;
71 } ping_context_t;
73 static double  opt_interval   = 1.0;
74 static int     opt_addrfamily = PING_DEF_AF;
75 static char   *opt_srcaddr    = NULL;
76 static int     opt_count      = -1;
78 static void sigint_handler (int signal)
79 {
80         /* Make compiler happy */
81         signal = 0;
82         /* Exit the loop */
83         opt_count = 0;
84 }
86 static ping_context_t *context_create (void)
87 {
88         ping_context_t *ret;
90         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
91                 return (NULL);
93         memset (ret, '\0', sizeof (ping_context_t));
95         ret->latency_min   = -1.0;
96         ret->latency_max   = -1.0;
97         ret->latency_total = 0.0;
98         ret->latency_total_square = 0.0;
100         return (ret);
103 static void context_destroy (ping_context_t *context)
105         free (context);
108 static void usage_exit (const char *name)
110         fprintf (stderr, "Usage: %s [-46] [-c count] [-i interval] host [host [host ...]]\n",
111                         name);
112         exit (1);
115 static int read_options (int argc, char **argv)
117         int optchar;
119         while (1)
120         {
121                 optchar = getopt (argc, argv, "46c:hi:I:");
123                 if (optchar == -1)
124                         break;
126                 switch (optchar)
127                 {
128                         case '4':
129                         case '6':
130                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
131                                 break;
133                         case 'c':
134                                 {
135                                         int new_count;
136                                         new_count = atoi (optarg);
137                                         if (new_count > 0)
138                                                 opt_count = new_count;
139                                 }
140                                 break;
142                         case 'i':
143                                 {
144                                         double new_interval;
145                                         new_interval = atof (optarg);
146                                         if (new_interval < 0.001)
147                                                 fprintf (stderr, "Ignoring invalid interval %g.\n",
148                                                                 new_interval);
149                                         else
150                                                 opt_interval = new_interval;
151                                 }
152                                 break;
153                         case 'I':
154                                 {
155                                         if (opt_srcaddr != NULL)
156                                                 free (opt_srcaddr);
157                                         opt_srcaddr = strdup (optarg);
158                                 }
159                                 break;
161                         case 'h':
162                         default:
163                                 usage_exit (argv[0]);
164                 }
165         }
167         return (optind);
170 static void print_host (pingobj_iter_t *iter)
172         double          latency;
173         unsigned int    sequence;
174         size_t          buffer_len;
175         size_t          data_len;
176         ping_context_t *context;
177         
178         buffer_len = sizeof (latency);
179         ping_iterator_get_info (iter, PING_INFO_LATENCY,
180                         &latency, &buffer_len);
182         buffer_len = sizeof (sequence);
183         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
184                         &sequence, &buffer_len);
186         data_len = 0;
187         ping_iterator_get_info (iter, PING_INFO_DATA,
188                         NULL, &data_len);
190         context = (ping_context_t *) ping_iterator_get_context (iter);
192         context->req_sent++;
193         if (latency > 0.0)
194         {
195                 context->req_rcvd++;
196                 context->latency_total += latency;
197                 context->latency_total_square += (latency * latency);
199                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
200                         context->latency_max = latency;
201                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
202                         context->latency_min = latency;
204                 printf ("%zu bytes from %s (%s): icmp_seq=%u time=%.2f ms\n",
205                                 data_len,
206                                 context->host, context->addr,
207                                 sequence, latency);
208         }
209         else
210         {
211                 printf ("echo reply from %s (%s): icmp_seq=%u timeout\n",
212                                 context->host, context->addr,
213                                 sequence);
214         }
217 static void time_normalize (struct timespec *ts)
219         while (ts->tv_nsec < 0)
220         {
221                 if (ts->tv_sec == 0)
222                 {
223                         ts->tv_nsec = 0;
224                         return;
225                 }
227                 ts->tv_sec  -= 1;
228                 ts->tv_nsec += 1000000000;
229         }
231         while (ts->tv_nsec >= 1000000000)
232         {
233                 ts->tv_sec  += 1;
234                 ts->tv_nsec -= 1000000000;
235         }
238 static void time_calc (struct timespec *ts_dest,
239                 const struct timespec *ts_int,
240                 const struct timeval  *tv_begin,
241                 const struct timeval  *tv_end)
243         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
244         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
245         time_normalize (ts_dest);
247         /* Assure that `(begin + interval) > end'.
248          * This may seem overly complicated, but `tv_sec' is of type `time_t'
249          * which may be `unsigned. *sigh* */
250         if ((tv_end->tv_sec > ts_dest->tv_sec)
251                         || ((tv_end->tv_sec == ts_dest->tv_sec)
252                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
253         {
254                 ts_dest->tv_sec  = 0;
255                 ts_dest->tv_nsec = 0;
256                 return;
257         }
259         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
260         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
261         time_normalize (ts_dest);
264 int main (int argc, char **argv)
266         pingobj_t      *ping;
267         pingobj_iter_t *iter;
269         struct sigaction sigint_action;
271         struct timeval  tv_begin;
272         struct timeval  tv_end;
273         struct timespec ts_wait;
274         struct timespec ts_int;
276         int optind;
277         int i;
279         optind = read_options (argc, argv);
281         if (optind >= argc)
282                 usage_exit (argv[0]);
284         if (geteuid () != 0)
285         {
286                 fprintf (stderr, "Need superuser privileges to open a RAW socket. Sorry.\n");
287                 return (1);
288         }
290         if ((ping = ping_construct ()) == NULL)
291         {
292                 fprintf (stderr, "ping_construct failed\n");
293                 return (1);
294         }
296         {
297                 double temp_sec;
298                 double temp_nsec;
300                 temp_nsec = modf (opt_interval, &temp_sec);
301                 ts_int.tv_sec  = (time_t) temp_sec;
302                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
304                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
305         }
307         if (opt_addrfamily != PING_DEF_AF)
308                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
310         if (opt_srcaddr != NULL)
311         {
312                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
313                 {
314                         fprintf (stderr, "Setting source address failed: %s\n",
315                                         ping_get_error (ping));
316                 }
317         }
319         for (i = optind; i < argc; i++)
320         {
321                 if (ping_host_add (ping, argv[i]) < 0)
322                 {
323                         const char *errmsg = ping_get_error (ping);
325                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
326                         continue;
327                 }
328         }
330         /* Drop root privileges if we're setuid-root. */
331         setuid (getuid ());
333         i = 0;
334         for (iter = ping_iterator_get (ping);
335                         iter != NULL;
336                         iter = ping_iterator_next (iter))
337         {
338                 ping_context_t *context;
339                 size_t buffer_size;
341                 context = context_create ();
343                 buffer_size = sizeof (context->host);
344                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
346                 buffer_size = sizeof (context->addr);
347                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
349                 buffer_size = 0;
350                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
352                 printf ("PING %s (%s) %zu bytes of data.\n",
353                                 context->host, context->addr, buffer_size);
355                 ping_iterator_set_context (iter, (void *) context);
357                 i++;
358         }
360         if (i == 0)
361                 return (1);
363         memset (&sigint_action, '\0', sizeof (sigint_action));
364         sigint_action.sa_handler = sigint_handler;
365         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
366         {
367                 perror ("sigaction");
368                 return (1);
369         }
371         while (opt_count != 0)
372         {
373                 int status;
375                 if (gettimeofday (&tv_begin, NULL) < 0)
376                 {
377                         perror ("gettimeofday");
378                         return (1);
379                 }
381                 if (ping_send (ping) < 0)
382                 {
383                         fprintf (stderr, "ping_send failed: %s\n",
384                                         ping_get_error (ping));
385                         return (1);
386                 }
388                 for (iter = ping_iterator_get (ping);
389                                 iter != NULL;
390                                 iter = ping_iterator_next (iter))
391                 {
392                         print_host (iter);
393                 }
394                 fflush (stdout);
396                 /* Don't sleep in the last iteration */
397                 if (opt_count == 1)
398                         break;
400                 if (gettimeofday (&tv_end, NULL) < 0)
401                 {
402                         perror ("gettimeofday");
403                         return (1);
404                 }
406                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
408                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
409                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
410                 {
411                         if (errno != EINTR)
412                         {
413                                 perror ("nanosleep");
414                                 break;
415                         }
416                         else if (opt_count == 0)
417                         {
418                                 /* sigint */
419                                 break;
420                         }
421                 }
423                 if (opt_count > 0)
424                         opt_count--;
425         } /* while (opt_count != 0) */
427         for (iter = ping_iterator_get (ping);
428                         iter != NULL;
429                         iter = ping_iterator_next (iter))
430         {
431                 ping_context_t *context;
433                 context = ping_iterator_get_context (iter);
435                 printf ("\n--- %s ping statistics ---\n"
436                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
437                                 context->host, context->req_sent, context->req_rcvd,
438                                 100.0 * (context->req_sent - context->req_rcvd) / ((double) context->req_sent),
439                                 context->latency_total);
441                 if (context->req_rcvd != 0)
442                 {
443                         double num_total;
444                         double average;
445                         double deviation;
447                         num_total = (double) context->req_rcvd;
449                         average = context->latency_total / num_total;
450                         deviation = sqrt (((num_total * context->latency_total_square) - (context->latency_total * context->latency_total))
451                                         / (num_total * (num_total - 1.0)));
453                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
454                                         context->latency_min,
455                                         average,
456                                         context->latency_max,
457                                         deviation);
458                 }
460                 ping_iterator_set_context (iter, NULL);
461                 context_destroy (context);
462         }
464         ping_destroy (ping);
466         return (0);