libcoap  4.3.0beta


coap_keepalive, coap_context_set_keepalive — Work with CoAP keepalive


#include <coap2/coap.h>

void void coap_context_set_keepalive(coap_context_t *context, unsigned int seconds);

Link with -lcoap-2, -lcoap-2-gnutls, -lcoap-2-openssl or -lcoap-2-tinydtls depending on your (D)TLS library type.


There may be a requirement to send out keepalive traffic when the CoAP session is idle (no packets have been sent or received for a specified period) to keep, say, an interim NAT device "warm" with the NAT translation state, or to periodically check whether the device at the other end of the session has "gone away".

For DTLS, this is done with the confirmable CoAP (0.00) Ping packet, which solicits a CoAP RST response. For TLS, this is done with Coap (7.02) Ping packet, which solicits a CoAP (7.03) Pong response, all handled by libcoap.

The coap_context_set_keepalive() function needs to be called to update the context with the keepalive for idle traffic timeout of seconds. If seconds is set to 0, then the sending of keepalives is disabled. Any sessions created from this context will use the same seconds value to determine whether a keepalive "ping" is to be sent out or not.

Applications can track the usage of the receipt of "pings" and receipt of "responses" by defining the respective handlers to use by using coap_register_ping_handler() and coap_register_pong_handler().

If the keepalive fails to solicit a response, then this can be tracked by defining the handler to use by using coap_register_nack_handler() which will be called with a reason of COAP_NACK_TOO_MANY_RETRIES.


coap_context_set_keepalive() is supported by both the CoAP client and CoAP server.


"RFC7252: The Constrained Application Protocol (CoAP)"

"RFC8323: CoAP (Constrained Application Protocol) over TCP, TLS, and WebSockets"


Please report bugs on the mailing list for libcoap: or raise an issue on GitHub at


The libcoap project <>