What is the best way to implement a heartbeat in C++ to check for socket connectivity?

Alex picture Alex · Jan 30, 2009 · Viewed 17.3k times · Source

Hey gang. I have just written a client and server in C++ using sys/socket. I need to handle a situation where the client is still active but the server is down. One suggested way to do this is to use a heartbeat to periodically assert connectivity. And if there is none to try to reconnect every X seconds for Y period of time, and then to time out.

Is this "heartbeat" the best way to check for connectivity?

The socket I am using might have information on it, is there a way to check that there is a connection without messing with the buffer?

Answer

Commodore Jaeger picture Commodore Jaeger · Jan 30, 2009

If you're using TCP sockets over an IP network, you can use the TCP protocol's keepalive feature, which will periodically check the socket to make sure the other end is still there. (This also has the advantage of keeping the forwarding record for your socket valid in any NAT routers between your client and your server.)

Here's a TCP keepalive overview which outlines some of the reasons you might want to use TCP keepalive; this Linux-specific HOWTO describes how to configure your socket to use TCP keepalive at runtime.

It looks like you can enable TCP keepalive in Windows sockets by setting SIO_KEEPALIVE_VALS using the WSAIoctl() function.

If you're using UDP sockets over IP you'll need to build your own heartbeat into your protocol.