WorkerBee
WorkerBee

Reputation: 693

How to implement TCP SO_KEEPALIVE in C on LINUX (Ubuntu)

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);

    }

Upvotes: 2

Views: 9026

Answers (2)

user207421
user207421

Reputation: 310868

If TCP KEEPALIVE fails you get an error in the next read or write to the socket after the detection, typically ECONNRESET. It isn't distinguishable as a KEEPALIVE failure specifically, just a general I/O error, which is what it is, really.

Upvotes: 1

Joe
Joe

Reputation: 7798

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.

Upvotes: 3

Related Questions