Abdullah Jibaly
Abdullah Jibaly

Reputation: 54790

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.

Upvotes: 4

Views: 3558

Answers (4)

Jorenko
Jorenko

Reputation: 2664

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.

Upvotes: 7

Kenan Banks
Kenan Banks

Reputation: 211980

Firewalls allow you to permit or deny traffic on a port-by-port basis. For this reason alone, an application without a well-defined port should expect to run into all kinds of problems in a client installation.

I say pick a random port, and make it very easy for the user to change the port if need be.

Here's a good starting place for well-known ports.

Upvotes: -2

Charlie Martin
Charlie Martin

Reputation: 112366

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.

Upvotes: 7

Claudiu
Claudiu

Reputation: 229361

Is make_server a function that you've written? More specifically, do you handle the code that creates the sockets? If you do, there should be a way where you don't specify a port number (or you specify 0 as a port number) and the OS will pick an available one for you.

Besides that, you could just pick a random port number, like 54315... it's unlikely someone will be using that one.

Upvotes: 2

Related Questions