Python http服务器在本地工作,但拒绝从其他机器连接



我正在树莓派上运行这个简单的Python http服务器演示

#/usr/bin/env python3
from http.server import BaseHTTPRequestHandler, HTTPServer
import sys
import time
hostName = "localhost"
serverPort = 80
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>https://pythonbasics.org</title></head>", "utf-8"))
self.wfile.write(bytes("<p>Request: %s</p>" % self.path, "utf-8"))
self.wfile.write(bytes("<body>", "utf-8"))
self.wfile.write(bytes("<p>This is an example web server.</p>", "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
if __name__ == "__main__":
sys.argv.pop(0)
if len (sys.argv):
serverPort=int(sys.argv.pop(0))
webServer = HTTPServer((hostName, serverPort), MyServer)
print("Server started http://%s:%s" % (hostName, serverPort))
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
print("Server stopped.")

我可以通过ssh pi@raspberrypi.localcurl localhost得到期望的输出

但是,如果我使用curl raspberrypi.local(在可以ssh的机器上),那么连接将被拒绝。

为什么curl工作在本地而不是远程?

正如@RonMaupin指出的那样,您正在使用本地主机地址,该地址在本地机器之外不可用。

试着改变这一行

hostName = "localhost"

hostName = "your Pi's IP address"

您可以使用以下命令查找IP地址:

ifconfig——

例如,在我的例子中,上面的命令显示Ipv4eth0的地址10.0.0.162.

所以我将代码改为:
hostName = "10.0.0.162"

如果你的Pi有多个网络接口(即WiFi和以太网),你也可以使用这个:

hostName = "0.0.0.0"

这将配置服务器监听所有网络接口。虽然这又快又简单,但确实有一些安全隐患,可能不应该在面向互联网的系统上进行。

最新更新