Anubhav Dinkar
Anubhav Dinkar

Reputation: 413

How can I automatically assign a free port for socket connection?

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

Answers (1)

Matt Timmermans
Matt Timmermans

Reputation: 59204

The python docs don't seem to mention it explicitly, but the normal procedure to do this with sockets is:

  1. Before listening, the server binds its socket to port 0, which causes the system to choose a free port.

  2. The server calls getsockname to get the address the socket is bound to, including the actual port number

  3. The server somehow publishes the port number where clients can see it

  4. Clients then connect to that specific port.

Upvotes: 4

Related Questions