elzell
elzell

Reputation: 2306

Python socket programming: "Address already in use" after exception

I have a little server running on my Raspberry Pi which listens at a specific port. However, whenever an exception occurs during a connection and the connection is terminated, it seems that the assignment to the port is not "unbound".

This is an example code:

import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind(('', 5005))
    s.listen(1)
    with s.accept()[0] as c:
        raise Exception() # Act as if anything goes wrong

When I run it for the first time and do a telnet localhost 5005 on another terminal, the connection is made and the server raises the Exception as expected. However, when I try to run it for a second time, I get this error:

Traceback (most recent call last):
  File "testsocketexception.py", line 4, in <module>
    s.bind(('', 5005))
OSError: [Errno 98] Address already in use

How can I make sure that the socket is unbound even if an exception is raised on the server? (By the way, this doesn't seem to happen in Windows.)

Upvotes: 2

Views: 1814

Answers (1)

falsetru
falsetru

Reputation: 369074

Set SO_REUSEADDR socket option before binding the socket.

the SO_REUSEADDR flag tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire.

from socket documentation


with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(('', 5005))
    ...

NOTE: You will get an error even if you apply this, if there's TIME_WAIT socket is remained from the previous run (without the SO_REUSEADDR option).

Upvotes: 4

Related Questions