3

how I will use setsockopt and getsockopt in linux c programming to determine broken tcp/ip connection?

jxh
  • 69,070
  • 8
  • 110
  • 193
Feanix
  • 39
  • 1
  • 1
  • 3

3 Answers3

6

From the TCP man page:

To set or get a TCP socket option, call getsockopt(2) to read or setsockopt(2) to write the option with the option level argument set to IPPROTO_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));
jxh
  • 69,070
  • 8
  • 110
  • 193
3

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

Community
  • 1
  • 1
lulyon
  • 6,707
  • 7
  • 32
  • 49
  • 1
    Did you copy that from an example for `SO_REUSEADDR`? The name `reuse` looks weird. –  Jul 19 '13 at 07:49
  • @WumpusQ.Wumbley Thanks for pointing out that. I got the code from APUE. I've edited it now. – lulyon Jul 19 '13 at 07:53
1

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

Alt Eisen
  • 598
  • 6
  • 9