how I will use setsockopt and getsockopt with KEEP_ALIVE in linux c programming to determine broken tcp/ip connection?
Solution 1
From the TCP man page:
To set or get a TCP socket option, call
getsockopt(2)
to read orsetsockopt(2)
to write the option with the option level argument set toIPPROTO_TCP
.
Here are the relevant options:
TCP_KEEPCNT
(since Linux 2.4)
The maximum number of keepalive probes TCP should send before dropping the connection. This option should not be used in code intended to be portable.
TCP_KEEPIDLE
(since Linux 2.4)
The time (in seconds) the connection needs to remain idle before TCP starts sending keepalive probes, if the socket option SO_KEEPALIVE has been set on this socket. This option should not be used in code intended to be portable.
TCP_KEEPINTVL
(since Linux 2.4)
The time (in seconds) between individual keepalive probes. This option should not be used in code intended to be portable.
Example:
int keepcnt = 5;
int keepidle = 30;
int keepintvl = 120;
setsockopt(sock, IPPROTO_TCP, TCP_KEEPCNT, &keepcnt, sizeof(int));
setsockopt(sock, IPPROTO_TCP, TCP_KEEPIDLE, &keepidle, sizeof(int));
setsockopt(sock, IPPROTO_TCP, TCP_KEEPINTVL, &keepintvl, sizeof(int));
Solution 2
Using the socket option SO_KEEPALIVE might helps. Code from APUE:
int keepalive = 1;
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive , sizeof(keepalive ));
And reference this: Detecting a broken socket
Solution 3
As @luly and @jxh answered, Firstly, you need enable keep-alive by setting SO_KEEPALIVE. Then control the interval of normal heartbeat using TCP_KEEPIDLE, interval of abnormal (unacknowledged) heartbeats using TCP_KEEPINTVL, and threshold of abnormal heartbeats using TCP_KEEPCNT.
For the purpose of detecting a broken connection, those options need to be set from the server-side.
A detailed explanation can be found from here
Related videos on Youtube
Feanix
Updated on June 04, 2022Comments
-
Feanix almost 2 years
how I will use setsockopt and getsockopt in linux c programming to determine broken tcp/ip connection?
-
Admin almost 11 yearsDid you copy that from an example for
SO_REUSEADDR
? The namereuse
looks weird. -
lulyon almost 11 years@WumpusQ.Wumbley Thanks for pointing out that. I got the code from APUE. I've edited it now.