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

空扰寡人 提交于 2021-01-28 03:03:39

问题


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?


回答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.



来源:https://stackoverflow.com/questions/9085286/how-do-i-set-tcp-keep-alive-to-a-specific-value-using-boost-asio

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!