[英]How do I make a Python server public?
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.我试过使用我的公共 IP,它没有用,我的私人 IP,它只能在 same.network 和 localhost 上工作,这只是我的 PC。 How can I change the host so when someone connects to my IP, it connects to my website (from my code)?如何更改主机,以便当有人连接到我的 IP 时,它会连接到我的网站(通过我的代码)? 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?我知道主机可以是我的私人 IP 或本地主机,还有其他主机可以使用吗? Edit: I saw an answer in another question that used Flask, I'd like to not use any dependencies as of now.编辑:我在另一个使用 Flask 的问题中看到了一个答案,我现在不想使用任何依赖项。
If you want to make it work from anywhere,如果你想让它在任何地方工作,
your application should listen on IP address 0.0.0.0
你的应用程序应该监听 IP 地址0.0.0.0
which means (in short) any IPv4 address at all
:这意味着(简而言之) 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:如果您使用的是最近的基于 linux/GNU 的操作系统,您可以使用以下命令检查监听端口:
ss -ltpn
Note that after that modification, you will depend of any proxy/firewall between you and your server to get your application response.请注意,在该修改之后,您将依赖于您和服务器之间的任何代理/防火墙来获取您的应用程序响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.