Code

src/oping.c: Make all functions (except `main') static.
[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.2)
147                                                 opt_interval = new_interval;
148                                 }
149                                 break;
150                         case 'I':
151                                 {
152                                         if (opt_srcaddr != NULL)
153                                                 free (opt_srcaddr);
154                                         opt_srcaddr = strdup (optarg);
155                                 }
156                                 break;
158                         case 'h':
159                         default:
160                                 usage_exit (argv[0]);
161                 }
162         }
164         return (optind);
167 static void print_host (pingobj_iter_t *iter)
169         double          latency;
170         unsigned int    sequence;
171         size_t          buffer_len;
172         size_t          data_len;
173         ping_context_t *context;
174         
175         buffer_len = sizeof (latency);
176         ping_iterator_get_info (iter, PING_INFO_LATENCY,
177                         &latency, &buffer_len);
179         buffer_len = sizeof (sequence);
180         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
181                         &sequence, &buffer_len);
183         data_len = 0;
184         ping_iterator_get_info (iter, PING_INFO_DATA,
185                         NULL, &data_len);
187         context = (ping_context_t *) ping_iterator_get_context (iter);
189         context->req_sent++;
190         if (latency > 0.0)
191         {
192                 context->req_rcvd++;
193                 context->latency_total += latency;
194                 context->latency_total_square += (latency * latency);
196                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
197                         context->latency_max = latency;
198                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
199                         context->latency_min = latency;
201                 printf ("%zu bytes from %s (%s): icmp_seq=%u time=%.2f ms\n",
202                                 data_len,
203                                 context->host, context->addr,
204                                 sequence, latency);
205         }
206         else
207         {
208                 printf ("echo reply from %s (%s): icmp_seq=%u timeout\n",
209                                 context->host, context->addr,
210                                 sequence);
211         }
214 static void time_normalize (struct timespec *ts)
216         while (ts->tv_nsec < 0)
217         {
218                 if (ts->tv_sec == 0)
219                 {
220                         ts->tv_nsec = 0;
221                         return;
222                 }
224                 ts->tv_sec  -= 1;
225                 ts->tv_nsec += 1000000000;
226         }
228         while (ts->tv_nsec >= 1000000000)
229         {
230                 ts->tv_sec  += 1;
231                 ts->tv_nsec -= 1000000000;
232         }
235 static void time_calc (struct timespec *ts_dest,
236                 const struct timespec *ts_int,
237                 const struct timeval  *tv_begin,
238                 const struct timeval  *tv_end)
240         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
241         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
242         time_normalize (ts_dest);
244         /* Assure that `(begin + interval) > end'.
245          * This may seem overly complicated, but `tv_sec' is of type `time_t'
246          * which may be `unsigned. *sigh* */
247         if ((tv_end->tv_sec > ts_dest->tv_sec)
248                         || ((tv_end->tv_sec == ts_dest->tv_sec)
249                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
250         {
251                 ts_dest->tv_sec  = 0;
252                 ts_dest->tv_nsec = 0;
253                 return;
254         }
256         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
257         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
258         time_normalize (ts_dest);
261 int main (int argc, char **argv)
263         pingobj_t      *ping;
264         pingobj_iter_t *iter;
266         struct sigaction sigint_action;
268         struct timeval  tv_begin;
269         struct timeval  tv_end;
270         struct timespec ts_wait;
271         struct timespec ts_int;
273         int optind;
274         int i;
276         optind = read_options (argc, argv);
278         if (optind >= argc)
279                 usage_exit (argv[0]);
281         if (geteuid () != 0)
282         {
283                 fprintf (stderr, "Need superuser privileges to open a RAW socket. Sorry.\n");
284                 return (1);
285         }
287         if ((ping = ping_construct ()) == NULL)
288         {
289                 fprintf (stderr, "ping_construct failed\n");
290                 return (1);
291         }
293         {
294                 double temp_sec;
295                 double temp_nsec;
297                 temp_nsec = modf (opt_interval, &temp_sec);
298                 ts_int.tv_sec  = (time_t) temp_sec;
299                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
301                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
302         }
304         if (opt_addrfamily != PING_DEF_AF)
305                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
307         if (opt_srcaddr != NULL)
308         {
309                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
310                 {
311                         fprintf (stderr, "Setting source address failed: %s\n",
312                                         ping_get_error (ping));
313                 }
314         }
316         for (i = optind; i < argc; i++)
317         {
318                 if (ping_host_add (ping, argv[i]) < 0)
319                 {
320                         const char *errmsg = ping_get_error (ping);
322                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
323                         continue;
324                 }
325         }
327         /* Drop root privileges if we're setuid-root. */
328         setuid (getuid ());
330         i = 0;
331         for (iter = ping_iterator_get (ping);
332                         iter != NULL;
333                         iter = ping_iterator_next (iter))
334         {
335                 ping_context_t *context;
336                 size_t buffer_size;
338                 context = context_create ();
340                 buffer_size = sizeof (context->host);
341                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
343                 buffer_size = sizeof (context->addr);
344                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
346                 buffer_size = 0;
347                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
349                 printf ("PING %s (%s) %zu bytes of data.\n",
350                                 context->host, context->addr, buffer_size);
352                 ping_iterator_set_context (iter, (void *) context);
354                 i++;
355         }
357         if (i == 0)
358                 return (1);
360         memset (&sigint_action, '\0', sizeof (sigint_action));
361         sigint_action.sa_handler = sigint_handler;
362         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
363         {
364                 perror ("sigaction");
365                 return (1);
366         }
368         while (opt_count != 0)
369         {
370                 int status;
372                 if (gettimeofday (&tv_begin, NULL) < 0)
373                 {
374                         perror ("gettimeofday");
375                         return (1);
376                 }
378                 if (ping_send (ping) < 0)
379                 {
380                         fprintf (stderr, "ping_send failed: %s\n",
381                                         ping_get_error (ping));
382                         return (1);
383                 }
385                 for (iter = ping_iterator_get (ping);
386                                 iter != NULL;
387                                 iter = ping_iterator_next (iter))
388                 {
389                         print_host (iter);
390                 }
391                 fflush (stdout);
393                 /* Don't sleep in the last iteration */
394                 if (opt_count == 1)
395                         break;
397                 if (gettimeofday (&tv_end, NULL) < 0)
398                 {
399                         perror ("gettimeofday");
400                         return (1);
401                 }
403                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
405                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
406                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
407                 {
408                         if (errno != EINTR)
409                         {
410                                 perror ("nanosleep");
411                                 break;
412                         }
413                         else if (opt_count == 0)
414                         {
415                                 /* sigint */
416                                 break;
417                         }
418                 }
420                 if (opt_count > 0)
421                         opt_count--;
422         } /* while (opt_count != 0) */
424         for (iter = ping_iterator_get (ping);
425                         iter != NULL;
426                         iter = ping_iterator_next (iter))
427         {
428                 ping_context_t *context;
430                 context = ping_iterator_get_context (iter);
432                 printf ("\n--- %s ping statistics ---\n"
433                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
434                                 context->host, context->req_sent, context->req_rcvd,
435                                 100.0 * (context->req_sent - context->req_rcvd) / ((double) context->req_sent),
436                                 context->latency_total);
438                 if (context->req_rcvd != 0)
439                 {
440                         double num_total;
441                         double average;
442                         double deviation;
444                         num_total = (double) context->req_rcvd;
446                         average = context->latency_total / num_total;
447                         deviation = sqrt (((num_total * context->latency_total_square) - (context->latency_total * context->latency_total))
448                                         / (num_total * (num_total - 1.0)));
450                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
451                                         context->latency_min,
452                                         average,
453                                         context->latency_max,
454                                         deviation);
455                 }
457                 ping_iterator_set_context (iter, NULL);
458                 free (context);
459         }
461         ping_destroy (ping);
463         return (0);