Skip to content

Instantly share code, notes, and snippets.

@cwyang
Last active February 16, 2021 02:07
Show Gist options
  • Save cwyang/e29e77f3134fd4c929f9596db83b094c to your computer and use it in GitHub Desktop.
Save cwyang/e29e77f3134fd4c929f9596db83b094c to your computer and use it in GitHub Desktop.
open SSL connection with TCP keepalive
import socket
import ssl
def set_keepalive_linux(sock, after_idle_sec=1, interval_sec=3, max_fails=5):
"""Set TCP keepalive on an open socket.
It activates after 1 second (after_idle_sec) of idleness,
then sends a keepalive ping once every 3 seconds (interval_sec),
and closes the connection after 5 failed ping (max_fails), or 15 seconds
"""
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_sec)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval_sec)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails)
hostname = 'www.python.org'
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
with socket.create_connection((hostname, 443)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
set_keepalive_linux(ssock)
print(ssock.version())
print(ssock.cipher())
print(ssock.getpeercert())
print(ssock.recv(1024))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment