socket.bind

Jp Calderone exarkun at intarweb.us
Sat Oct 4 22:54:18 EDT 2003


On Sun, Oct 05, 2003 at 01:00:46PM +1300, sashan wrote:
> I'm writing a program using sockets. I'm binding to a port like this:
> 	
> PORT = 5000              # Arbitrary non-privileged port
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.bind((HOST, PORT))
> s.listen(1)
> 
> Now sometimes the rest of the program crashes later for whatever reason. 
> As a result this leaves a socket bound to port 5000. When I try to run 
> my program again it crashes at
> 
> s.bind((HOST, PORT))
> 
> saying that the port is still in use. How do I unbind that port? I've 
> killed the previous program using the system monitor in Gnome.
> 

  Python programs don't crash (at least, hardly ever -- if the interpreter
segfaults, you should file a bug report!).  So, it's always possible to
clean up resources you allocate.

  In this case, setting SO_REUSEADDR is a good solution to avoid needing to
clean up, but for other resources you allocate, you might want to read up on
the try/finally construct (http://python.org/doc/tut/node10.html, especially
the last section), or use try/except and call a cleanup function in the
except clause before re-raising the original exception.

  Jp






More information about the Python-list mailing list