Keep-Alive Heartbeats & Socket Zombie Pruning
If a mobile client disconnects abruptly without sending a TCP `FIN` packet, the server's socket remains in `ESTABLISHED` state indefinitely. Enabling `SO_KEEPALIVE` instructs the kernel to probe silent connections and prune dead zombie sockets 💓.
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Enable kernel-level TCP Keep-Alive probes:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
enabled = sock.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE)
print(f"Keep-Alive active: {bool(enabled)} 💓")
sock.close()
# 12. Keep-Alive Heartbeats & Socket Zombie Pruning If a mobile client disconnects abruptly without sending a TCP `FIN` packet, the server's socket remains in `ESTABLISHED` state indefinitely. Enabling `SO_KEEPALIVE` instructs the kernel to probe silent connections and prune dead zombie sockets 💓. ```python import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Enable kernel-level TCP Keep-Alive probes: sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) enabled = sock.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) print(f"Keep-Alive active: {bool(enabled)} 💓") sock.close() ``` On Linux, you can fine-tune probe intervals via `TCP_KEEPIDLE` (idle time before first probe), `TCP_KEEPINTVL` (interval between retries), and `TCP_KEEPCNT` (dropped probes before aborting the socket connection) ⚡! --- ### Question What catastrophic resource leak occurs when clients disconnect silently if TCP Keep-Alive is disabled? 🧠- [ ] a. Sockets linger in ESTABLISHED state forever, leaking file descriptors and kernel memory buffers (zombie sockets) 💓 - [ ] b. The server's IP address is revoked by the local DHCP server - [ ] c. Python garbage collection crashes due to circular pointer references - [ ] d. Network routers reroute incoming traffic to localhost --- ### Challenge Create a TCP socket. Enable `socket.SO_KEEPALIVE`. Query via `getsockopt` and print `bool(val)`. Clean up the socket. 🎯 <details> <summary>Solution</summary> ```python import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) val = s.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) s.close() print(bool(val)) ``` </details>