Skip to content Skip to sidebar Skip to footer

How To Close Socket Connection On Ctrl-c In A Python Programme

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) any_connection = False while True: try: conn, addr = s.accept() data =

Solution 1:

As per the docs the error OSError: [Errno 48] Address already in use occurs because the previous execution of your script has left the socket in a TIME_WAIT state, and can’t be immediately reused. This can be resolved by using the socket.SO_REUSEADDR flag.

For eg:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))

Solution 2:

You need to register a hook for this, something like:

#!/usr/bin/env pythonimport signal
import sys
defsignal_handler(signal, frame):
        # close the socket here
        sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)

Post a Comment for "How To Close Socket Connection On Ctrl-c In A Python Programme"