How can I detect a TCP connection in linux in C?

I wrote a program in C where the client sent some information once to the server. I used TCP sockets. And for some time the server calculated and had to send the result to the client. How can I detect that the connection on the server or client has been broken?

+3
source share
4 answers

You can 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, the TCP continue timer starts after 7200 seconds of inactivity. If keep-alive messages are unsuccessful, they are repeated at intervals of 75 seconds. After 9 consecutive attempts to reconnect, the connection will be disconnected.

keepalive , script /etc/init.d.

+3

, , , TCP- , - - . -, . , - , . , . - , . , . , , .

0

TCP Keep-Alive - , ​​. , TCP-.

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

, tcp keep-alives (SO_KEEPALIVE) setsockopt.

, . , .

0

Linux :

  1. (uint) .
  2. readlinkfile /proc/[pid]/fd/[#hander]. If it is a socket, it will return a type string socket:[#inode].
  3. Read /proc/net/tcp, find the row with this index (11th column).
  4. Read the status column ( st) in this row (4th column). If it is 0x07 (Close) or 0x08 (TIME_WAIT), the socket is dead.
0
source

Source: https://habr.com/ru/post/1613049/


All Articles