Python Forum

Full Version: BaseHTTPServer.HTTPServer pick-a-port?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
My code works beautifully and looks like this:
server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT), WebRequestHandler)
What's wanted is for PORT to be a range, for example (25500-25510), and for the web server to pick one that is free. Possible?

Thanks.

Lou.
from http.server import BaseHTTPRequestHandler, HTTPServer


HOST_NAME = 'localhost'
server_ok = False

for port in range(25500, 25511):
    try:
        server_class = HTTPServer
        httpd = server_class((HOST_NAME, port), BaseHTTPRequestHandler)
        server_ok = True
        break
    except Exception as e:
        print(f'{port} - {e}')
        continue

if server_ok:
    httpd.serve_forever()
else:
    print('All ports are busy!')