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-2024 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.4.0
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  {
236  message->data[i] = i & 0xFF;
237  }
238 
239  //Length of the complete ICMP message including header and data
240  length = sizeof(IcmpEchoMessage) + context->dataPayloadSize;
241 
242  //Select the relevant network interface
243  interface = context->interface;
244 
245 #if (IPV4_SUPPORT == ENABLED)
246  //Is target address an IPv4 address?
247  if(targetIpAddr->length == sizeof(Ipv4Addr))
248  {
250 
251  //Select the source IPv4 address and the relevant network
252  //interface to use when pinging the specified host
253  error = ipv4SelectSourceAddr(&interface, targetIpAddr->ipv4Addr,
254  &srcIpAddr);
255  //Any error to report?
256  if(error)
257  return error;
258 
259  //ICMP Echo Request message
261  //Message checksum calculation
262  message->checksum = ipCalcChecksum(message, length);
263 
264  //Open a raw socket
266  }
267  else
268 #endif
269 #if (IPV6_SUPPORT == ENABLED)
270  //Is target address an IPv6 address?
271  if(targetIpAddr->length == sizeof(Ipv6Addr))
272  {
273  Ipv6PseudoHeader pseudoHeader;
274 
275  //Select the source IPv6 address and the relevant network interface
276  //to use when pinging the specified host
277  error = ipv6SelectSourceAddr(&interface, &targetIpAddr->ipv6Addr,
278  &pseudoHeader.srcAddr);
279  //Any error to report?
280  if(error)
281  return error;
282 
283  //ICMPv6 Echo Request message
285 
286  //Format IPv6 pseudo header
287  pseudoHeader.destAddr = targetIpAddr->ipv6Addr;
288  pseudoHeader.length = htonl(length);
289  pseudoHeader.reserved[0] = 0;
290  pseudoHeader.reserved[1] = 0;
291  pseudoHeader.reserved[2] = 0;
292  pseudoHeader.nextHeader = IPV6_ICMPV6_HEADER;
293 
294  //Message checksum calculation
295  message->checksum = ipCalcUpperLayerChecksum(&pseudoHeader,
296  sizeof(Ipv6PseudoHeader), message, length);
297 
298  //Open a raw socket
300  }
301  else
302 #endif
303  //Invalid target address?
304  {
305  //Report an error
306  return ERROR_INVALID_ADDRESS;
307  }
308 
309  //Failed to open socket?
310  if(context->socket == NULL)
311  return ERROR_OPEN_FAILED;
312 
313  //Set the TTL value to be used
314  context->socket->ttl = ttl;
315 
316  //Start of exception handling block
317  do
318  {
319  //Associate the newly created socket with the relevant interface
320  error = socketBindToInterface(context->socket, interface);
321  //Unable to bind the socket to the desired interface?
322  if(error)
323  break;
324 
325  //Debug message
326  TRACE_INFO("Sending ICMP echo request to %s (%" PRIuSIZE " bytes)...\r\n",
327  ipAddrToString(targetIpAddr, NULL), length);
328 
329  //Send Echo Request message
330  error = socketSendTo(context->socket, targetIpAddr, 0,
331  message, length, NULL, 0);
332  //Failed to send message ?
333  if(error)
334  break;
335 
336  //Save the time at which the request was sent
337  context->timestamp = osGetSystemTime();
338 
339  //End of exception handling block
340  } while(0);
341 
342  //Any error to report?
343  if(error)
344  {
345  //Clean up side effects
346  socketClose(context->socket);
347  context->socket = NULL;
348  }
349 
350  //Return status code
351  return error;
352 }
353 
354 
355 /**
356  * @brief Check whether an incoming ICMP message is acceptable
357  * @param[in] context Pointer to the ping context
358  * @param[in] srcIpAddr Source IP address
359  * @param[in] destIpAddr Destination IP address
360  * @param[in] message Pointer to the incoming ICMP message
361  * @param[in] length Length of the message, in bytes
362  * @return Error code
363  **/
364 
366  const IpAddr *destIpAddr, const IcmpEchoMessage *message, size_t length)
367 {
368  size_t i;
369 
370  //Check message length
371  if(length != (sizeof(IcmpEchoMessage) + context->dataPayloadSize))
372  return ERROR_INVALID_MESSAGE;
373 
374 #if (IPV4_SUPPORT == ENABLED)
375  //Is target address an IPv4 address?
376  if(context->socket->protocol == SOCKET_IP_PROTO_ICMP)
377  {
378  //Check address type
379  if(destIpAddr->length != sizeof(Ipv4Addr))
380  return ERROR_INVALID_MESSAGE;
381 
382  //Check message type
383  if(message->type != ICMP_TYPE_ECHO_REPLY)
384  return ERROR_INVALID_MESSAGE;
385 
386  //Verify checksum value
387  if(ipCalcChecksum(message, length) != 0x0000)
388  return ERROR_INVALID_MESSAGE;
389  }
390  else
391 #endif
392 #if (IPV6_SUPPORT == ENABLED)
393  //Is target address an IPv6 address?
394  if(context->socket->protocol == SOCKET_IP_PROTO_ICMPV6)
395  {
396  Ipv6PseudoHeader pseudoHeader;
397 
398  //Check address type
399  if(destIpAddr->length != sizeof(Ipv6Addr))
400  return ERROR_INVALID_MESSAGE;
401 
402  //Check message type
403  if(message->type != ICMPV6_TYPE_ECHO_REPLY)
404  return ERROR_INVALID_MESSAGE;
405 
406  //Format IPv6 pseudo header
407  pseudoHeader.srcAddr = srcIpAddr->ipv6Addr;
408  pseudoHeader.destAddr = destIpAddr->ipv6Addr;
409  pseudoHeader.length = htonl(length);
410  pseudoHeader.reserved[0] = 0;
411  pseudoHeader.reserved[1] = 0;
412  pseudoHeader.reserved[2] = 0;
413  pseudoHeader.nextHeader = IPV6_ICMPV6_HEADER;
414 
415  //Verify checksum value
416  if(ipCalcUpperLayerChecksum(&pseudoHeader,
417  sizeof(Ipv6PseudoHeader), message, length) != 0x0000)
418  {
419  //The checksum is not valid
420  return ERROR_INVALID_MESSAGE;
421  }
422  }
423  else
424 #endif
425  //Invalid target address?
426  {
427  //Report an error
428  return ERROR_INVALID_ADDRESS;
429  }
430 
431  //Make sure the response identifier matches the request identifier
432  if(message->identifier != context->identifier)
433  return ERROR_INVALID_MESSAGE;
434  //Make sure the sequence number is correct
435  if(message->sequenceNumber != context->sequenceNumber)
436  return ERROR_INVALID_MESSAGE;
437 
438  //Verify data payload
439  for(i = 0; i < context->dataPayloadSize; i++)
440  {
441  //Compare received data against expected data pattern
442  if(message->data[i] != (i & 0xFF))
443  return ERROR_INVALID_MESSAGE;
444  }
445 
446  //The ICMP Echo Reply message is acceptable
447  return NO_ERROR;
448 }
449 
450 
451 /**
452  * @brief Wait for a matching ICMP Echo Reply message
453  * @param[in] context Pointer to the ping context
454  * @param[out] targetIpAddr IP address of the remote host (optional parameter)
455  * @param[out] rtt Round-trip time (optional parameter)
456  * @return Error code
457  **/
458 
460  IpAddr *targetIpAddr, systime_t *rtt)
461 {
462  error_t error;
463  size_t length;
464  systime_t time;
465  systime_t timeout;
468 
469  //Invalid context?
470  if(context == NULL)
472 
473  //Wait for an ICMP Echo Reply message
474  do
475  {
476  //Get current time
477  time = osGetSystemTime();
478 
479  //Compute the timeout to be used
480  if(timeCompare(time, context->timestamp + context->timeout) < 0)
481  {
482  timeout = context->timestamp + context->timeout - time;
483  }
484  else
485  {
486  timeout = 0;
487  }
488 
489  //Adjust receive timeout
490  error = socketSetTimeout(context->socket, timeout);
491  //Any error to report?
492  if(error)
493  break;
494 
495  //Wait for an incoming ICMP message
496  error = socketReceiveEx(context->socket, &srcIpAddr, NULL,
497  &destIpAddr, context->buffer, PING_BUFFER_SIZE, &length, 0);
498 
499 #if (NET_RTOS_SUPPORT == DISABLED)
500  //Catch timeout exception
501  if(error == ERROR_TIMEOUT)
502  error = ERROR_WOULD_BLOCK;
503 #endif
504 
505  //Get current time
506  time = osGetSystemTime();
507 
508  //Check status code
509  if(!error)
510  {
511  //Check whether the incoming ICMP message is acceptable
512  error = pingCheckReply(context, &srcIpAddr, &destIpAddr,
513  (IcmpEchoMessage *) context->buffer, length);
514  }
515 
516  //Check status code
517  if(!error)
518  {
519  //Calculate round-trip time
520  context->rtt = time - context->timestamp;
521 
522  //Debug message
523  TRACE_INFO("ICMP echo reply received from %s (%" PRIu32 " ms)...\r\n",
524  ipAddrToString(&srcIpAddr, NULL), context->rtt);
525 
526  //Return the IP address of the host
527  if(targetIpAddr != NULL)
528  *targetIpAddr = srcIpAddr;
529 
530  //Return the round-trip time
531  if(rtt != NULL)
532  *rtt = context->rtt;
533  }
534  else
535  {
536  //Timeout value exceeded?
537  if(timeCompare(time, context->timestamp + context->timeout) >= 0)
538  {
539  //Report an error
540  error = ERROR_TIMEOUT;
541  }
542  }
543 
544  //Wait for the next incoming ICMP message
545  } while(error == ERROR_INVALID_MESSAGE);
546 
547  //Return status code
548  return error;
549 }
550 
551 
552 /**
553  * @brief Release ping context
554  * @param[in] context Pointer to the ping context
555  **/
556 
557 void pingRelease(PingContext *context)
558 {
559  //Make sure the context is valid
560  if(context != NULL)
561  {
562  //Close underlying socket
563  if(context->socket != NULL)
564  {
565  socketClose(context->socket);
566  context->socket = NULL;
567  }
568  }
569 }
570 
571 #endif
uint8_t message[]
Definition: chap.h:154
#define PRIuSIZE
#define htonl(value)
Definition: cpu_endian.h:414
Debugging facilities.
#define TRACE_INFO(...)
Definition: debug.h:95
uint32_t time
uint32_t ttl
Definition: dns_common.h:221
error_t
Error codes.
Definition: error.h:43
@ ERROR_WOULD_BLOCK
Definition: error.h:96
@ ERROR_INVALID_ADDRESS
Definition: error.h:103
@ ERROR_TIMEOUT
Definition: error.h:95
@ ERROR_INVALID_MESSAGE
Definition: error.h:105
@ ERROR_OPEN_FAILED
Definition: error.h:75
@ NO_ERROR
Success.
Definition: error.h:44
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
ICMP (Internet Control Message Protocol)
@ ICMP_TYPE_ECHO_REPLY
Definition: icmp.h:53
@ ICMP_TYPE_ECHO_REQUEST
Definition: icmp.h:57
IcmpEchoMessage
Definition: icmp.h:186
ICMPv6 (Internet Control Message Protocol Version 6)
@ ICMPV6_TYPE_ECHO_REQUEST
Definition: icmpv6.h:57
@ ICMPV6_TYPE_ECHO_REPLY
Definition: icmpv6.h:58
uint16_t ipCalcUpperLayerChecksum(const void *pseudoHeader, size_t pseudoHeaderLen, const void *data, size_t dataLen)
Calculate IP upper-layer checksum.
Definition: ip.c:692
char_t * ipAddrToString(const IpAddr *ipAddr, char_t *str)
Convert a binary IP address to a string representation.
Definition: ip.c:838
uint16_t ipCalcChecksum(const void *data, size_t length)
IP checksum calculation.
Definition: ip.c:499
IPv4 and IPv6 common routines.
Ipv4Addr destIpAddr
Definition: ipcp.h:80
Ipv4Addr srcIpAddr
Definition: ipcp.h:79
IPv4 (Internet Protocol Version 4)
uint32_t Ipv4Addr
IPv4 network address.
Definition: ipv4.h:267
#define IPV4_SUPPORT
Definition: ipv4.h:48
error_t ipv4SelectSourceAddr(NetInterface **interface, Ipv4Addr destAddr, Ipv4Addr *srcAddr)
IPv4 source address selection.
Definition: ipv4_misc.c:202
Helper functions for IPv4.
IPv6 (Internet Protocol Version 6)
Ipv6Addr
Definition: ipv6.h:251
@ IPV6_ICMPV6_HEADER
Definition: ipv6.h:186
#define Ipv6PseudoHeader
Definition: ipv6.h:42
error_t ipv6SelectSourceAddr(NetInterface **interface, const Ipv6Addr *destAddr, Ipv6Addr *srcAddr)
IPv6 source address selection.
Definition: ipv6_misc.c:895
Helper functions for IPv6.
uint32_t netGetRand(void)
Generate a random 32-bit value.
Definition: net.c:385
TCP/IP stack core.
#define NetInterface
Definition: net.h:36
#define netMutex
Definition: net_legacy.h:195
#define socketBindToInterface
Definition: net_legacy.h:193
#define osMemset(p, value, length)
Definition: os_port.h:135
#define timeCompare(t1, t2)
Definition: os_port.h:40
#define MIN(a, b)
Definition: os_port.h:63
#define ENABLED
Definition: os_port.h:37
void osAcquireMutex(OsMutex *mutex)
Acquire ownership of the specified mutex object.
void osReleaseMutex(OsMutex *mutex)
Release ownership of the specified mutex object.
systime_t osGetSystemTime(void)
Retrieve system time.
uint32_t systime_t
System time.
error_t pingSendRequest(PingContext *context, const IpAddr *targetIpAddr, size_t size, uint8_t ttl)
Send an ICMP Echo Request message.
Definition: ping.c:190
void pingRelease(PingContext *context)
Release ping context.
Definition: ping.c:557
error_t pingBindToInterface(PingContext *context, NetInterface *interface)
Select a particular network interface.
Definition: ping.c:167
error_t pingWaitForReply(PingContext *context, IpAddr *targetIpAddr, systime_t *rtt)
Wait for a matching ICMP Echo Reply message.
Definition: ping.c:459
void pingInit(PingContext *context)
Initialize ping context.
Definition: ping.c:125
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
error_t pingSetTimeout(PingContext *context, systime_t timeout)
Set timeout value.
Definition: ping.c:146
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:365
Ping utility.
#define PING_BUFFER_SIZE
Definition: ping.h:61
#define PING_MAX_DATA_SIZE
Definition: ping.h:55
#define PING_DEFAULT_TIMEOUT
Definition: ping.h:48
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:967
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:1196
Socket * socketOpen(uint_t type, uint_t protocol)
Create a socket (UDP or TCP)
Definition: socket.c:125
error_t socketSetTimeout(Socket *socket, systime_t timeout)
Set timeout value for blocking operations.
Definition: socket.c:148
void socketClose(Socket *socket)
Close an existing socket.
Definition: socket.c:1517
Socket API.
@ SOCKET_IP_PROTO_ICMPV6
Definition: socket.h:102
@ SOCKET_IP_PROTO_ICMP
Definition: socket.h:98
@ SOCKET_TYPE_RAW_IP
Definition: socket.h:87
IP network address.
Definition: ip.h:79
Ipv6Addr ipv6Addr
Definition: ip.h:87
Ipv4Addr ipv4Addr
Definition: ip.h:84
size_t length
Definition: ip.h:80
Ping context.
Definition: ping.h:74
systime_t timestamp
Definition: ping.h:80
uint16_t identifier
Definition: ping.h:78
uint16_t sequenceNumber
Definition: ping.h:79
size_t dataPayloadSize
Definition: ping.h:77
systime_t rtt
Definition: ping.h:82
systime_t timeout
Definition: ping.h:81
Socket * socket
Definition: ping.h:76
uint8_t buffer[PING_BUFFER_SIZE]
Definition: ping.h:83
NetInterface * interface
Definition: ping.h:75
uint8_t length
Definition: tcp.h:368