Display a line of the following form when starting `oping':
[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; either version 2 of the License, or
8  * (at your option) any later version.
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  */
19
20 #if HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
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 */
33
34 #if HAVE_MATH_H
35 # include <math.h>
36 #endif
37
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
48
49 #if HAVE_NETDB_H
50 # include <netdb.h> /* NI_MAXHOST */
51 #endif
52
53 #if HAVE_SIGNAL_H
54 # include <signal.h>
55 #endif
56
57 #include "oping.h"
58
59 typedef struct ping_context
60 {
61         char host[NI_MAXHOST];
62         char addr[NI_MAXHOST];
63
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;
72
73 static double opt_interval   = 1.0;
74 static int    opt_addrfamily = PING_DEF_AF;
75 static int    opt_count      = -1;
76
77 void sigint_handler (int signal)
78 {
79         /* Exit the loop */
80         opt_count = 0;
81 }
82
83 ping_context_t *context_create (void)
84 {
85         ping_context_t *ret;
86
87         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
88                 return (NULL);
89
90         memset (ret, '\0', sizeof (ping_context_t));
91
92         ret->latency_min   = -1.0;
93         ret->latency_max   = -1.0;
94         ret->latency_total = 0.0;
95         ret->latency_total_square = 0.0;
96
97         return (ret);
98 }
99
100 void context_destroy (ping_context_t *context)
101 {
102         free (context);
103 }
104
105 void usage_exit (const char *name)
106 {
107         fprintf (stderr, "Usage: %s [-46] [-c count] [-i interval] host [host [host ...]]\n",
108                         name);
109         exit (1);
110 }
111
112 int read_options (int argc, char **argv)
113 {
114         int optchar;
115
116         while (1)
117         {
118                 optchar = getopt (argc, argv, "46c:hi:");
119
120                 if (optchar == -1)
121                         break;
122
123                 switch (optchar)
124                 {
125                         case '4':
126                         case '6':
127                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
128                                 break;
129
130                         case 'c':
131                                 {
132                                         int new_count;
133                                         new_count = atoi (optarg);
134                                         if (new_count > 0)
135                                                 opt_count = new_count;
136                                 }
137                                 break;
138
139                         case 'i':
140                                 {
141                                         double new_interval;
142                                         new_interval = atof (optarg);
143                                         if (new_interval >= 0.2)
144                                                 opt_interval = new_interval;
145                                 }
146                                 break;
147
148                         case 'h':
149                         default:
150                                 usage_exit (argv[0]);
151                 }
152         }
153
154         return (optind);
155 }
156
157 void print_host (pingobj_iter_t *iter)
158 {
159         double          latency;
160         unsigned int    sequence;
161         size_t          buffer_len;
162         size_t          data_len;
163         ping_context_t *context;
164         
165         buffer_len = sizeof (latency);
166         ping_iterator_get_info (iter, PING_INFO_LATENCY,
167                         &latency, &buffer_len);
168
169         buffer_len = sizeof (sequence);
170         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
171                         &sequence, &buffer_len);
172
173         data_len = 0;
174         ping_iterator_get_info (iter, PING_INFO_DATA,
175                         NULL, &data_len);
176
177         context = (ping_context_t *) ping_iterator_get_context (iter);
178
179         context->req_sent++;
180         if (latency > 0.0)
181         {
182                 context->req_rcvd++;
183                 context->latency_total += latency;
184                 context->latency_total_square += (latency * latency);
185
186                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
187                         context->latency_max = latency;
188                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
189                         context->latency_min = latency;
190
191                 printf ("%u bytes from %s (%s): icmp_seq=%u time=%.2f ms\n",
192                                 (unsigned int) data_len,
193                                 context->host, context->addr,
194                                 (unsigned int) sequence, latency);
195         }
196         else
197         {
198                 printf ("echo reply from %s (%s): icmp_seq=%u timeout\n",
199                                 context->host, context->addr,
200                                 (unsigned int) sequence);
201         }
202 }
203
204 void time_normalize (struct timespec *ts)
205 {
206         while (ts->tv_nsec < 0)
207         {
208                 if (ts->tv_sec == 0)
209                 {
210                         ts->tv_nsec = 0;
211                         return;
212                 }
213
214                 ts->tv_sec  -= 1;
215                 ts->tv_nsec += 1000000000;
216         }
217
218         while (ts->tv_nsec >= 1000000000)
219         {
220                 ts->tv_sec  += 1;
221                 ts->tv_nsec -= 1000000000;
222         }
223 }
224
225 void time_calc (struct timespec *ts_dest,
226                 const struct timespec *ts_int,
227                 const struct timeval  *tv_begin,
228                 const struct timeval  *tv_end)
229 {
230         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
231         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
232         time_normalize (ts_dest);
233
234         /* Assure that `(begin + interval) > end'.
235          * This may seem overly complicated, but `tv_sec' is of type `time_t'
236          * which may be `unsigned. *sigh* */
237         if ((tv_end->tv_sec > ts_dest->tv_sec)
238                         || ((tv_end->tv_sec == ts_dest->tv_sec)
239                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
240         {
241                 ts_dest->tv_sec  = 0;
242                 ts_dest->tv_nsec = 0;
243                 return;
244         }
245
246         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
247         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
248         time_normalize (ts_dest);
249 }
250
251 int main (int argc, char **argv)
252 {
253         pingobj_t      *ping;
254         pingobj_iter_t *iter;
255
256         struct sigaction sigint_action;
257
258         struct timeval  tv_begin;
259         struct timeval  tv_end;
260         struct timespec ts_wait;
261         struct timespec ts_int;
262
263         int optind;
264         int i;
265
266         optind = read_options (argc, argv);
267
268         if (optind >= argc)
269                 usage_exit (argv[0]);
270
271         if (geteuid () != 0)
272         {
273                 fprintf (stderr, "Need superuser privileges to open a RAW socket. Sorry.\n");
274                 return (1);
275         }
276
277         if ((ping = ping_construct ()) == NULL)
278         {
279                 fprintf (stderr, "ping_construct failed\n");
280                 return (1);
281         }
282
283         {
284                 double temp_sec;
285                 double temp_nsec;
286
287                 temp_nsec = modf (opt_interval, &temp_sec);
288                 ts_int.tv_sec  = (time_t) temp_sec;
289                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
290
291                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
292         }
293
294         if (opt_addrfamily != PING_DEF_AF)
295                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
296
297         for (i = optind; i < argc; i++)
298         {
299                 if (ping_host_add (ping, argv[i]) > 0)
300                 {
301                         fprintf (stderr, "ping_host_add (%s) failed\n", argv[i]);
302                         continue;
303                 }
304         }
305
306         for (iter = ping_iterator_get (ping);
307                         iter != NULL;
308                         iter = ping_iterator_next (iter))
309         {
310                 ping_context_t *context;
311                 size_t buffer_size;
312
313                 context = context_create ();
314
315                 buffer_size = sizeof (context->host);
316                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
317
318                 buffer_size = sizeof (context->addr);
319                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
320
321                 buffer_size = 0;
322                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
323
324                 printf ("PING %s (%s) %u bytes of data.\n",
325                                 context->host, context->addr, buffer_size);
326
327                 ping_iterator_set_context (iter, (void *) context);
328         }
329
330         memset (&sigint_action, '\0', sizeof (sigint_action));
331         sigint_action.sa_handler = sigint_handler;
332         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
333         {
334                 perror ("sigaction");
335                 return (1);
336         }
337
338         while (opt_count != 0)
339         {
340                 int status;
341
342                 if (gettimeofday (&tv_begin, NULL) < 0)
343                 {
344                         perror ("gettimeofday");
345                         return (1);
346                 }
347
348                 if (ping_send (ping) < 0)
349                 {
350                         fprintf (stderr, "ping_send failed\n");
351                         return (1);
352                 }
353
354                 for (iter = ping_iterator_get (ping);
355                                 iter != NULL;
356                                 iter = ping_iterator_next (iter))
357                 {
358                         print_host (iter);
359                 }
360                 fflush (stdout);
361
362                 /* Don't sleep in the last iteration */
363                 if (opt_count == 1)
364                         break;
365
366                 if (gettimeofday (&tv_end, NULL) < 0)
367                 {
368                         perror ("gettimeofday");
369                         return (1);
370                 }
371
372                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
373
374                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
375                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
376                 {
377                         if (errno != EINTR)
378                         {
379                                 perror ("nanosleep");
380                                 break;
381                         }
382                         else if (opt_count == 0)
383                         {
384                                 /* sigint */
385                                 break;
386                         }
387                 }
388
389                 if (opt_count > 0)
390                         opt_count--;
391         } /* while (opt_count != 0) */
392
393         for (iter = ping_iterator_get (ping);
394                         iter != NULL;
395                         iter = ping_iterator_next (iter))
396         {
397                 ping_context_t *context;
398
399                 context = ping_iterator_get_context (iter);
400
401                 printf ("\n--- %s ping statistics ---\n"
402                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
403                                 context->host, context->req_sent, context->req_rcvd,
404                                 100.0 * (context->req_sent - context->req_rcvd) / ((double) context->req_sent),
405                                 context->latency_total);
406
407                 if (context->req_rcvd != 0)
408                 {
409                         double num_total;
410                         double average;
411                         double deviation;
412
413                         num_total = (double) context->req_rcvd;
414
415                         average = context->latency_total / num_total;
416                         deviation = sqrt (((num_total * context->latency_total_square) - (context->latency_total * context->latency_total))
417                                         / (num_total * (num_total - 1.0)));
418
419                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
420                                         context->latency_min,
421                                         average,
422                                         context->latency_max,
423                                         deviation);
424                 }
425
426                 ping_iterator_set_context (iter, NULL);
427                 free (context);
428         }
429
430         ping_destroy (ping);
431
432         return (0);
433 }