Python Forum
BaseHTTPServer.HTTPServer pick-a-port? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: BaseHTTPServer.HTTPServer pick-a-port? (/thread-11375.html)



BaseHTTPServer.HTTPServer pick-a-port? - degenaro - Jul-05-2018

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.


RE: BaseHTTPServer.HTTPServer pick-a-port? - gontajones - Jul-05-2018

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!')