Skip to content

Instantly share code, notes, and snippets.

@nishidy
Last active April 29, 2019 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nishidy/dd2f6f4ee39061231bc5c02126d6d4fa to your computer and use it in GitHub Desktop.
Save nishidy/dd2f6f4ee39061231bc5c02126d6d4fa to your computer and use it in GitHub Desktop.
TCP KEEPALIVE and TIME_WAIT
import socket
import time
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect(('xxxxxxxx', 8080))
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 35)
s.send(b'GET / HTTP/1.1\r\nHost: localhost')
data = s.recv(1024)
print(data)
time.sleep(180)
@nishidy
Copy link
Author

nishidy commented Apr 29, 2019

$ cat /proc/sys/net/ipv4/tcp_keepalive_time 
30
$ cat /proc/sys/net/ipv4/tcp_keepalive_intvl 
10
  • With SO_KEEPALIVE option on client side, it should send keepalive packets when tcp_keepalive_time elapses after the last packet is sent.
  • It would repeatedly send keepalive packet every tcp_keepalive_intvl until it reaches to tcp_keepalive_probes in case no ACK confirmed.
  • tcp_keepalive_time can be overwritten after the socket is created. It will be effective for the socket right after the value is changed.
  • TCP_KEEPIDLE option overwrites the value taken from tcp_keepalive_time.
  • With SO_KEEPALIVE option on server side, no effect for sending keepalive packets at all.
  • As an other note, with tcp_tw_reuse enabled (1), TIME_WAIT socket will be reused immediately instead of being blocked during tcp_fin_timeout.
  • We can find the time when TIME_WAIT socket is released with netstat -o option as follows.
   -o, --timers
       Include information related to networking timers.
State     Timer
TIME_WAIT     timewait (53.32/0/0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment