Code

src/oping.c: Allow setting of the TTL using `-t'.
[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;
77 static int     opt_send_ttl   = 64;
79 static void sigint_handler (int signal)
80 {
81         /* Make compiler happy */
82         signal = 0;
83         /* Exit the loop */
84         opt_count = 0;
85 }
87 static ping_context_t *context_create (void)
88 {
89         ping_context_t *ret;
91         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
92                 return (NULL);
94         memset (ret, '\0', sizeof (ping_context_t));
96         ret->latency_min   = -1.0;
97         ret->latency_max   = -1.0;
98         ret->latency_total = 0.0;
99         ret->latency_total_square = 0.0;
101         return (ret);
104 static void context_destroy (ping_context_t *context)
106         free (context);
109 static void usage_exit (const char *name)
111         int name_length;
113         name_length = (int) strlen (name);
115         fprintf (stderr, "Usage: %s [-46] [-c count] [-i interval]\n"
116                         "%*s[-t ttl] [-I srcaddr]\n"
117                         "%*shost [host [host ...]]\n",
118                         name,
119                         8 + name_length, "",
120                         8 + name_length, "");
121         exit (1);
124 static int read_options (int argc, char **argv)
126         int optchar;
128         while (1)
129         {
130                 optchar = getopt (argc, argv, "46c:hi:I:t:");
132                 if (optchar == -1)
133                         break;
135                 switch (optchar)
136                 {
137                         case '4':
138                         case '6':
139                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
140                                 break;
142                         case 'c':
143                                 {
144                                         int new_count;
145                                         new_count = atoi (optarg);
146                                         if (new_count > 0)
147                                                 opt_count = new_count;
148                                 }
149                                 break;
151                         case 'i':
152                                 {
153                                         double new_interval;
154                                         new_interval = atof (optarg);
155                                         if (new_interval < 0.001)
156                                                 fprintf (stderr, "Ignoring invalid interval %g.\n",
157                                                                 new_interval);
158                                         else
159                                                 opt_interval = new_interval;
160                                 }
161                                 break;
162                         case 'I':
163                                 {
164                                         if (opt_srcaddr != NULL)
165                                                 free (opt_srcaddr);
166                                         opt_srcaddr = strdup (optarg);
167                                 }
168                                 break;
170                         case 't':
171                         {
172                                 int new_send_ttl;
173                                 new_send_ttl = atoi (optarg);
174                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
175                                         opt_send_ttl = new_send_ttl;
176                                 else
177                                         fprintf (stderr, "Invalid TTL argument: %s\n",
178                                                         optarg);
179                                 break;
180                         }
182                         case 'h':
183                         default:
184                                 usage_exit (argv[0]);
185                 }
186         }
188         return (optind);
191 static void print_host (pingobj_iter_t *iter)
193         double          latency;
194         unsigned int    sequence;
195         int             recv_ttl;
196         size_t          buffer_len;
197         size_t          data_len;
198         ping_context_t *context;
199         
200         latency = -1.0;
201         buffer_len = sizeof (latency);
202         ping_iterator_get_info (iter, PING_INFO_LATENCY,
203                         &latency, &buffer_len);
205         sequence = 0;
206         buffer_len = sizeof (sequence);
207         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
208                         &sequence, &buffer_len);
210         recv_ttl = -1;
211         buffer_len = sizeof (recv_ttl);
212         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
213                         &recv_ttl, &buffer_len);
215         data_len = 0;
216         ping_iterator_get_info (iter, PING_INFO_DATA,
217                         NULL, &data_len);
219         context = (ping_context_t *) ping_iterator_get_context (iter);
221         context->req_sent++;
222         if (latency > 0.0)
223         {
224                 context->req_rcvd++;
225                 context->latency_total += latency;
226                 context->latency_total_square += (latency * latency);
228                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
229                         context->latency_max = latency;
230                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
231                         context->latency_min = latency;
233                 printf ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i time=%.2f ms\n",
234                                 data_len,
235                                 context->host, context->addr,
236                                 sequence, recv_ttl, latency);
237         }
238         else
239         {
240                 printf ("echo reply from %s (%s): icmp_seq=%u timeout\n",
241                                 context->host, context->addr,
242                                 sequence);
243         }
246 static void time_normalize (struct timespec *ts)
248         while (ts->tv_nsec < 0)
249         {
250                 if (ts->tv_sec == 0)
251                 {
252                         ts->tv_nsec = 0;
253                         return;
254                 }
256                 ts->tv_sec  -= 1;
257                 ts->tv_nsec += 1000000000;
258         }
260         while (ts->tv_nsec >= 1000000000)
261         {
262                 ts->tv_sec  += 1;
263                 ts->tv_nsec -= 1000000000;
264         }
267 static void time_calc (struct timespec *ts_dest,
268                 const struct timespec *ts_int,
269                 const struct timeval  *tv_begin,
270                 const struct timeval  *tv_end)
272         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
273         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
274         time_normalize (ts_dest);
276         /* Assure that `(begin + interval) > end'.
277          * This may seem overly complicated, but `tv_sec' is of type `time_t'
278          * which may be `unsigned. *sigh* */
279         if ((tv_end->tv_sec > ts_dest->tv_sec)
280                         || ((tv_end->tv_sec == ts_dest->tv_sec)
281                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
282         {
283                 ts_dest->tv_sec  = 0;
284                 ts_dest->tv_nsec = 0;
285                 return;
286         }
288         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
289         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
290         time_normalize (ts_dest);
293 int main (int argc, char **argv)
295         pingobj_t      *ping;
296         pingobj_iter_t *iter;
298         struct sigaction sigint_action;
300         struct timeval  tv_begin;
301         struct timeval  tv_end;
302         struct timespec ts_wait;
303         struct timespec ts_int;
305         int optind;
306         int i;
308         optind = read_options (argc, argv);
310         if (optind >= argc)
311                 usage_exit (argv[0]);
313         if (geteuid () != 0)
314         {
315                 fprintf (stderr, "Need superuser privileges to open a RAW socket. Sorry.\n");
316                 return (1);
317         }
319         if ((ping = ping_construct ()) == NULL)
320         {
321                 fprintf (stderr, "ping_construct failed\n");
322                 return (1);
323         }
325         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
326         {
327                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
328                                 opt_send_ttl, ping_get_error (ping));
329         }
331         {
332                 double temp_sec;
333                 double temp_nsec;
335                 temp_nsec = modf (opt_interval, &temp_sec);
336                 ts_int.tv_sec  = (time_t) temp_sec;
337                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
339                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
340         }
342         if (opt_addrfamily != PING_DEF_AF)
343                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
345         if (opt_srcaddr != NULL)
346         {
347                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
348                 {
349                         fprintf (stderr, "Setting source address failed: %s\n",
350                                         ping_get_error (ping));
351                 }
352         }
354         for (i = optind; i < argc; i++)
355         {
356                 if (ping_host_add (ping, argv[i]) < 0)
357                 {
358                         const char *errmsg = ping_get_error (ping);
360                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
361                         continue;
362                 }
363         }
365         /* Drop root privileges if we're setuid-root. */
366         setuid (getuid ());
368         i = 0;
369         for (iter = ping_iterator_get (ping);
370                         iter != NULL;
371                         iter = ping_iterator_next (iter))
372         {
373                 ping_context_t *context;
374                 size_t buffer_size;
376                 context = context_create ();
378                 buffer_size = sizeof (context->host);
379                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
381                 buffer_size = sizeof (context->addr);
382                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
384                 buffer_size = 0;
385                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
387                 printf ("PING %s (%s) %zu bytes of data.\n",
388                                 context->host, context->addr, buffer_size);
390                 ping_iterator_set_context (iter, (void *) context);
392                 i++;
393         }
395         if (i == 0)
396                 return (1);
398         memset (&sigint_action, '\0', sizeof (sigint_action));
399         sigint_action.sa_handler = sigint_handler;
400         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
401         {
402                 perror ("sigaction");
403                 return (1);
404         }
406         while (opt_count != 0)
407         {
408                 int status;
410                 if (gettimeofday (&tv_begin, NULL) < 0)
411                 {
412                         perror ("gettimeofday");
413                         return (1);
414                 }
416                 if (ping_send (ping) < 0)
417                 {
418                         fprintf (stderr, "ping_send failed: %s\n",
419                                         ping_get_error (ping));
420                         return (1);
421                 }
423                 for (iter = ping_iterator_get (ping);
424                                 iter != NULL;
425                                 iter = ping_iterator_next (iter))
426                 {
427                         print_host (iter);
428                 }
429                 fflush (stdout);
431                 /* Don't sleep in the last iteration */
432                 if (opt_count == 1)
433                         break;
435                 if (gettimeofday (&tv_end, NULL) < 0)
436                 {
437                         perror ("gettimeofday");
438                         return (1);
439                 }
441                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
443                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
444                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
445                 {
446                         if (errno != EINTR)
447                         {
448                                 perror ("nanosleep");
449                                 break;
450                         }
451                         else if (opt_count == 0)
452                         {
453                                 /* sigint */
454                                 break;
455                         }
456                 }
458                 if (opt_count > 0)
459                         opt_count--;
460         } /* while (opt_count != 0) */
462         for (iter = ping_iterator_get (ping);
463                         iter != NULL;
464                         iter = ping_iterator_next (iter))
465         {
466                 ping_context_t *context;
468                 context = ping_iterator_get_context (iter);
470                 printf ("\n--- %s ping statistics ---\n"
471                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
472                                 context->host, context->req_sent, context->req_rcvd,
473                                 100.0 * (context->req_sent - context->req_rcvd) / ((double) context->req_sent),
474                                 context->latency_total);
476                 if (context->req_rcvd != 0)
477                 {
478                         double num_total;
479                         double average;
480                         double deviation;
482                         num_total = (double) context->req_rcvd;
484                         average = context->latency_total / num_total;
485                         deviation = sqrt (((num_total * context->latency_total_square) - (context->latency_total * context->latency_total))
486                                         / (num_total * (num_total - 1.0)));
488                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
489                                         context->latency_min,
490                                         average,
491                                         context->latency_max,
492                                         deviation);
493                 }
495                 ping_iterator_set_context (iter, NULL);
496                 context_destroy (context);
497         }
499         ping_destroy (ping);
501         return (0);