Code

src/oping.c: Exit successfully when using the -h option.
[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_filename   = NULL;
77 static int     opt_count      = -1;
78 static int     opt_send_ttl   = 64;
80 static void sigint_handler (int signal)
81 {
82         /* Make compiler happy */
83         signal = 0;
84         /* Exit the loop */
85         opt_count = 0;
86 }
88 static ping_context_t *context_create (void)
89 {
90         ping_context_t *ret;
92         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
93                 return (NULL);
95         memset (ret, '\0', sizeof (ping_context_t));
97         ret->latency_min   = -1.0;
98         ret->latency_max   = -1.0;
99         ret->latency_total = 0.0;
100         ret->latency_total_square = 0.0;
102         return (ret);
105 static void context_destroy (ping_context_t *context)
107         free (context);
110 static void usage_exit (const char *name, int status)
112         int name_length;
114         name_length = (int) strlen (name);
116         fprintf (stderr, "Usage: %s [OPTIONS] "
117                                 "-f filename | host [host [host ...]]\n"
119                         "\nAvailable options:\n"
120                         "  -4|-6        force the use of IPv4 or IPv6\n"
121                         "  -c count     number of ICMP packets to send\n"
122                         "  -i interval  interval with which to send ICMP packets\n"
123                         "  -t ttl       time to live for each ICMP packet\n"
124                         "  -I srcaddr   source address\n"
125                         "  -f filename  filename to read hosts from\n"
127                         "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
128                         "by Florian octo Forster <octo@verplant.org>\n"
129                         "for contributions see `AUTHORS'\n",
130                         name);
131         exit (status);
134 static int read_options (int argc, char **argv)
136         int optchar;
138         while (1)
139         {
140                 optchar = getopt (argc, argv, "46c:hi:I:t:f:");
142                 if (optchar == -1)
143                         break;
145                 switch (optchar)
146                 {
147                         case '4':
148                         case '6':
149                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
150                                 break;
152                         case 'c':
153                                 {
154                                         int new_count;
155                                         new_count = atoi (optarg);
156                                         if (new_count > 0)
157                                                 opt_count = new_count;
158                                         else
159                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
160                                                                 optarg);
161                                 }
162                                 break;
164                         case 'f':
165                                 {
166                                         if (opt_filename != NULL)
167                                                 free (opt_filename);
168                                         opt_filename = strdup (optarg);
169                                 }
170                                 break;
172                         case 'i':
173                                 {
174                                         double new_interval;
175                                         new_interval = atof (optarg);
176                                         if (new_interval < 0.001)
177                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
178                                                                 optarg);
179                                         else
180                                                 opt_interval = new_interval;
181                                 }
182                                 break;
183                         case 'I':
184                                 {
185                                         if (opt_srcaddr != NULL)
186                                                 free (opt_srcaddr);
187                                         opt_srcaddr = strdup (optarg);
188                                 }
189                                 break;
191                         case 't':
192                         {
193                                 int new_send_ttl;
194                                 new_send_ttl = atoi (optarg);
195                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
196                                         opt_send_ttl = new_send_ttl;
197                                 else
198                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
199                                                         optarg);
200                                 break;
201                         }
203                         case 'h':
204                                 usage_exit (argv[0], 0);
205                                 break;
206                         default:
207                                 usage_exit (argv[0], 1);
208                 }
209         }
211         return (optind);
214 static void print_host (pingobj_iter_t *iter)
216         double          latency;
217         unsigned int    sequence;
218         int             recv_ttl;
219         size_t          buffer_len;
220         size_t          data_len;
221         ping_context_t *context;
223         latency = -1.0;
224         buffer_len = sizeof (latency);
225         ping_iterator_get_info (iter, PING_INFO_LATENCY,
226                         &latency, &buffer_len);
228         sequence = 0;
229         buffer_len = sizeof (sequence);
230         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
231                         &sequence, &buffer_len);
233         recv_ttl = -1;
234         buffer_len = sizeof (recv_ttl);
235         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
236                         &recv_ttl, &buffer_len);
238         data_len = 0;
239         ping_iterator_get_info (iter, PING_INFO_DATA,
240                         NULL, &data_len);
242         context = (ping_context_t *) ping_iterator_get_context (iter);
244         context->req_sent++;
245         if (latency > 0.0)
246         {
247                 context->req_rcvd++;
248                 context->latency_total += latency;
249                 context->latency_total_square += (latency * latency);
251                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
252                         context->latency_max = latency;
253                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
254                         context->latency_min = latency;
256                 printf ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i time=%.2f ms\n",
257                                 data_len,
258                                 context->host, context->addr,
259                                 sequence, recv_ttl, latency);
260         }
261         else
262         {
263                 printf ("echo reply from %s (%s): icmp_seq=%u timeout\n",
264                                 context->host, context->addr,
265                                 sequence);
266         }
269 static void time_normalize (struct timespec *ts)
271         while (ts->tv_nsec < 0)
272         {
273                 if (ts->tv_sec == 0)
274                 {
275                         ts->tv_nsec = 0;
276                         return;
277                 }
279                 ts->tv_sec  -= 1;
280                 ts->tv_nsec += 1000000000;
281         }
283         while (ts->tv_nsec >= 1000000000)
284         {
285                 ts->tv_sec  += 1;
286                 ts->tv_nsec -= 1000000000;
287         }
290 static void time_calc (struct timespec *ts_dest,
291                 const struct timespec *ts_int,
292                 const struct timeval  *tv_begin,
293                 const struct timeval  *tv_end)
295         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
296         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
297         time_normalize (ts_dest);
299         /* Assure that `(begin + interval) > end'.
300          * This may seem overly complicated, but `tv_sec' is of type `time_t'
301          * which may be `unsigned. *sigh* */
302         if ((tv_end->tv_sec > ts_dest->tv_sec)
303                         || ((tv_end->tv_sec == ts_dest->tv_sec)
304                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
305         {
306                 ts_dest->tv_sec  = 0;
307                 ts_dest->tv_nsec = 0;
308                 return;
309         }
311         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
312         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
313         time_normalize (ts_dest);
316 int main (int argc, char **argv)
318         pingobj_t      *ping;
319         pingobj_iter_t *iter;
321         struct sigaction sigint_action;
323         struct timeval  tv_begin;
324         struct timeval  tv_end;
325         struct timespec ts_wait;
326         struct timespec ts_int;
328         int optind;
329         int i;
331         optind = read_options (argc, argv);
333         if ((optind >= argc) && (opt_filename == NULL)) {
334                 usage_exit (argv[0], 1);
335         }
337         if (geteuid () != 0)
338         {
339                 fprintf (stderr, "Need superuser privileges to open a RAW socket. Sorry.\n");
340                 return (1);
341         }
343         if ((ping = ping_construct ()) == NULL)
344         {
345                 fprintf (stderr, "ping_construct failed\n");
346                 return (1);
347         }
349         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
350         {
351                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
352                                 opt_send_ttl, ping_get_error (ping));
353         }
355         {
356                 double temp_sec;
357                 double temp_nsec;
359                 temp_nsec = modf (opt_interval, &temp_sec);
360                 ts_int.tv_sec  = (time_t) temp_sec;
361                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
363                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
364         }
366         if (opt_addrfamily != PING_DEF_AF)
367                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
369         if (opt_srcaddr != NULL)
370         {
371                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
372                 {
373                         fprintf (stderr, "Setting source address failed: %s\n",
374                                         ping_get_error (ping));
375                 }
376         }
378         if (opt_filename != NULL)
379         {
380                 FILE *infile;
381                 char line[256];
382                 char host[256];
384                 if (strcmp (opt_filename, "-") == 0)
385                         /* Open STDIN */
386                         infile = fdopen(0, "r");
387                 else
388                         infile = fopen(opt_filename, "r");
390                 if (infile == NULL)
391                 {
392                         fprintf (stderr, "Opening %s failed: %s\n",
393                                         (strcmp (opt_filename, "-") == 0)
394                                         ? "STDIN" : opt_filename,
395                                         strerror(errno));
396                         return (1);
397                 }
399                 while (fgets(line, sizeof(line), infile))
400                 {
401                         /* Strip whitespace */
402                         if (sscanf(line, "%s", host) != 1)
403                                 continue;
405                         if ((host[0] == 0) || (host[0] == '#'))
406                                 continue;
408                         if (ping_host_add(ping, host) < 0)
409                         {
410                                 const char *errmsg = ping_get_error (ping);
412                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
413                                 continue;
414                         }
415                 }
417                 fclose(infile);
418         }
420         for (i = optind; i < argc; i++)
421         {
422                 if (ping_host_add (ping, argv[i]) < 0)
423                 {
424                         const char *errmsg = ping_get_error (ping);
426                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
427                         continue;
428                 }
429         }
431         /* Drop root privileges if we're setuid-root. */
432         setuid (getuid ());
434         i = 0;
435         for (iter = ping_iterator_get (ping);
436                         iter != NULL;
437                         iter = ping_iterator_next (iter))
438         {
439                 ping_context_t *context;
440                 size_t buffer_size;
442                 context = context_create ();
444                 buffer_size = sizeof (context->host);
445                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
447                 buffer_size = sizeof (context->addr);
448                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
450                 buffer_size = 0;
451                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
453                 printf ("PING %s (%s) %zu bytes of data.\n",
454                                 context->host, context->addr, buffer_size);
456                 ping_iterator_set_context (iter, (void *) context);
458                 i++;
459         }
461         if (i == 0)
462                 return (1);
464         memset (&sigint_action, '\0', sizeof (sigint_action));
465         sigint_action.sa_handler = sigint_handler;
466         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
467         {
468                 perror ("sigaction");
469                 return (1);
470         }
472         while (opt_count != 0)
473         {
474                 int status;
476                 if (gettimeofday (&tv_begin, NULL) < 0)
477                 {
478                         perror ("gettimeofday");
479                         return (1);
480                 }
482                 if (ping_send (ping) < 0)
483                 {
484                         fprintf (stderr, "ping_send failed: %s\n",
485                                         ping_get_error (ping));
486                         return (1);
487                 }
489                 for (iter = ping_iterator_get (ping);
490                                 iter != NULL;
491                                 iter = ping_iterator_next (iter))
492                 {
493                         print_host (iter);
494                 }
495                 fflush (stdout);
497                 /* Don't sleep in the last iteration */
498                 if (opt_count == 1)
499                         break;
501                 if (gettimeofday (&tv_end, NULL) < 0)
502                 {
503                         perror ("gettimeofday");
504                         return (1);
505                 }
507                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
509                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
510                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
511                 {
512                         if (errno != EINTR)
513                         {
514                                 perror ("nanosleep");
515                                 break;
516                         }
517                         else if (opt_count == 0)
518                         {
519                                 /* sigint */
520                                 break;
521                         }
522                 }
524                 if (opt_count > 0)
525                         opt_count--;
526         } /* while (opt_count != 0) */
528         for (iter = ping_iterator_get (ping);
529                         iter != NULL;
530                         iter = ping_iterator_next (iter))
531         {
532                 ping_context_t *context;
534                 context = ping_iterator_get_context (iter);
536                 printf ("\n--- %s ping statistics ---\n"
537                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
538                                 context->host, context->req_sent, context->req_rcvd,
539                                 100.0 * (context->req_sent - context->req_rcvd) / ((double) context->req_sent),
540                                 context->latency_total);
542                 if (context->req_rcvd != 0)
543                 {
544                         double num_total;
545                         double average;
546                         double deviation;
548                         num_total = (double) context->req_rcvd;
550                         average = context->latency_total / num_total;
551                         deviation = sqrt (((num_total * context->latency_total_square) - (context->latency_total * context->latency_total))
552                                         / (num_total * (num_total - 1.0)));
554                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
555                                         context->latency_min,
556                                         average,
557                                         context->latency_max,
558                                         deviation);
559                 }
561                 ping_iterator_set_context (iter, NULL);
562                 context_destroy (context);
563         }
565         ping_destroy (ping);
567         return (0);