All Courses

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

By Manerushi149@gmail.com, a month ago
  • Bookmark
0

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

Python
Http.server
Ip address
1 Answer
0
Goutamp777

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 127.0.0.1 (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 192.168.1.100 and port 8000, you can run the following command in your terminal:


python -m http.server --bind 192.168.1.100 8000

This will start a web server that listens for incoming requests on the IP address 192.168.1.100 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(('192.168.1.100', 8000))
        
handler = http.server.SimpleHTTPRequestHandler
httpd = CustomHTTPServer(('192.168.1.100', 8000), handler)
httpd.serve_forever()

This will create a custom HTTPServer class that binds to the IP address 192.168.1.100 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

Webinars

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