socket.bind

Peter Hansen peter at engcorp.com
Sat Oct 4 21:29:25 EDT 2003


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.

You need to use setsockopt() to set the SO_REUSE_ADDR option:

  yourSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

-Peter




More information about the Python-list mailing list