Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pick a free port number in python? [duplicate]

Tags:

python

Possible Duplicate:
On localhost, how to pick a free port number?

My requirement is different from this question.

On localhost, how to pick a free port number?

I am writing a test setup of another process using python. The other process needs a port number to be passed (say as a command line parameter). I cannot hard-code some random port number because many users usually would run same test in the same box. Now, how do I select a free port in python?

Edit:

I am not creating a socket in python. I just need to pass a number to some other process as a command line argument.

From DRH's answer, I could create a dummy socket, get its port number, close it and pass to the actual process. Is there any better way to do this?

like image 700
balki Avatar asked Dec 22 '11 06:12

balki


People also ask

How do I find my free port number?

You can use "netstat" to check whether a port is available or not. Use the netstat -anp | find "port number" command to find whether a port is occupied by an another process or not. If it is occupied by an another process, it will show the process id of that process.

How do you get a port available in Python?

Bind the socket to port 0. A random free port from 1024 to 65535 will be selected. You may retrieve the selected port with getsockname() right after bind() .

What are free port numbers?

Well-Known Ports. Port numbers can run from 0 to 65353. Port numbers from 0 to 1023 are reserved for common TCP/IP applications and are called well-known ports.


1 Answers

There likely is not a safe way to do what you're asking. Even if the OS could return a port to you that is currently free, there's no guarantee that another process wouldn't bind a socket to that port between the time where you request the port and when the application you invoke attempts to bind to it.

Given that, if you're just looking for a port that is likely free, you could bind to port 0 as described here On localhost, how to pick a free port number?, close the resulting socket (freeing the port), and then pass that value to your application.

like image 173
DRH Avatar answered Sep 27 '22 00:09

DRH