ICMP (Internet Control Message Protocol) is used for diagnostic or control purposes or generated in response to errors in IP operations. The common network util ``ping`` is implemented based on the ICMP packets with the type field value of 0, also called ``Echo Reply``.
During a ping session, the source host firstly sends out an ICMP echo request packet and wait for an ICMP echo reply with specific times. In this way, it also measures the round-trip time for the messages. After receiving a valid ICMP echo reply, the source host will generate statistics about the IP link layer (e.g. packet loss, elapsed time, etc).
It is common that IoT device needs to check whether a remote server is alive or not. The device should show the warnings to users when it got offline. It can be achieved by creating a ping session and sending/parsing ICMP echo packets periodically.
To make this internal procedure much easier for users, ESP-IDF provides some out-of-box APIs.
Create a new ping session
^^^^^^^^^^^^^^^^^^^^^^^^^
To create a ping session, you need to fill in the ``esp_ping_config_t`` configuration structure firstly, specifying target IP address, interval times, and etc. Optionally, you can also register some callback functions with the `esp_ping_callbacks_t`` structure.
Example method to create a new ping session and register callbacks:
ping_config.target_addr = target_addr; // target IP address
ping_config.count = ESP_PING_COUNT_INFINITE; // ping in infinite mode, esp_ping_stop can stop it
/* set callback functions */
esp_ping_callbacks_t cbs;
cbs.on_ping_success = test_on_ping_success;
cbs.on_ping_timeout = test_on_ping_timeout;
cbs.on_ping_end = test_on_ping_end;
cbs.cb_args = "foo"; // arguments that will feed to all callback functions, can be NULL
cbs.cb_args = eth_event_group;
esp_ping_handle_t ping;
esp_ping_new_session(&ping_config, &cbs, &ping);
}
Start and Stop ping session
^^^^^^^^^^^^^^^^^^^^^^^^^^^
You can start and stop ping session with the handle returned by ``esp_ping_new_session``. Note that, the ping session won't start automatically after creation. If the ping session is stopped, and restart again, the sequence number in ICMP packets will recount from zero again.
Delete a ping session
^^^^^^^^^^^^^^^^^^^^^
If a ping session won't be used any more, you can delete it with ``esp_ping_delete_session``. Please make sure the ping session is in stop state (i.e. you have called ``esp_ping_stop`` before or the ping session has finished all the procedures) when you call this function.
Get runtime statistics
^^^^^^^^^^^^^^^^^^^^^^
As the example code above, you can call ``esp_ping_get_profile`` to get different runtime statistics of ping session in the callback function.