macchina-io / macchina.io

macchina.io EDGE is a powerful C++ and JavaScript SDK for edge devices, multi-service IoT gateways and connected embedded systems.
https://macchina.io
GNU General Public License v3.0
512 stars 152 forks source link

TCP KeepAlive options #111

Closed zaleksa closed 2 years ago

zaleksa commented 2 years ago

I have a question regarding implementation of KeepAlive mechanism for TCP connection.

The currently configured TCP Keep-Alive settings can be found in

/proc/sys/net/ipv4/tcp_keepalive_time - default 7200 seconds /proc/sys/net/ipv4/tcp_keepalive_probes - default 9 /proc/sys/net/ipv4/tcp_keepalive_intvl - default 75 seconds

Further more, if keep-alive is enabled with SO_KEEPALIVE option, then the default TCP settings are used for keep-alive timeout and interval unless these values have been changed using TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT options.

I found that macchina.io SocketImpl supports setOption(SOL_SOCKET, SO_KEEPALIVE, value) i.e. setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen), but I can't find settings of these options:

setsockopt(sockfd, SOL_TCP, TCP_KEEPIDLE, &optval, optlen) setsockopt(sockfd, SOL_TCP, TCP_KEEPINTVL, &optval, optlen) setsockopt(sockfd, SOL_TCP, TCP_KEEPCNT, &optval, optlen)

Does the implementation of TCP Socket supports changing of these options?

Regards, Aleksandar

zaleksa commented 2 years ago

Finally I managed to set TCP Socket KeepAlive options:

#define SOL_TCP         6   // Socket Level for TCP options
#define TCP_KEEPIDLE        4   // Start keepalives after this period (Linux default 7200 seconds)
#define TCP_KEEPINTVL       5   // Interval between keepalives (Linux default 75 seconds)
#define TCP_KEEPCNT     6   // Number of keepalives before death (Linux default 9)

Poco::Net::StreamSocket socket;

socket.setKeepAlive(true);

socket.setOption(SOL_TCP, TCP_KEEPIDLE, 360);   // KeepAlive Idle - 360 seconds
socket.setOption(SOL_TCP, TCP_KEEPINTVL, 75);   // KeepAlive Interval - 75 seconds
socket.setOption(SOL_TCP, TCP_KEEPCNT, 9);  // KeepAlive Count - 9

Regards, Aleksandar