How do I make a Python server public?

1.5k Views Asked by At

Using this code:

from http import server
class Serv(server.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
server.HTTPServer(('host', 80), Serv).serve_forever()

I have tried using my public IP, which didn't work, my private IP, which only worked from the same network, and localhost, which is my PC only. How can I change the host so when someone connects to my IP, it connects to my website (from my code)? Do I need my router to redirect to my PC? I know host can be my private IP or localhost, are there any other hosts I can use? Edit: I saw an answer in another question that used Flask, I'd like to not use any dependencies as of now.

1

There are 1 best solutions below

3
Etienne Dijon On BEST ANSWER

If you want to make it work from anywhere,

your application should listen on IP address 0.0.0.0

which means (in short) any IPv4 address at all :

from http import server

class Serv(server.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'Hello, world!')
server.HTTPServer(('', 80), Serv).serve_forever()

If you are in a recent linux/GNU based OS, you may check listening ports with :

ss -ltpn

Note that after that modification, you will depend of any proxy/firewall between you and your server to get your application response.