Python Forum
BaseHTTPServer.HTTPServer pick-a-port?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
BaseHTTPServer.HTTPServer pick-a-port?
#1
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.
Reply
#2
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!')
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  is there a way to mention port range or search for port dynamically with qConnection Creepy 0 1,477 Sep-09-2021, 03:15 PM
Last Post: Creepy
  asyncio: executing tasks + httpserver freebsdd 2 2,626 Aug-29-2020, 09:50 PM
Last Post: freebsdd
  How do I pick the right python in Linux env? MDRI 9 3,664 Jun-27-2020, 05:40 PM
Last Post: snippsat
  Python MySQL - How to pick column row data as variable? bharaths 1 4,250 Nov-02-2018, 12:08 PM
Last Post: bharaths
  Pick Value from Json dataonmyview 3 3,018 Sep-24-2018, 04:11 PM
Last Post: nilamo
  Pick 3 Lotto Code? Python3 4 4,538 Sep-10-2017, 05:09 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020