cpprestsdk icon indicating copy to clipboard operation
cpprestsdk copied to clipboard

Add a socket options callback to enable setting TCP keepalive

Open lo-simon opened this issue 3 months ago • 1 comments

This callback enables the user to customise the socket options, such as adding TCP keepalive. It uses a similar style to the http_client_config for the http_listener_config.

Here is an example of using the callback to set the TCP keepalive.

inline std::function<void(boost::asio::ip::tcp::socket&)> make_listener_tcp_socket_callback()
{
    const int keepalive = 1;
    const int idle = 5;
    const int intvl = 2;
    const int cnt = 3;

    return [&](boost::asio::ip::tcp::socket& sock)
    {
        if (0 == setsockopt(sock.native_handle(), SOL_SOCKET, SO_KEEPALIVE, (const char*)&keepalive, sizeof(keepalive)))
        {
            if (keepalive)
            {
                // set keepalive parameters
                // Note: Windows does not support setsockopt(..., TCP_KEEPIDLE / TCP_KEEPINTVL / TCP_KEEPCNT) use WSAIoctl(SIO_KEEPALIVE_VALS)
                // to set keepalive parameters
#ifdef _WIN32
                tcp_keepalive ka = { 1, idle*1000, intvl*1000 };
                DWORD bytes = 0;
                WSAIoctl(sock.native_handle(), SIO_KEEPALIVE_VALS, &ka, sizeof(ka), NULL, 0, &bytes, NULL, NULL);
#else
                // The time (in seconds) the connection needs to remain idle before TCP starts sending keepalive probes
                setsockopt(sock.native_handle(), IPPROTO_TCP, TCP_KEEPIDLE, (const char*)&idle, sizeof(idle));

                // The time (in seconds) between individual keepalive probes
                setsockopt(sock.native_handle(), IPPROTO_TCP, TCP_KEEPINTVL, (const char*)&intvl, sizeof(intvl));

                // The maximum number of keepalive probes TCP should send before dropping the connection
                setsockopt(sock.native_handle(), IPPROTO_TCP, TCP_KEEPCNT, (const char*)&cnt, sizeof(cnt));
#endif // _WIN32
            }
        }
        else
        {
            std::cerr << "Unable to set socket keepalive";
        }
    };
}

lo-simon avatar Oct 24 '25 20:10 lo-simon

@microsoft-github-policy-service agree company="Sony Corporation"

lo-simon avatar Oct 29 '25 09:10 lo-simon