Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an HTTP server in Python using the first available port?

I want to avoid hardcoding the port number as in the following:

httpd = make_server('', 8000, simple_app)

The reason I'm creating the server this way is that I want to use it as a 'kernel' for an Adobe AIR app so it will communicate using PyAMF. Since I'm running this on the client side it is very possible that any port I define is already in use. If there is a better way to do this and I am asking the wrong question please let me know.

like image 945
Abdullah Jibaly Avatar asked Oct 20 '25 10:10

Abdullah Jibaly


2 Answers

The problem is that you need a known port for the application to use. But if you give a port number of 0, I believe the OS will provide you with the first available unused port.

like image 179
Charlie Martin Avatar answered Oct 21 '25 22:10

Charlie Martin


The problem is that you need a known port for the application to use. But if you give a port number of 0, I believe the OS will provide you with the first available unused port.

You are correct, sir. Here's how that works:

>>> import socket
>>> s = socket.socket()
>>> s.bind(("", 0))
>>> s.getsockname()
('0.0.0.0', 54485)

I now have a socket bound to port 54485.

like image 28
Jorenko Avatar answered Oct 21 '25 23:10

Jorenko