I am trying to implement the TCP SO_KEEPALIVE to close and reconnect my connection when a keep alive message does not receive a response. My problem is that I have not had any luck with this and I think (hope) it is because I am not implementing it right. Below is a example of how I am implementing this.
//var to re-set socket's timeout value
struct timeval timeout;
//creates a variable for KEEPALIVE's optval parm
int optval;
//creates a variable for KEEPALIVE's optlen parm
socklen_t optlen = sizeof(optval);
// sets KEEPALIVE parms
optval = 1;
optlen = sizeof(optval);
// turns on KEEPALIVE property on socket
if (setsockopt (Socket, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen) < 0)
{
CloseSocket(Socket, 0);
connect(Socket);
}
Your code is only showing you setting the socket option then immediately closing and reopening it. Setting the socket option will not tell you that the keepalive has failed. You’ll get that as a result of checking the socket (with a read, write, poll/select etc.) Setting the option merely turns on the keep-alive sending & checking. Look for ETIMEDOUT as the errno.