Question

I wrote a program on C , where a client sent one time some information to a server. I used TCP sockets.And some time the server calculated and should to sent result to the client. How can I detect if connection on The server or the client was broken?

Was it helpful?

Solution

You may want to try TCP keepalives.

  # cat /proc/sys/net/ipv4/tcp_keepalive_time
  7200

  # cat /proc/sys/net/ipv4/tcp_keepalive_intvl
  75

  # cat /proc/sys/net/ipv4/tcp_keepalive_probes
  9`

In the above example, TCP keep-alive timer kicks in after the idle time of 7200 seconds. If the keep-alive messages are unsuccessful then they are retried at the interval of 75 seconds. After 9 successive retry failure, the connection will be brought down.

The keepalive time can be modified at boot time by placing startup script at /etc/init.d.

OTHER TIPS

There is a way to detect, on Linux, dead sockets without reading or writing to them:

  1. Get the numeric (uint) file descriptor from the socket handler.
  2. readlink the file /proc/[pid]/fd/[#hander]. If it's a socket it will return a string like socket:[#inode].
  3. Read /proc/net/tcp, search for the line with that inode (11th column).
  4. Read the status (st) column on that line (4th column). If it's 0x07 (Close) or 0x08 (TIME_WAIT), the socket is dead.

The only way I know for a program to know for certain that a TCP connection is dead is to attempt to send something on it. The attempt will either time-out or return with an error condition. Thus, the program doesn't need to do anything special -- just send the stuff it was designed to send. It does need to handle, however, all possible error-conditions. On time-out, it could retry for a limited time or decide that the connection is dead. The latter case is appropriate if sending the same data multiple times would be harmful. After this or an error condition, the program should close the current connection and, if appropriate, re-establish it.

TCP Keep-Alive is a reliable way to determine if the peer is dead.That is if the peer application exited without doing a proper closure of the open TCP connection.

http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html

Lookout for how to enable tcp keep-alives(SO_KEEPALIVE) per socket using setsockopt call.

Another method is that the client and the server application agree on heartbeats at regular intervals. Non arrival of heartbeats should indicate that the peer is dead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top