Python port binding

I recently studied python and I started playing online using the python socket library. Everything went well until recently, when my script exited without closing the connection. The next time I ran the script, I got:

 File "./alert_server.py", line 9, in <module> s.bind((HOST, PORT)) File "<string>", line 1, in bind socket.error: (98, 'Address already in use') 

So it seems that something is still bound to the port, although the python script is not working (and I checked it with $px aux . Which is strange that in a minute or so I can run the script on the same port again, and everything will be fine. Is there a way to prevent / untie the port when this happens in the future?

+6
python
source share
1 answer

What you want to do is just before bind , do:

 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 

The reason you see your behavior is because the OS reserves this particular port for some time after the last connection is completed. This means that it can correctly discard any subsequent packets that may appear after the application terminates.

By setting the SO_REUSEADDR socket option, you tell the OS that you know what you are doing, and you still want to bind to the same port.

+14
source share

All Articles