Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current port number in Flask?

Tags:

Using Flask, how can I get the current port number that flask is connected to? I want to start a server on a random port using port 0 but I also need to know which port I am on.

Edit

I think I've found a work around for my issue, although it isn't an answer to the question. I can iterate through ports starting with 49152 and attempt to use that port through app.run(port=PORT). I can do this in a try catch block so that if I get an Address already in use error, I can try the next port.

like image 232
david4dev Avatar asked Feb 23 '11 00:02

david4dev


People also ask

How do I find my Flask port number?

Binding to port 0 is correct. That will make the operating system choose an available port between 1024 and 65535 for you. To retrieve the chosen port after binding, use your_socket. getsockname()[1] .

What port is Flask running on?

By default, Flask runs on port 5000 in development mode. That works fine if you're running on your own laptop.

How do I get my Flask to run on port 80?

To get Python Flask to run on port 80, we can call app. run with the port argument. to call app. run with the port argument set to 80 to run our Flask app on port 80.


1 Answers

You can't easily get at the server socket used by Flask, as it's hidden in the internals of the standard library (Flask uses Werkzeug, whose development server is based on the stdlib's BaseHTTPServer).

However, you can create an ephemeral port yourself and then close the socket that creates it, then use that port yourself. For example:

# hello.py from flask import Flask, request import socket  app = Flask(__name__)  @app.route('/') def hello():     return 'Hello, world! running on %s' % request.host  if __name__ == '__main__':     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)     sock.bind(('localhost', 0))     port = sock.getsockname()[1]     sock.close()     app.run(port=port) 

will give you the port number to use. An example run:

$ python hello.py  * Running on http://127.0.0.1:34447/ 

and, on browsing to http://localhost:34447/, I see

Hello, world! running on localhost:34447

in my browser.

Of course, if something else uses that port between you closing the socket and then Flask opening the socket with that port, you'd get an "Address in use" error, but you may be able to use this technique in your environment.

like image 70
Vinay Sajip Avatar answered Oct 21 '22 00:10

Vinay Sajip