Code

src/oping.c: Print the received TTL, too.
[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         int             recv_ttl;
175         size_t          buffer_len;
176         size_t          data_len;
177         ping_context_t *context;
178         
179         latency = -1.0;
180         buffer_len = sizeof (latency);
181         ping_iterator_get_info (iter, PING_INFO_LATENCY,
182                         &latency, &buffer_len);
184         sequence = 0;
185         buffer_len = sizeof (sequence);
186         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
187                         &sequence, &buffer_len);
189         recv_ttl = -1;
190         buffer_len = sizeof (recv_ttl);
191         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
192                         &recv_ttl, &buffer_len);
194         data_len = 0;
195         ping_iterator_get_info (iter, PING_INFO_DATA,
196                         NULL, &data_len);
198         context = (ping_context_t *) ping_iterator_get_context (iter);
200         context->req_sent++;
201         if (latency > 0.0)
202         {
203                 context->req_rcvd++;
204                 context->latency_total += latency;
205                 context->latency_total_square += (latency * latency);
207                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
208                         context->latency_max = latency;
209                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
210                         context->latency_min = latency;
212                 printf ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i time=%.2f ms\n",
213                                 data_len,
214                                 context->host, context->addr,
215                                 sequence, recv_ttl, latency);
216         }
217         else
218         {
219                 printf ("echo reply from %s (%s): icmp_seq=%u timeout\n",
220                                 context->host, context->addr,
221                                 sequence);
222         }
225 static void time_normalize (struct timespec *ts)
227         while (ts->tv_nsec < 0)
228         {
229                 if (ts->tv_sec == 0)
230                 {
231                         ts->tv_nsec = 0;
232                         return;
233                 }
235                 ts->tv_sec  -= 1;
236                 ts->tv_nsec += 1000000000;
237         }
239         while (ts->tv_nsec >= 1000000000)
240         {
241                 ts->tv_sec  += 1;
242                 ts->tv_nsec -= 1000000000;
243         }
246 static void time_calc (struct timespec *ts_dest,
247                 const struct timespec *ts_int,
248                 const struct timeval  *tv_begin,
249                 const struct timeval  *tv_end)
251         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
252         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
253         time_normalize (ts_dest);
255         /* Assure that `(begin + interval) > end'.
256          * This may seem overly complicated, but `tv_sec' is of type `time_t'
257          * which may be `unsigned. *sigh* */
258         if ((tv_end->tv_sec > ts_dest->tv_sec)
259                         || ((tv_end->tv_sec == ts_dest->tv_sec)
260                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
261         {
262                 ts_dest->tv_sec  = 0;
263                 ts_dest->tv_nsec = 0;
264                 return;
265         }
267         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
268         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
269         time_normalize (ts_dest);
272 int main (int argc, char **argv)
274         pingobj_t      *ping;
275         pingobj_iter_t *iter;
277         struct sigaction sigint_action;
279         struct timeval  tv_begin;
280         struct timeval  tv_end;
281         struct timespec ts_wait;
282         struct timespec ts_int;
284         int optind;
285         int i;
287         optind = read_options (argc, argv);
289         if (optind >= argc)
290                 usage_exit (argv[0]);
292         if (geteuid () != 0)
293         {
294                 fprintf (stderr, "Need superuser privileges to open a RAW socket. Sorry.\n");
295                 return (1);
296         }
298         if ((ping = ping_construct ()) == NULL)
299         {
300                 fprintf (stderr, "ping_construct failed\n");
301                 return (1);
302         }
304         {
305                 double temp_sec;
306                 double temp_nsec;
308                 temp_nsec = modf (opt_interval, &temp_sec);
309                 ts_int.tv_sec  = (time_t) temp_sec;
310                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
312                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
313         }
315         if (opt_addrfamily != PING_DEF_AF)
316                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
318         if (opt_srcaddr != NULL)
319         {
320                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
321                 {
322                         fprintf (stderr, "Setting source address failed: %s\n",
323                                         ping_get_error (ping));
324                 }
325         }
327         for (i = optind; i < argc; i++)
328         {
329                 if (ping_host_add (ping, argv[i]) < 0)
330                 {
331                         const char *errmsg = ping_get_error (ping);
333                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
334                         continue;
335                 }
336         }
338         /* Drop root privileges if we're setuid-root. */
339         setuid (getuid ());
341         i = 0;
342         for (iter = ping_iterator_get (ping);
343                         iter != NULL;
344                         iter = ping_iterator_next (iter))
345         {
346                 ping_context_t *context;
347                 size_t buffer_size;
349                 context = context_create ();
351                 buffer_size = sizeof (context->host);
352                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
354                 buffer_size = sizeof (context->addr);
355                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
357                 buffer_size = 0;
358                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
360                 printf ("PING %s (%s) %zu bytes of data.\n",
361                                 context->host, context->addr, buffer_size);
363                 ping_iterator_set_context (iter, (void *) context);
365                 i++;
366         }
368         if (i == 0)
369                 return (1);
371         memset (&sigint_action, '\0', sizeof (sigint_action));
372         sigint_action.sa_handler = sigint_handler;
373         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
374         {
375                 perror ("sigaction");
376                 return (1);
377         }
379         while (opt_count != 0)
380         {
381                 int status;
383                 if (gettimeofday (&tv_begin, NULL) < 0)
384                 {
385                         perror ("gettimeofday");
386                         return (1);
387                 }
389                 if (ping_send (ping) < 0)
390                 {
391                         fprintf (stderr, "ping_send failed: %s\n",
392                                         ping_get_error (ping));
393                         return (1);
394                 }
396                 for (iter = ping_iterator_get (ping);
397                                 iter != NULL;
398                                 iter = ping_iterator_next (iter))
399                 {
400                         print_host (iter);
401                 }
402                 fflush (stdout);
404                 /* Don't sleep in the last iteration */
405                 if (opt_count == 1)
406                         break;
408                 if (gettimeofday (&tv_end, NULL) < 0)
409                 {
410                         perror ("gettimeofday");
411                         return (1);
412                 }
414                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
416                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
417                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
418                 {
419                         if (errno != EINTR)
420                         {
421                                 perror ("nanosleep");
422                                 break;
423                         }
424                         else if (opt_count == 0)
425                         {
426                                 /* sigint */
427                                 break;
428                         }
429                 }
431                 if (opt_count > 0)
432                         opt_count--;
433         } /* while (opt_count != 0) */
435         for (iter = ping_iterator_get (ping);
436                         iter != NULL;
437                         iter = ping_iterator_next (iter))
438         {
439                 ping_context_t *context;
441                 context = ping_iterator_get_context (iter);
443                 printf ("\n--- %s ping statistics ---\n"
444                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
445                                 context->host, context->req_sent, context->req_rcvd,
446                                 100.0 * (context->req_sent - context->req_rcvd) / ((double) context->req_sent),
447                                 context->latency_total);
449                 if (context->req_rcvd != 0)
450                 {
451                         double num_total;
452                         double average;
453                         double deviation;
455                         num_total = (double) context->req_rcvd;
457                         average = context->latency_total / num_total;
458                         deviation = sqrt (((num_total * context->latency_total_square) - (context->latency_total * context->latency_total))
459                                         / (num_total * (num_total - 1.0)));
461                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
462                                         context->latency_min,
463                                         average,
464                                         context->latency_max,
465                                         deviation);
466                 }
468                 ping_iterator_set_context (iter, NULL);
469                 context_destroy (context);
470         }
472         ping_destroy (ping);
474         return (0);