socket.bind

S

sashan

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.
 
P

Peter Hansen

sashan said:
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
 
J

Jp Calderone

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top