pmf
pmf

Reputation: 7749

TCP/IP: set socket option for keep-alive after connection has been established

Is it possible to set a socket's SO_KEEPALIVE option (TCP keep alive interval and TCP keep alive value) after some hypothetical application level handshake? Or does it have to be set before a call to accept?

I'm concerned with interoperability between Linux, Windows and the eCos lwIP stack, so information about both platforms is appreciated.

Upvotes: 3

Views: 2373

Answers (1)

Ortomala Lokni
Ortomala Lokni

Reputation: 62506

As EJP said, you can set it any time. The man page says:

setsockopt() manipulate options for the socket referred to by the file descriptor sockfd.

You can set or unset SO_KEEPALIVE like this

int iOption = 1; // Turn on keep-alive, 0 = disables, 1 = enables
if (setsockopt(socketHandle, SOL_SOCKET, SO_KEEPALIVE, (const char *) &iOption,  sizeof(int)) == SOCKET_ERROR)
    {
           cerr << "Set keepalive: Keepalive option failed" << endl;
    }

You can also read this tutorial for more details.

Upvotes: 4

Related Questions