ping.c
Go to the documentation of this file.
1 /**
2  * @file ping.c
3  * @brief Ping utility
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2019 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneTCP Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @author Oryx Embedded SARL (www.oryx-embedded.com)
28  * @version 1.9.6
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL PING_TRACE_LEVEL
33 
34 //Dependencies
35 #include "core/net.h"
36 #include "core/ping.h"
37 #include "core/ip.h"
38 #include "ipv4/ipv4.h"
39 #include "ipv4/ipv4_misc.h"
40 #include "ipv4/icmp.h"
41 #include "ipv6/ipv6.h"
42 #include "ipv6/ipv6_misc.h"
43 #include "ipv6/icmpv6.h"
44 #include "core/socket.h"
45 #include "debug.h"
46 
47 //Check TCP/IP stack configuration
48 #if (PING_SUPPORT == ENABLED)
49 
50 //Sequence number field
51 static uint16_t pingSequenceNumber = 0;
52 
53 
54 /**
55  * @brief Test the reachability of a host
56  *
57  * Ping operates by sending an ICMP Echo Request message to the
58  * target host and waiting for an ICMP Echo Reply message
59  *
60  * @param[in] interface Underlying network interface (optional parameter)
61  * @param[in] targetIpAddr IP address of the host to reach
62  * @param[in] size Size of the data payload in bytes
63  * @param[in] ttl Time-To-Live value to be used
64  * @param[in] timeout Maximum time to wait before giving up
65  * @param[out] rtt Round-trip time (optional parameter)
66  * @return Error code
67  **/
68 
69 error_t ping(NetInterface *interface, const IpAddr *targetIpAddr,
70  size_t size, uint8_t ttl, systime_t timeout, systime_t *rtt)
71 {
72  error_t error;
73  PingContext context;
74 
75  //Check parameters
76  if(targetIpAddr == NULL)
78 
79  //Initialize context
80  pingInit(&context);
81 
82  //Start of exception handling block
83  do
84  {
85  //Select the specified network interface
86  error = pingBindToInterface(&context, interface);
87  //Any error to report?
88  if(error)
89  break;
90 
91  //Set timeout value
92  error = pingSetTimeout(&context, timeout);
93  //Any error to report?
94  if(error)
95  break;
96 
97  //Send an ICMP Echo Request message
98  error = pingSendRequest(&context, targetIpAddr, size, ttl);
99  //Any error to report?
100  if(error)
101  break;
102 
103  //Wait for a matching Echo Reply message
104  error = pingWaitForReply(&context, NULL, rtt);
105  //Any error to report?
106  if(error)
107  break;
108 
109  //End of exception handling block
110  } while(0);
111 
112  //Release resources
113  pingRelease(&context);
114 
115  //Return status code
116  return error;
117 }
118 
119 
120 /**
121  * @brief Initialize ping context
122  * @param[in] context Pointer to the ping context
123  **/
124 
125 void pingInit(PingContext *context)
126 {
127  //Make sure the context is valid
128  if(context != NULL)
129  {
130  //Initialize context
131  memset(context, 0, sizeof(PingContext));
132 
133  //Set the default timeout to be used
134  context->timeout = PING_DEFAULT_TIMEOUT;
135  }
136 }
137 
138 
139 /**
140  * @brief Set timeout value
141  * @param[in] context Pointer to the ping context
142  * @param[in] timeout Maximum time to wait
143  * @return Error code
144  **/
145 
147 {
148  //Invalid context?
149  if(context == NULL)
151 
152  //Save timeout value
153  context->timeout = timeout;
154 
155  //Successful processing
156  return NO_ERROR;
157 }
158 
159 
160 /**
161  * @brief Select a particular network interface
162  * @param[in] context Pointer to the ping context
163  * @param[in] interface Network interface to be used
164  * @return Error code
165  **/
166 
168 {
169  //Invalid context?
170  if(context == NULL)
172 
173  //Select the specified network interface
174  context->interface = interface;
175 
176  //Successful processing
177  return NO_ERROR;
178 }
179 
180 
181 /**
182  * @brief Send an ICMP Echo Request message
183  * @param[in] context Pointer to the ping context
184  * @param[in] targetIpAddr IP address of the host to reach
185  * @param[in] size Size of the data payload, in bytes
186  * @param[in] ttl Time-To-Live value to be used
187  * @return Error code
188  **/
189 
191  const IpAddr *targetIpAddr, size_t size, uint8_t ttl)
192 {
193  error_t error;
194  size_t i;
195  size_t length;
196  NetInterface *interface;
198 
199  //Invalid context?
200  if(context == NULL)
202 
203  //Limit the size of the data payload
204  context->dataPayloadSize = MIN (size, PING_MAX_DATA_SIZE);
205 
206  //Close existing socket, if necessary
207  if(context->socket != NULL)
208  {
209  socketClose(context->socket);
210  context->socket = NULL;
211  }
212 
213  //Identifier field is used to help matching requests and replies
214  context->identifier = netGetRand();
215 
216  //Get exclusive access
218  //Sequence Number field is increment each time an Echo Request is sent
219  context->sequenceNumber = pingSequenceNumber++;
220  //Release exclusive access
222 
223  //Point to the buffer where to format the ICMP message
224  message = (IcmpEchoMessage *) context->buffer;
225 
226  //Format ICMP Echo Request message
228  message->code = 0;
229  message->checksum = 0;
230  message->identifier = context->identifier;
231  message->sequenceNumber = context->sequenceNumber;
232 
233  //Initialize data payload
234  for(i = 0; i < context->dataPayloadSize; i++)
235  message->data[i] = i & 0xFF;
236 
237  //Length of the complete ICMP message including header and data
238  length = sizeof(IcmpEchoMessage) + context->dataPayloadSize;
239 
240  //Select the relevant network interface
241  interface = context->interface;
242 
243 #if (IPV4_SUPPORT == ENABLED)
244  //Is target address an IPv4 address?
245  if(targetIpAddr->length == sizeof(Ipv4Addr))
246  {
248 
249  //Select the source IPv4 address and the relevant network
250  //interface to use when pinging the specified host
251  error = ipv4SelectSourceAddr(&interface, targetIpAddr->ipv4Addr,
252  &srcIpAddr);
253  //Any error to report?
254  if(error)
255  return error;
256 
257  //ICMP Echo Request message
259  //Message checksum calculation
260  message->checksum = ipCalcChecksum(message, length);
261 
262  //Open a raw socket
264  }
265  else
266 #endif
267 #if (IPV6_SUPPORT == ENABLED)
268  //Is target address an IPv6 address?
269  if(targetIpAddr->length == sizeof(Ipv6Addr))
270  {
271  Ipv6PseudoHeader pseudoHeader;
272 
273  //Select the source IPv6 address and the relevant network interface
274  //to use when pinging the specified host
275  error = ipv6SelectSourceAddr(&interface, &targetIpAddr->ipv6Addr,
276  &pseudoHeader.srcAddr);
277  //Any error to report?
278  if(error)
279  return error;
280 
281  //ICMPv6 Echo Request message
283 
284  //Format IPv6 pseudo header
285  pseudoHeader.destAddr = targetIpAddr->ipv6Addr;
286  pseudoHeader.length = htonl(length);
287  pseudoHeader.reserved = 0;
288  pseudoHeader.nextHeader = IPV6_ICMPV6_HEADER;
289 
290  //Message checksum calculation
291  message->checksum = ipCalcUpperLayerChecksum(&pseudoHeader,
292  sizeof(Ipv6PseudoHeader), message, length);
293 
294  //Open a raw socket
296  }
297  else
298 #endif
299  //Invalid target address?
300  {
301  //Report an error
302  return ERROR_INVALID_ADDRESS;
303  }
304 
305  //Failed to open socket?
306  if(context->socket == NULL)
307  return ERROR_OPEN_FAILED;
308 
309  //Set the TTL value to be used
310  context->socket->ttl = ttl;
311 
312  //Start of exception handling block
313  do
314  {
315  //Associate the newly created socket with the relevant interface
316  error = socketBindToInterface(context->socket, interface);
317  //Unable to bind the socket to the desired interface?
318  if(error)
319  break;
320 
321  //Debug message
322  TRACE_INFO("Sending ICMP echo request to %s (%" PRIuSIZE " bytes)...\r\n",
323  ipAddrToString(targetIpAddr, NULL), length);
324 
325  //Send Echo Request message
326  error = socketSendTo(context->socket, targetIpAddr, 0,
327  message, length, NULL, 0);
328  //Failed to send message ?
329  if(error)
330  break;
331 
332  //Save the time at which the request was sent
333  context->timestamp = osGetSystemTime();
334 
335  //End of exception handling block
336  } while(0);
337 
338  //Any error to report?
339  if(error)
340  {
341  //Clean up side effects
342  socketClose(context->socket);
343  context->socket = NULL;
344  }
345 
346  //Return status code
347  return error;
348 }
349 
350 
351 /**
352  * @brief Check whether an incoming ICMP message is acceptable
353  * @param[in] context Pointer to the ping context
354  * @param[in] srcIpAddr Source IP address
355  * @param[in] destIpAddr Destination IP address
356  * @param[in] message Pointer to the incoming ICMP message
357  * @param[in] length Length of the message, in bytes
358  * @return Error code
359  **/
360 
362  const IpAddr *destIpAddr, const IcmpEchoMessage *message, size_t length)
363 {
364  size_t i;
365 
366  //Check message length
367  if(length != (sizeof(IcmpEchoMessage) + context->dataPayloadSize))
368  return ERROR_INVALID_MESSAGE;
369 
370 #if (IPV4_SUPPORT == ENABLED)
371  //Is target address an IPv4 address?
372  if(context->socket->protocol == SOCKET_IP_PROTO_ICMP)
373  {
374  //Check address type
375  if(destIpAddr->length != sizeof(Ipv4Addr))
376  return ERROR_INVALID_MESSAGE;
377 
378  //Check message type
379  if(message->type != ICMP_TYPE_ECHO_REPLY)
380  return ERROR_INVALID_MESSAGE;
381 
382  //Verify checksum value
383  if(ipCalcChecksum(message, length) != 0x0000)
384  return ERROR_INVALID_MESSAGE;
385  }
386  else
387 #endif
388 #if (IPV6_SUPPORT == ENABLED)
389  //Is target address an IPv6 address?
390  if(context->socket->protocol == SOCKET_IP_PROTO_ICMPV6)
391  {
392  Ipv6PseudoHeader pseudoHeader;
393 
394  //Check address type
395  if(destIpAddr->length != sizeof(Ipv6Addr))
396  return ERROR_INVALID_MESSAGE;
397 
398  //Check message type
399  if(message->type != ICMPV6_TYPE_ECHO_REPLY)
400  return ERROR_INVALID_MESSAGE;
401 
402  //Format IPv6 pseudo header
403  pseudoHeader.srcAddr = srcIpAddr->ipv6Addr;
404  pseudoHeader.destAddr = destIpAddr->ipv6Addr;
405  pseudoHeader.length = htonl(length);
406  pseudoHeader.reserved = 0;
407  pseudoHeader.nextHeader = IPV6_ICMPV6_HEADER;
408 
409  //Verify checksum value
410  if(ipCalcUpperLayerChecksum(&pseudoHeader,
411  sizeof(Ipv6PseudoHeader), message, length) != 0x0000)
412  {
413  //The checksum is not valid
414  return ERROR_INVALID_MESSAGE;
415  }
416  }
417  else
418 #endif
419  //Invalid target address?
420  {
421  //Report an error
422  return ERROR_INVALID_ADDRESS;
423  }
424 
425  //Make sure the response identifier matches the request identifier
426  if(message->identifier != context->identifier)
427  return ERROR_INVALID_MESSAGE;
428  //Make sure the sequence number is correct
429  if(message->sequenceNumber != context->sequenceNumber)
430  return ERROR_INVALID_MESSAGE;
431 
432  //Verify data payload
433  for(i = 0; i < context->dataPayloadSize; i++)
434  {
435  //Compare received data against expected data pattern
436  if(message->data[i] != (i & 0xFF))
437  return ERROR_INVALID_MESSAGE;
438  }
439 
440  //The ICMP Echo Reply message is acceptable
441  return NO_ERROR;
442 }
443 
444 
445 /**
446  * @brief Wait for a matching ICMP Echo Reply message
447  * @param[in] context Pointer to the ping context
448  * @param[out] targetIpAddr IP address of the remote host (optional parameter)
449  * @param[out] rtt Round-trip time (optional parameter)
450  * @return Error code
451  **/
452 
454  IpAddr *targetIpAddr, systime_t *rtt)
455 {
456  error_t error;
457  size_t length;
458  systime_t time;
459  systime_t timeout;
462 
463  //Invalid context?
464  if(context == NULL)
466 
467  //Wait for an ICMP Echo Reply message
468  do
469  {
470  //Get current time
471  time = osGetSystemTime();
472 
473  //Compute the timeout to be used
474  if(timeCompare(time, context->timestamp + context->timeout) < 0)
475  timeout = context->timestamp + context->timeout - time;
476  else
477  timeout = 0;
478 
479  //Adjust receive timeout
480  error = socketSetTimeout(context->socket, timeout);
481  //Any error to report?
482  if(error)
483  break;
484 
485  //Wait for an incoming ICMP message
486  error = socketReceiveEx(context->socket, &srcIpAddr, NULL,
487  &destIpAddr, context->buffer, PING_BUFFER_SIZE, &length, 0);
488 
489 #if (NET_RTOS_SUPPORT == DISABLED)
490  //Catch timeout exception
491  if(error == ERROR_TIMEOUT)
492  error = ERROR_WOULD_BLOCK;
493 #endif
494 
495  //Get current time
496  time = osGetSystemTime();
497 
498  //Check status code
499  if(!error)
500  {
501  //Check whether the incoming ICMP message is acceptable
502  error = pingCheckReply(context, &srcIpAddr, &destIpAddr,
503  (IcmpEchoMessage *) context->buffer, length);
504  }
505 
506  //Check status code
507  if(!error)
508  {
509  //Calculate round-trip time
510  context->rtt = time - context->timestamp;
511 
512  //Debug message
513  TRACE_INFO("ICMP echo reply received from %s (%" PRIu32 " ms)...\r\n",
514  ipAddrToString(&srcIpAddr, NULL), context->rtt);
515 
516  //Return the IP address of the host
517  if(targetIpAddr != NULL)
518  *targetIpAddr = srcIpAddr;
519 
520  //Return the round-trip time
521  if(rtt != NULL)
522  *rtt = context->rtt;
523  }
524  else
525  {
526  //Timeout value exceeded?
527  if(timeCompare(time, context->timestamp + context->timeout) >= 0)
528  {
529  //Report an error
530  error = ERROR_TIMEOUT;
531  }
532  }
533 
534  //Wait for the next incoming ICMP message
535  } while(error == ERROR_INVALID_MESSAGE);
536 
537  //Return status code
538  return error;
539 }
540 
541 
542 /**
543  * @brief Release ping context
544  * @param[in] context Pointer to the ping context
545  **/
546 
547 void pingRelease(PingContext *context)
548 {
549  //Make sure the context is valid
550  if(context != NULL)
551  {
552  //Close underlying socket
553  if(context->socket != NULL)
554  {
555  socketClose(context->socket);
556  context->socket = NULL;
557  }
558  }
559 }
560 
561 #endif
#define PING_MAX_DATA_SIZE
Definition: ping.h:55
IPv6 (Internet Protocol Version 6)
uint8_t length
Definition: dtls_misc.h:149
error_t pingCheckReply(PingContext *context, const IpAddr *srcIpAddr, const IpAddr *destIpAddr, const IcmpEchoMessage *message, size_t length)
Check whether an incoming ICMP message is acceptable.
Definition: ping.c:361
void pingRelease(PingContext *context)
Release ping context.
Definition: ping.c:547
IP network address.
Definition: ip.h:71
systime_t timeout
Definition: ping.h:81
void socketClose(Socket *socket)
Close an existing socket.
Definition: socket.c:822
#define PING_DEFAULT_TIMEOUT
Definition: ping.h:48
error_t pingBindToInterface(PingContext *context, NetInterface *interface)
Select a particular network interface.
Definition: ping.c:167
char_t * ipAddrToString(const IpAddr *ipAddr, char_t *str)
Convert a binary IP address to a string representation.
Definition: ip.c:726
error_t ipv4SelectSourceAddr(NetInterface **interface, Ipv4Addr destAddr, Ipv4Addr *srcAddr)
IPv4 source address selection.
Definition: ipv4_misc.c:163
#define PING_BUFFER_SIZE
Definition: ping.h:61
Ipv4Addr srcIpAddr
Definition: ipcp.h:77
#define IPV4_SUPPORT
Definition: ipv4.h:49
Socket * socket
Definition: ping.h:76
#define timeCompare(t1, t2)
Definition: os_port.h:42
uint32_t Ipv4Addr
IPv4 network address.
Definition: ipv4.h:239
Ping context.
Definition: ping.h:73
systime_t timestamp
Definition: ping.h:80
error_t pingSendRequest(PingContext *context, const IpAddr *targetIpAddr, size_t size, uint8_t ttl)
Send an ICMP Echo Request message.
Definition: ping.c:190
Helper functions for IPv4.
ICMPv6 (Internet Control Message Protocol Version 6)
Invalid parameter.
Definition: error.h:47
#define htonl(value)
Definition: cpu_endian.h:393
ICMP (Internet Control Message Protocol)
Ping utility.
error_t
Error codes.
Definition: error.h:42
uint16_t sequenceNumber
Definition: ping.h:79
#define Ipv6PseudoHeader
Definition: ipv6.h:42
error_t ipv6SelectSourceAddr(NetInterface **interface, const Ipv6Addr *destAddr, Ipv6Addr *srcAddr)
IPv6 source address selection.
Definition: ipv6_misc.c:882
#define NetInterface
Definition: net.h:36
Helper functions for IPv6.
OsMutex netMutex
Definition: net.c:75
__start_packed struct @179 Ipv6Addr
IPv6 network address.
error_t ping(NetInterface *interface, const IpAddr *targetIpAddr, size_t size, uint8_t ttl, systime_t timeout, systime_t *rtt)
Test the reachability of a host.
Definition: ping.c:69
#define TRACE_INFO(...)
Definition: debug.h:94
Socket * socketOpen(uint_t type, uint_t protocol)
Create a socket (UDP or TCP)
Definition: socket.c:95
#define MIN(a, b)
Definition: os_port.h:62
size_t length
Definition: ip.h:73
#define ENABLED
Definition: os_port.h:37
#define socketBindToInterface
Definition: net_legacy.h:270
uint32_t netGetRand(void)
Get a random value.
Definition: net.c:1810
uint8_t buffer[PING_BUFFER_SIZE]
Definition: ping.h:83
uint16_t ipCalcUpperLayerChecksum(const void *pseudoHeader, size_t pseudoHeaderLen, const void *data, size_t dataLen)
Calculate IP upper-layer checksum.
Definition: ip.c:585
Ipv4Addr ipv4Addr
Definition: ip.h:77
uint32_t time
__start_packed struct @168 IcmpEchoMessage
ICMP Echo Request and Echo Reply messages.
IPv4 and IPv6 common routines.
error_t pingSetTimeout(PingContext *context, systime_t timeout)
Set timeout value.
Definition: ping.c:146
void osAcquireMutex(OsMutex *mutex)
Acquire ownership of the specified mutex object.
void osReleaseMutex(OsMutex *mutex)
Release ownership of the specified mutex object.
uint8_t message[]
Definition: chap.h:152
Socket API.
error_t socketSendTo(Socket *socket, const IpAddr *destIpAddr, uint16_t destPort, const void *data, size_t length, size_t *written, uint_t flags)
Send a datagram to a specific destination.
Definition: socket.c:535
error_t pingWaitForReply(PingContext *context, IpAddr *targetIpAddr, systime_t *rtt)
Wait for a matching ICMP Echo Reply message.
Definition: ping.c:453
NetInterface * interface
Definition: ping.h:75
error_t socketReceiveEx(Socket *socket, IpAddr *srcIpAddr, uint16_t *srcPort, IpAddr *destIpAddr, void *data, size_t size, size_t *received, uint_t flags)
Receive a datagram.
Definition: socket.c:650
IPv4 (Internet Protocol Version 4)
uint32_t ttl
Definition: dns_common.h:205
Ipv6Addr ipv6Addr
Definition: ip.h:80
#define PRIuSIZE
Definition: compiler_port.h:78
systime_t rtt
Definition: ping.h:82
TCP/IP stack core.
void pingInit(PingContext *context)
Initialize ping context.
Definition: ping.c:125
uint16_t identifier
Definition: ping.h:78
error_t socketSetTimeout(Socket *socket, systime_t timeout)
Set timeout value for blocking operations.
Definition: socket.c:219
uint32_t systime_t
Definition: compiler_port.h:46
Success.
Definition: error.h:44
Debugging facilities.
size_t dataPayloadSize
Definition: ping.h:77
uint16_t ipCalcChecksum(const void *data, size_t length)
IP checksum calculation.
Definition: ip.c:392
systime_t osGetSystemTime(void)
Retrieve system time.
Ipv4Addr destIpAddr
Definition: ipcp.h:78