harryzcy
harryzcy

Reputation: 27

Opening the localhost web from another device using Python

I'm working on a python file that sends the response to the localhost website opened by the browser. This web can successfully open by the same device which hosts it, but when failed to be opened by the other device under the same LAN. Why does that happen?

I use http.server in Python3 to host the local server. I'm using these codes:

from http.server import BaseHTTPRequestHandler, HTTPServer

hostName = "localhost"
hostPort = 9000

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        path = self.path
        print(path)
        referer = self.headers.get('Referer')
        print("The referer is", referer)
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        # str is the html code I used
        self.wfile.write(bytes(str, "utf-8"))

myServer = HTTPServer((hostName, hostPort), MyServer)
print("Server Starts - %s:%s" % (hostName, hostPort))

try:
    myServer.serve_forever()
except KeyboardInterrupt:
    pass

myServer.server_close()
print("Server Stops - %s:%s" % (hostName, hostPort))

I am able to open the web by using localhost and 127.0.0.1, but just not the ip address.

Can anyone help me, please? Thank you

Upvotes: 0

Views: 656

Answers (1)

salmanwahed
salmanwahed

Reputation: 9647

Use your machine's IP address instead of localhost(Loopback) as the host. If your machine's IP is 192.168.x.x then the server will run at: 192.168.x.x:9000.

Upvotes: 1

Related Questions