views:

328

answers:

4

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.

+2  A: 

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.

Claudiu
Yes, 0 for port works. socket.socket(socket.AF_INET).bind(('127.0.0.1', 0))
bobince
+4  A: 

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.

Charlie Martin
A: 

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.

Triptych
We are talking here about using TCP to communicate locally on the client. Firewalls have nothing to do with that.
Guillaume
+1  A: 

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.

Jorenko
"You are correct, sir." Love it when that happens.
Charlie Martin