Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close server socket on quit/crash

I'm learning how to use sockets in python, and quite often when my program crashes or I Ctrl+C the server socket somehow stays listening on the port. This obviously stops the program from listening on that port when it starts back up again, so I have to keep changing it.

I'm guessing I need to do socket.close() somewhere, but where?

like image 202
Matt Avatar asked Oct 14 '11 11:10

Matt


2 Answers

You could try the atexit module.

import atexit

function close_socket:
    s.close()

atexit.register(close_socket)

If the issue is delays in the port becoming available during testing, I would suggest setting SO_REUSEADDR which will allow the port to be bound again immediately instead of waiting for timeouts on the TCP stack.

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
like image 150
Michael Mior Avatar answered Oct 15 '22 13:10

Michael Mior


Terminating a program makes all its sockets automatically close. However, the TCP ports are still kept in use after that. The UNIX socket FAQ has a really long explanation in section 2.7.

For testing purposes, it may be best to ask for an arbitrary port (or ask for successive ones, like 8000, 8001, 8002, ...) and output that port in the console.

like image 30
phihag Avatar answered Oct 15 '22 14:10

phihag