Reputation: 413
I am using Python for a basic socket program.
On the server side:
port = 3135
c.bind('0.0.0.0',port)
On the client side:
port = 3135
s.connect(('127.0.0.1', port))
However, I need to manually change the port
variable every time the program throws an OSError
(when the port is not free)
How can I automatically select a port that is free?
Upvotes: 2
Views: 982
Reputation: 59204
The python docs don't seem to mention it explicitly, but the normal procedure to do this with sockets is:
Before listening, the server binds its socket to port 0, which causes the system to choose a free port.
The server calls getsockname
to get the address the socket is bound to, including the actual port number
The server somehow publishes the port number where clients can see it
Clients then connect to that specific port.
Upvotes: 4