Code

Merge branch 'liboping-1.2'
[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;
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 char   *opt_device     = NULL;
77 static char   *opt_filename   = NULL;
78 static int     opt_count      = -1;
79 static int     opt_send_ttl   = 64;
81 static void sigint_handler (int signal)
82 {
83         /* Make compiler happy */
84         signal = 0;
85         /* Exit the loop */
86         opt_count = 0;
87 }
89 static ping_context_t *context_create (void)
90 {
91         ping_context_t *ret;
93         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
94                 return (NULL);
96         memset (ret, '\0', sizeof (ping_context_t));
98         ret->latency_min   = -1.0;
99         ret->latency_max   = -1.0;
100         ret->latency_total = 0.0;
101         ret->latency_total_square = 0.0;
103         return (ret);
106 static void context_destroy (ping_context_t *context)
108         free (context);
111 static void usage_exit (const char *name, int status)
113         int name_length;
115         name_length = (int) strlen (name);
117         fprintf (stderr, "Usage: %s [OPTIONS] "
118                                 "-f filename | host [host [host ...]]\n"
120                         "\nAvailable options:\n"
121                         "  -4|-6        force the use of IPv4 or IPv6\n"
122                         "  -c count     number of ICMP packets to send\n"
123                         "  -i interval  interval with which to send ICMP packets\n"
124                         "  -t ttl       time to live for each ICMP packet\n"
125                         "  -I srcaddr   source address\n"
126                         "  -D device    outgoing interface name\n"
127                         "  -f filename  filename to read hosts from\n"
129                         "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
130                         "by Florian octo Forster <octo@verplant.org>\n"
131                         "for contributions see `AUTHORS'\n",
132                         name);
133         exit (status);
136 static int read_options (int argc, char **argv)
138         int optchar;
140         while (1)
141         {
142                 optchar = getopt (argc, argv, "46c:hi:I:t:f:D:");
144                 if (optchar == -1)
145                         break;
147                 switch (optchar)
148                 {
149                         case '4':
150                         case '6':
151                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
152                                 break;
154                         case 'c':
155                                 {
156                                         int new_count;
157                                         new_count = atoi (optarg);
158                                         if (new_count > 0)
159                                                 opt_count = new_count;
160                                         else
161                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
162                                                                 optarg);
163                                 }
164                                 break;
166                         case 'f':
167                                 {
168                                         if (opt_filename != NULL)
169                                                 free (opt_filename);
170                                         opt_filename = strdup (optarg);
171                                 }
172                                 break;
174                         case 'i':
175                                 {
176                                         double new_interval;
177                                         new_interval = atof (optarg);
178                                         if (new_interval < 0.001)
179                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
180                                                                 optarg);
181                                         else
182                                                 opt_interval = new_interval;
183                                 }
184                                 break;
185                         case 'I':
186                                 {
187                                         if (opt_srcaddr != NULL)
188                                                 free (opt_srcaddr);
189                                         opt_srcaddr = strdup (optarg);
190                                 }
191                                 break;
193                         case 'D':
194                                 opt_device = optarg;
195                                 break;
197                         case 't':
198                         {
199                                 int new_send_ttl;
200                                 new_send_ttl = atoi (optarg);
201                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
202                                         opt_send_ttl = new_send_ttl;
203                                 else
204                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
205                                                         optarg);
206                                 break;
207                         }
209                         case 'h':
210                                 usage_exit (argv[0], 0);
211                                 break;
212                         default:
213                                 usage_exit (argv[0], 1);
214                 }
215         }
217         return (optind);
220 static void print_host (pingobj_iter_t *iter)
222         double          latency;
223         unsigned int    sequence;
224         int             recv_ttl;
225         size_t          buffer_len;
226         size_t          data_len;
227         ping_context_t *context;
229         latency = -1.0;
230         buffer_len = sizeof (latency);
231         ping_iterator_get_info (iter, PING_INFO_LATENCY,
232                         &latency, &buffer_len);
234         sequence = 0;
235         buffer_len = sizeof (sequence);
236         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
237                         &sequence, &buffer_len);
239         recv_ttl = -1;
240         buffer_len = sizeof (recv_ttl);
241         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
242                         &recv_ttl, &buffer_len);
244         data_len = 0;
245         ping_iterator_get_info (iter, PING_INFO_DATA,
246                         NULL, &data_len);
248         context = (ping_context_t *) ping_iterator_get_context (iter);
250         context->req_sent++;
251         if (latency > 0.0)
252         {
253                 context->req_rcvd++;
254                 context->latency_total += latency;
255                 context->latency_total_square += (latency * latency);
257                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
258                         context->latency_max = latency;
259                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
260                         context->latency_min = latency;
262                 printf ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i time=%.2f ms\n",
263                                 data_len,
264                                 context->host, context->addr,
265                                 sequence, recv_ttl, latency);
266         }
267         else
268         {
269                 printf ("echo reply from %s (%s): icmp_seq=%u timeout\n",
270                                 context->host, context->addr,
271                                 sequence);
272         }
275 static void time_normalize (struct timespec *ts)
277         while (ts->tv_nsec < 0)
278         {
279                 if (ts->tv_sec == 0)
280                 {
281                         ts->tv_nsec = 0;
282                         return;
283                 }
285                 ts->tv_sec  -= 1;
286                 ts->tv_nsec += 1000000000;
287         }
289         while (ts->tv_nsec >= 1000000000)
290         {
291                 ts->tv_sec  += 1;
292                 ts->tv_nsec -= 1000000000;
293         }
296 static void time_calc (struct timespec *ts_dest,
297                 const struct timespec *ts_int,
298                 const struct timeval  *tv_begin,
299                 const struct timeval  *tv_end)
301         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
302         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
303         time_normalize (ts_dest);
305         /* Assure that `(begin + interval) > end'.
306          * This may seem overly complicated, but `tv_sec' is of type `time_t'
307          * which may be `unsigned. *sigh* */
308         if ((tv_end->tv_sec > ts_dest->tv_sec)
309                         || ((tv_end->tv_sec == ts_dest->tv_sec)
310                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
311         {
312                 ts_dest->tv_sec  = 0;
313                 ts_dest->tv_nsec = 0;
314                 return;
315         }
317         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
318         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
319         time_normalize (ts_dest);
322 int main (int argc, char **argv)
324         pingobj_t      *ping;
325         pingobj_iter_t *iter;
327         struct sigaction sigint_action;
329         struct timeval  tv_begin;
330         struct timeval  tv_end;
331         struct timespec ts_wait;
332         struct timespec ts_int;
334         int optind;
335         int i;
337         optind = read_options (argc, argv);
339         if ((optind >= argc) && (opt_filename == NULL)) {
340                 usage_exit (argv[0], 1);
341         }
343         if (geteuid () != 0)
344         {
345                 fprintf (stderr, "Need superuser privileges to open a RAW socket. Sorry.\n");
346                 return (1);
347         }
349         if ((ping = ping_construct ()) == NULL)
350         {
351                 fprintf (stderr, "ping_construct failed\n");
352                 return (1);
353         }
355         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
356         {
357                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
358                                 opt_send_ttl, ping_get_error (ping));
359         }
361         {
362                 double temp_sec;
363                 double temp_nsec;
365                 temp_nsec = modf (opt_interval, &temp_sec);
366                 ts_int.tv_sec  = (time_t) temp_sec;
367                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
369                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
370         }
372         if (opt_addrfamily != PING_DEF_AF)
373                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
375         if (opt_srcaddr != NULL)
376         {
377                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
378                 {
379                         fprintf (stderr, "Setting source address failed: %s\n",
380                                         ping_get_error (ping));
381                 }
382         }
384         if (opt_device != NULL)
385         {
386                 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
387                 {
388                         fprintf (stderr, "Setting device failed: %s\n",
389                                         ping_get_error (ping));
390                 }
391         }
393         if (opt_filename != NULL)
394         {
395                 FILE *infile;
396                 char line[256];
397                 char host[256];
399                 if (strcmp (opt_filename, "-") == 0)
400                         /* Open STDIN */
401                         infile = fdopen(0, "r");
402                 else
403                         infile = fopen(opt_filename, "r");
405                 if (infile == NULL)
406                 {
407                         fprintf (stderr, "Opening %s failed: %s\n",
408                                         (strcmp (opt_filename, "-") == 0)
409                                         ? "STDIN" : opt_filename,
410                                         strerror(errno));
411                         return (1);
412                 }
414                 while (fgets(line, sizeof(line), infile))
415                 {
416                         /* Strip whitespace */
417                         if (sscanf(line, "%s", host) != 1)
418                                 continue;
420                         if ((host[0] == 0) || (host[0] == '#'))
421                                 continue;
423                         if (ping_host_add(ping, host) < 0)
424                         {
425                                 const char *errmsg = ping_get_error (ping);
427                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
428                                 continue;
429                         }
430                 }
432                 fclose(infile);
433         }
435         for (i = optind; i < argc; i++)
436         {
437                 if (ping_host_add (ping, argv[i]) < 0)
438                 {
439                         const char *errmsg = ping_get_error (ping);
441                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
442                         continue;
443                 }
444         }
446         /* Drop root privileges if we're setuid-root. */
447         setuid (getuid ());
449         i = 0;
450         for (iter = ping_iterator_get (ping);
451                         iter != NULL;
452                         iter = ping_iterator_next (iter))
453         {
454                 ping_context_t *context;
455                 size_t buffer_size;
457                 context = context_create ();
459                 buffer_size = sizeof (context->host);
460                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
462                 buffer_size = sizeof (context->addr);
463                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
465                 buffer_size = 0;
466                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
468                 printf ("PING %s (%s) %zu bytes of data.\n",
469                                 context->host, context->addr, buffer_size);
471                 ping_iterator_set_context (iter, (void *) context);
473                 i++;
474         }
476         if (i == 0)
477                 return (1);
479         memset (&sigint_action, '\0', sizeof (sigint_action));
480         sigint_action.sa_handler = sigint_handler;
481         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
482         {
483                 perror ("sigaction");
484                 return (1);
485         }
487         while (opt_count != 0)
488         {
489                 int status;
491                 if (gettimeofday (&tv_begin, NULL) < 0)
492                 {
493                         perror ("gettimeofday");
494                         return (1);
495                 }
497                 if (ping_send (ping) < 0)
498                 {
499                         fprintf (stderr, "ping_send failed: %s\n",
500                                         ping_get_error (ping));
501                         return (1);
502                 }
504                 for (iter = ping_iterator_get (ping);
505                                 iter != NULL;
506                                 iter = ping_iterator_next (iter))
507                 {
508                         print_host (iter);
509                 }
510                 fflush (stdout);
512                 /* Don't sleep in the last iteration */
513                 if (opt_count == 1)
514                         break;
516                 if (gettimeofday (&tv_end, NULL) < 0)
517                 {
518                         perror ("gettimeofday");
519                         return (1);
520                 }
522                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
524                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
525                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
526                 {
527                         if (errno != EINTR)
528                         {
529                                 perror ("nanosleep");
530                                 break;
531                         }
532                         else if (opt_count == 0)
533                         {
534                                 /* sigint */
535                                 break;
536                         }
537                 }
539                 if (opt_count > 0)
540                         opt_count--;
541         } /* while (opt_count != 0) */
543         for (iter = ping_iterator_get (ping);
544                         iter != NULL;
545                         iter = ping_iterator_next (iter))
546         {
547                 ping_context_t *context;
549                 context = ping_iterator_get_context (iter);
551                 printf ("\n--- %s ping statistics ---\n"
552                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
553                                 context->host, context->req_sent, context->req_rcvd,
554                                 100.0 * (context->req_sent - context->req_rcvd) / ((double) context->req_sent),
555                                 context->latency_total);
557                 if (context->req_rcvd != 0)
558                 {
559                         double num_total;
560                         double average;
561                         double deviation;
563                         num_total = (double) context->req_rcvd;
565                         average = context->latency_total / num_total;
566                         deviation = sqrt (((num_total * context->latency_total_square) - (context->latency_total * context->latency_total))
567                                         / (num_total * (num_total - 1.0)));
569                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
570                                         context->latency_min,
571                                         average,
572                                         context->latency_max,
573                                         deviation);
574                 }
576                 ping_iterator_set_context (iter, NULL);
577                 context_destroy (context);
578         }
580         ping_destroy (ping);
582         return (0);