2

I know boost ASIO has a socket option to enable tcp keep-alive, but how can I set it to a specific value?

If not through Boost defined types, perhaps I can get the socket handle and set the option using posix setsocketopt() call?

JeffV
  • 52,985
  • 32
  • 103
  • 124

1 Answers1

1

There are two parts to keep-alive. First, it can be enabled with default values. Second, keep alive interval and timeout can be set.

For the first part you can use this:

unsigned long val = 1;
int res = setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, (char*)&val, sizeof val);

Keep-alive parameters cannot be set in posix. However, on Windows it can be done as the following:

tcp_keepalive alive;
alive.onoff = TRUE;
alive.keepalivetime = 60000; 
alive.keepaliveinterval = 1000;
int bytes_ret=0;
res = WSAIoctl(socket, SIO_KEEPALIVE_VALS, &alive, sizeof(alive), NULL, 0, 
    &bytes_ret, NULL, NULL);

Both on Windows and Linux you can define keep-alive timeout and interval system-wide.

Dmitry Shkuropatsky
  • 3,902
  • 2
  • 21
  • 13
  • In case of socket is boost::asio::ip::tcp::socket type, use socket.native(). – Hill May 20 '16 at 01:54
  • 1
    This `WSAIoctl()` call works well despite of `socket.set_option(boost::asio::socket_base::keep_alive(true))` not working in my Windows 7 PC. – Hill May 20 '16 at 02:02