Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python port binding

Tags:

python

I've recently been learning python and I just started playing with networking using python's socket library. Everything has been going well until recently when my script terminated 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 binded to the port, even though the python script isn't running (and I've verified this using $px aux. What's weird is that after a minute or so, I can run the script again on the same port and it will be fine. Is there any way to prevent/unbind a port for when this happens in the future?

like image 461
Steve Gattuso Avatar asked Mar 03 '09 22:03

Steve Gattuso


People also ask

What is socket () bind () listen () accept () and connect ()?

Bind the socket to an address using the bind() function; Listen for connections with the listen() function; Accept a connection with the accept() function system call. This call typically blocks until a client connects with the server. Send and receive data by means of send() and receive().

What does listen () do in Python?

The .listen() method has a backlog parameter. It specifies the number of unaccepted connections that the system will allow before refusing new connections. Starting in Python 3.5, it's optional. If not specified, a default backlog value is chosen.

What is the difference between bind () and listen ()?

A server has a bind() method which binds it to a specific IP and port so that it can listen to incoming requests on that IP and port. A server has a listen() method which puts the server into listen mode. This allows the server to listen to incoming connections.


1 Answers

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

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

The reason you are seeing the behaviour you are is that the OS is reserving that particular port for some time after the last connection terminated. This is so that it can properly discard any stray further packets that might come in after the application has terminated.

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

like image 91
Greg Hewgill Avatar answered Sep 22 '22 09:09

Greg Hewgill