From b53ebf712e51d61049b84a4a13b759c02d128f48 Mon Sep 17 00:00:00 2001 From: Fabio Zadrozny Date: Fri, 4 Jun 2021 11:20:51 -0300 Subject: [PATCH] Set keepalive for all debugpy sockets. Fixes #626 --- src/debugpy/common/sockets.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/debugpy/common/sockets.py b/src/debugpy/common/sockets.py index 75603f8d9..2a79e442a 100644 --- a/src/debugpy/common/sockets.py +++ b/src/debugpy/common/sockets.py @@ -43,6 +43,27 @@ def _new_sock(): sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) else: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + + # Set TCP keepalive on an open socket. + # It activates after 1 second (TCP_KEEPIDLE,) of idleness, + # then sends a keepalive ping once every 3 seconds (TCP_KEEPINTVL), + # and closes the connection after 5 failed ping (TCP_KEEPCNT), or 15 seconds + try: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + except (AttributeError, OSError): + pass # May not be available everywhere. + try: + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1) + except (AttributeError, OSError): + pass # May not be available everywhere. + try: + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 3) + except (AttributeError, OSError): + pass # May not be available everywhere. + try: + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5) + except (AttributeError, OSError): + pass # May not be available everywhere. return sock