How to force OS to free port with python

network-protocols, python, sockets

Solution

You'll never be able to force the OS (with any sort of reasonable effort) to release a socket.

Instead you just want to say you don't care with `setsockopt`

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

This means that the option takes place at the Socket Object Level SOCKET (as opposed to the TCP or something else) and you're setting the Socket Option REUSEADDR (you're telling the OS that it's OK, you really do want to listen here). And finally, you're turning the option on with `1`, rather than off (with `0`).

Problem

I use a port in my python program and close it,now I want to use it again.Just that port not another port. Is there any way to force OS to free port with python? ``` #!/usr/bin/python # This is server.py file import socket # Import socket module s = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 12349 portt = 12341 # Reserve a port for your service. s.bind((host, portt)) # Bind to the port s.connect((host, port)) s.close ss = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name ss.bind((host, portt)) s.close ``` but the output is: ``` Traceback (most recent call last): File "client.py", line 17, in <module> ss.bind((host, portt)) File "/usr/lib/python2.7/socket.py", line 224, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 98] Address already in use ```

Original source