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-2023 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 2.2.2
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 && RAW_SOCKET_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  osMemset(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] = 0;
288  pseudoHeader.reserved[1] = 0;
289  pseudoHeader.reserved[2] = 0;
290  pseudoHeader.nextHeader = IPV6_ICMPV6_HEADER;
291 
292  //Message checksum calculation
293  message->checksum = ipCalcUpperLayerChecksum(&pseudoHeader,
294  sizeof(Ipv6PseudoHeader), message, length);
295 
296  //Open a raw socket
298  }
299  else
300 #endif
301  //Invalid target address?
302  {
303  //Report an error
304  return ERROR_INVALID_ADDRESS;
305  }
306 
307  //Failed to open socket?
308  if(context->socket == NULL)
309  return ERROR_OPEN_FAILED;
310 
311  //Set the TTL value to be used
312  context->socket->ttl = ttl;
313 
314  //Start of exception handling block
315  do
316  {
317  //Associate the newly created socket with the relevant interface
318  error = socketBindToInterface(context->socket, interface);
319  //Unable to bind the socket to the desired interface?
320  if(error)
321  break;
322 
323  //Debug message
324  TRACE_INFO("Sending ICMP echo request to %s (%" PRIuSIZE " bytes)...\r\n",
325  ipAddrToString(targetIpAddr, NULL), length);
326 
327  //Send Echo Request message
328  error = socketSendTo(context->socket, targetIpAddr, 0,
329  message, length, NULL, 0);
330  //Failed to send message ?
331  if(error)
332  break;
333 
334  //Save the time at which the request was sent
335  context->timestamp = osGetSystemTime();
336 
337  //End of exception handling block
338  } while(0);
339 
340  //Any error to report?
341  if(error)
342  {
343  //Clean up side effects
344  socketClose(context->socket);
345  context->socket = NULL;
346  }
347 
348  //Return status code
349  return error;
350 }
351 
352 
353 /**
354  * @brief Check whether an incoming ICMP message is acceptable
355  * @param[in] context Pointer to the ping context
356  * @param[in] srcIpAddr Source IP address
357  * @param[in] destIpAddr Destination IP address
358  * @param[in] message Pointer to the incoming ICMP message
359  * @param[in] length Length of the message, in bytes
360  * @return Error code
361  **/
362 
364  const IpAddr *destIpAddr, const IcmpEchoMessage *message, size_t length)
365 {
366  size_t i;
367 
368  //Check message length
369  if(length != (sizeof(IcmpEchoMessage) + context->dataPayloadSize))
370  return ERROR_INVALID_MESSAGE;
371 
372 #if (IPV4_SUPPORT == ENABLED)
373  //Is target address an IPv4 address?
374  if(context->socket->protocol == SOCKET_IP_PROTO_ICMP)
375  {
376  //Check address type
377  if(destIpAddr->length != sizeof(Ipv4Addr))
378  return ERROR_INVALID_MESSAGE;
379 
380  //Check message type
381  if(message->type != ICMP_TYPE_ECHO_REPLY)
382  return ERROR_INVALID_MESSAGE;
383 
384  //Verify checksum value
385  if(ipCalcChecksum(message, length) != 0x0000)
386  return ERROR_INVALID_MESSAGE;
387  }
388  else
389 #endif
390 #if (IPV6_SUPPORT == ENABLED)
391  //Is target address an IPv6 address?
392  if(context->socket->protocol == SOCKET_IP_PROTO_ICMPV6)
393  {
394  Ipv6PseudoHeader pseudoHeader;
395 
396  //Check address type
397  if(destIpAddr->length != sizeof(Ipv6Addr))
398  return ERROR_INVALID_MESSAGE;
399 
400  //Check message type
401  if(message->type != ICMPV6_TYPE_ECHO_REPLY)
402  return ERROR_INVALID_MESSAGE;
403 
404  //Format IPv6 pseudo header
405  pseudoHeader.srcAddr = srcIpAddr->ipv6Addr;
406  pseudoHeader.destAddr = destIpAddr->ipv6Addr;
407  pseudoHeader.length = htonl(length);
408  pseudoHeader.reserved[0] = 0;
409  pseudoHeader.reserved[1] = 0;
410  pseudoHeader.reserved[2] = 0;
411  pseudoHeader.nextHeader = IPV6_ICMPV6_HEADER;
412 
413  //Verify checksum value
414  if(ipCalcUpperLayerChecksum(&pseudoHeader,
415  sizeof(Ipv6PseudoHeader), message, length) != 0x0000)
416  {
417  //The checksum is not valid
418  return ERROR_INVALID_MESSAGE;
419  }
420  }
421  else
422 #endif
423  //Invalid target address?
424  {
425  //Report an error
426  return ERROR_INVALID_ADDRESS;
427  }
428 
429  //Make sure the response identifier matches the request identifier
430  if(message->identifier != context->identifier)
431  return ERROR_INVALID_MESSAGE;
432  //Make sure the sequence number is correct
433  if(message->sequenceNumber != context->sequenceNumber)
434  return ERROR_INVALID_MESSAGE;
435 
436  //Verify data payload
437  for(i = 0; i < context->dataPayloadSize; i++)
438  {
439  //Compare received data against expected data pattern
440  if(message->data[i] != (i & 0xFF))
441  return ERROR_INVALID_MESSAGE;
442  }
443 
444  //The ICMP Echo Reply message is acceptable
445  return NO_ERROR;
446 }
447 
448 
449 /**
450  * @brief Wait for a matching ICMP Echo Reply message
451  * @param[in] context Pointer to the ping context
452  * @param[out] targetIpAddr IP address of the remote host (optional parameter)
453  * @param[out] rtt Round-trip time (optional parameter)
454  * @return Error code
455  **/
456 
458  IpAddr *targetIpAddr, systime_t *rtt)
459 {
460  error_t error;
461  size_t length;
462  systime_t time;
463  systime_t timeout;
466 
467  //Invalid context?
468  if(context == NULL)
470 
471  //Wait for an ICMP Echo Reply message
472  do
473  {
474  //Get current time
475  time = osGetSystemTime();
476 
477  //Compute the timeout to be used
478  if(timeCompare(time, context->timestamp + context->timeout) < 0)
479  timeout = context->timestamp + context->timeout - time;
480  else
481  timeout = 0;
482 
483  //Adjust receive timeout
484  error = socketSetTimeout(context->socket, timeout);
485  //Any error to report?
486  if(error)
487  break;
488 
489  //Wait for an incoming ICMP message
490  error = socketReceiveEx(context->socket, &srcIpAddr, NULL,
491  &destIpAddr, context->buffer, PING_BUFFER_SIZE, &length, 0);
492 
493 #if (NET_RTOS_SUPPORT == DISABLED)
494  //Catch timeout exception
495  if(error == ERROR_TIMEOUT)
496  error = ERROR_WOULD_BLOCK;
497 #endif
498 
499  //Get current time
500  time = osGetSystemTime();
501 
502  //Check status code
503  if(!error)
504  {
505  //Check whether the incoming ICMP message is acceptable
506  error = pingCheckReply(context, &srcIpAddr, &destIpAddr,
507  (IcmpEchoMessage *) context->buffer, length);
508  }
509 
510  //Check status code
511  if(!error)
512  {
513  //Calculate round-trip time
514  context->rtt = time - context->timestamp;
515 
516  //Debug message
517  TRACE_INFO("ICMP echo reply received from %s (%" PRIu32 " ms)...\r\n",
518  ipAddrToString(&srcIpAddr, NULL), context->rtt);
519 
520  //Return the IP address of the host
521  if(targetIpAddr != NULL)
522  *targetIpAddr = srcIpAddr;
523 
524  //Return the round-trip time
525  if(rtt != NULL)
526  *rtt = context->rtt;
527  }
528  else
529  {
530  //Timeout value exceeded?
531  if(timeCompare(time, context->timestamp + context->timeout) >= 0)
532  {
533  //Report an error
534  error = ERROR_TIMEOUT;
535  }
536  }
537 
538  //Wait for the next incoming ICMP message
539  } while(error == ERROR_INVALID_MESSAGE);
540 
541  //Return status code
542  return error;
543 }
544 
545 
546 /**
547  * @brief Release ping context
548  * @param[in] context Pointer to the ping context
549  **/
550 
551 void pingRelease(PingContext *context)
552 {
553  //Make sure the context is valid
554  if(context != NULL)
555  {
556  //Close underlying socket
557  if(context->socket != NULL)
558  {
559  socketClose(context->socket);
560  context->socket = NULL;
561  }
562  }
563 }
564 
565 #endif
uint8_t length
Definition: coap_common.h:193
#define PING_MAX_DATA_SIZE
Definition: ping.h:55
IPv6 (Internet Protocol Version 6)
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:363
void pingRelease(PingContext *context)
Release ping context.
Definition: ping.c:551
@ ERROR_WOULD_BLOCK
Definition: error.h:96
#define netMutex
Definition: net_legacy.h:195
IP network address.
Definition: ip.h:79
systime_t timeout
Definition: ping.h:81
__start_packed struct @5 IcmpEchoMessage
ICMP Echo Request and Echo Reply messages.
@ SOCKET_IP_PROTO_ICMPV6
Definition: socket.h:95
void socketClose(Socket *socket)
Close an existing socket.
Definition: socket.c:1331
#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:806
error_t ipv4SelectSourceAddr(NetInterface **interface, Ipv4Addr destAddr, Ipv4Addr *srcAddr)
IPv4 source address selection.
Definition: ipv4_misc.c:203
#define PING_BUFFER_SIZE
Definition: ping.h:61
@ IPV6_ICMPV6_HEADER
Definition: ipv6.h:187
@ ERROR_INVALID_MESSAGE
Definition: error.h:105
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:261
Ping context.
Definition: ping.h:74
systime_t timestamp
Definition: ping.h:80
@ ICMPV6_TYPE_ECHO_REQUEST
Definition: icmpv6.h:57
@ ERROR_OPEN_FAILED
Definition: error.h:75
@ ICMPV6_TYPE_ECHO_REPLY
Definition: icmpv6.h:58
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)
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
#define htonl(value)
Definition: cpu_endian.h:414
ICMP (Internet Control Message Protocol)
Ping utility.
error_t
Error codes.
Definition: error.h:43
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:879
@ ERROR_INVALID_ADDRESS
Definition: error.h:103
#define NetInterface
Definition: net.h:36
Helper functions for IPv6.
@ SOCKET_TYPE_RAW_IP
Definition: socket.h:80
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
@ ICMP_TYPE_ECHO_REQUEST
Definition: icmp.h:57
#define TRACE_INFO(...)
Definition: debug.h:95
Socket * socketOpen(uint_t type, uint_t protocol)
Create a socket (UDP or TCP)
Definition: socket.c:122
#define MIN(a, b)
Definition: os_port.h:62
size_t length
Definition: ip.h:80
#define ENABLED
Definition: os_port.h:37
#define socketBindToInterface
Definition: net_legacy.h:193
uint32_t netGetRand(void)
Generate a random 32-bit value.
Definition: net.c:325
uint8_t buffer[PING_BUFFER_SIZE]
Definition: ping.h:83
uint32_t systime_t
System time.
uint16_t ipCalcUpperLayerChecksum(const void *pseudoHeader, size_t pseudoHeaderLen, const void *data, size_t dataLen)
Calculate IP upper-layer checksum.
Definition: ip.c:665
@ ERROR_TIMEOUT
Definition: error.h:95
Ipv4Addr ipv4Addr
Definition: ip.h:84
uint32_t time
IPv4 and IPv6 common routines.
@ ICMP_TYPE_ECHO_REPLY
Definition: icmp.h:53
error_t pingSetTimeout(PingContext *context, systime_t timeout)
Set timeout value.
Definition: ping.c:146
@ SOCKET_IP_PROTO_ICMP
Definition: socket.h:91
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:781
error_t pingWaitForReply(PingContext *context, IpAddr *targetIpAddr, systime_t *rtt)
Wait for a matching ICMP Echo Reply message.
Definition: ping.c:457
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:1010
IPv4 (Internet Protocol Version 4)
uint32_t ttl
Definition: dns_common.h:205
Ipv6Addr ipv6Addr
Definition: ip.h:87
#define PRIuSIZE
systime_t rtt
Definition: ping.h:82
#define osMemset(p, value, length)
Definition: os_port.h:131
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:145
__start_packed struct @0 Ipv6Addr
IPv6 network address.
@ NO_ERROR
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:472
systime_t osGetSystemTime(void)
Retrieve system time.
Ipv4Addr destIpAddr
Definition: ipcp.h:78