How to close socket connection on Ctrl-C in python program

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 = conn.recv(1024) any_connection = True # keep looking if not data: continue pid = os.fork() if pid == 0: server_process(data, conn) except KeyboardInterrupt: break if any_connection: print("Closing connection") conn.close() 

I pick up the KeyboardInterrupt signal here on an endlessly running TCP server that I wrote in Python. However, although I know that it closes the connection because it prints Closing Connection , when I try to restart the server, I get:

OSError: [Errno 48] Address already in use

I have no idea what is happening, because I know for sure that I am calling conn.close() .

And running killall python3 does not fix it, I keep getting an error if I don't wait a long time or change the port. I also tried grep all python3 processes, but got nothing.

I am running OS X Yosemite.

+5
source share
2 answers

According to the docs , an OSError: [Errno 48] Address already in use error OSError: [Errno 48] Address already in use , because the previous execution of your script left the socket in TIME_WAIT state and cannot be reused again. This can be solved using the socket.SO_REUSEADDR flag.

For instance,

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

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

 #!/usr/bin/env python import signal import sys def signal_handler(signal, frame): # close the socket here sys.exit(0) signal.signal(signal.SIGINT, signal_handler) 
+3
source

Source: https://habr.com/ru/post/1208584/


All Articles