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