Search code examples
pythonsocketstcpclient

Python Binding Socket: “Address already in use”, after closing socket


I know there is a similar question already, but none of the solutions solve my problem. Over ssh I am starting a script on a remote client with

nohup python script.py &

This script contains the following:

TCP_PORT = 5005
host = ""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.settimeout(40)
s.bind((host, TCP_PORT))
s.listen(0)
c, addr = s.accept()

...some code...

try:
    while True:
        c.send(str(1).ljust(16).encode())
except Exception as e:
    print("exiting main")
    print(e)
    c.close()
    s.close()

When I run the code two times in e row, the second time I always get the above mentioned error. The log of the python output:

exiting main
[Errno 32] Broken pipe

Traceback (most recent call last):
  File "LogImages.py", line 204, in <module>
    main(interv)
  File "LogImages.py", line 114, in main
    s.bind((host, TCP_PORT))
OSError: [Errno 98] Address already in use

So obviously the process calls c.close() and s.close(). So how can the address still be in use?


Solution

  • Closing a socket just releases the handle to any underlying connection. It can still take the implementation some amount of time to complete the orderly shutdown of the connection and, during that time, the address is still in use.

    For example, if you have an active connection and the other side isn't reading from it, the implementation will give it time to read the data that was sent. During that time, the address is still in use.