Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Binding Socket: "Address already in use"

I have a question regarding client socket on TCP/IP network. Let's say I use

try:      comSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)     comSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  except socket.error, msg:      sys.stderr.write("[ERROR] %s\n" % msg[1])     sys.exit(1)  try:     comSocket.bind(('', 5555))      comSocket.connect()  except socket.error, msg:      sys.stderr.write("[ERROR] %s\n" % msg[1])      sys.exit(2) 

The socket created will be bound to port 5555. The problem is that after ending the connection

comSocket.shutdown(1) comSocket.close() 

Using wireshark, I see the socket closed with FIN,ACK and ACK from both sides, I can't use the port again. I get the following error:

[ERROR] Address already in use 

I wonder how can I clear the port right away so that next time I still can use that same port.

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

setsockopt doesn't seem to be able to resolve the problem Thank you!

like image 905
Tu Hoang Avatar asked Jun 17 '11 00:06

Tu Hoang


People also ask

How do I fix bind address already in use?

The Error “address already in use” occurred because some process was already running on the same port. So we can resolve the issue just by killing the process. To stop the process, we need the process ID (PID), which we can fetch using the lsof command.

Could not bind socket address and port are already in use?

To do so, open the program options by going to Edit -> Options -> Browsers and change the value of the WebSockets port. The same value must then also be set in the browser add-on (within the browser itself).

Which function binds the socket to an address in Python?

Bind() Function Of Socket Module In Python The bind() method of Python's socket class assigns an IP address and a port number to a socket instance. The bind() method is used when a socket needs to be made a server socket.


1 Answers

Try using the SO_REUSEADDR socket option before binding the socket.

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

Edit: I see you're still having trouble with this. There is a case where SO_REUSEADDR won't work. If you try to bind a socket and reconnect to the same destination (with SO_REUSEADDR enabled), then TIME_WAIT will still be in effect. It will however allow you to connect to a different host:port.

A couple of solutions come to mind. You can either continue retrying until you can gain a connection again. Or if the client initiates the closing of the socket (not the server), then it should magically work.

like image 167
Bryan Avatar answered Sep 23 '22 14:09

Bryan