0

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?

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer. This was the problem. I guess just stop reading and calling s.close() was the wrong approach. I know call s.shutdown() on the host and keep on reading until the connection is closed. This way I can immediately reuse the address.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.