All Courses

Can Python's http.server be used with a different IP address?

By, a month ago
  • Bookmark

Can I use the Python http.server on a different IP?  

Ip address
1 Answer

Yes, you can use Python's http.server module to run a web server with a different IP address. By default, the http.server module binds to the loopback address (localhost), which means that it can only be accessed from the same machine.

To bind to a different IP address, you can specify the IP address and port number when you create the server instance. For example, to bind to the IP address and port 8000, you can run the following command in your terminal:

python -m http.server --bind 8000

This will start a web server that listens for incoming requests on the IP address and port 8000.

Alternatively, you can create a custom server class that inherits from http.server.HTTPServer and overrides the server_bind method to specify the IP address and port number. Here's an example:

import http.server
import socketserver

class CustomHTTPServer(http.server.HTTPServer):
    def server_bind(self):
        self.socket.bind(('', 8000))
handler = http.server.SimpleHTTPRequestHandler
httpd = CustomHTTPServer(('', 8000), handler)

This will create a custom HTTPServer class that binds to the IP address and port 8000, and then creates an instance of the SimpleHTTPRequestHandler class to handle incoming requests. Finally, the server is started and set to run indefinitely using the serve_forever method.

Your Answer


Live Masterclass on : "How Machine Get Trained in Machine Learning?"

Mar 30th (7:00 PM) 516 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More