JeffV
JeffV

Reputation: 54487

How do I set TCP Keep Alive to a specific value using Boost ASIO?

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?

Upvotes: 2

Views: 3409

Answers (1)

Dmitry Shkuropatsky
Dmitry Shkuropatsky

Reputation: 3965

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.

Upvotes: 1

Related Questions