【发布时间】:2017-12-25 07:06:50
【问题描述】:
使用以下 Python 3 代码:
from http.server import HTTPServer, SimpleHTTPRequestHandler
s = HTTPServer(('localhost', 0), SimpleHTTPRequestHandler)
我收到以下错误:
Traceback (most recent call last):
File "repro.py", line 2, in <module>
s = HTTPServer(('localhost', 0), SimpleHTTPRequestHandler)
File "/usr/lib/python3.6/socketserver.py", line 453, in __init__
self.server_bind()
File "/usr/lib/python3.6/http/server.py", line 136, in server_bind
socketserver.TCPServer.server_bind(self)
File "/usr/lib/python3.6/socketserver.py", line 467, in server_bind
self.socket.bind(self.server_address)
OSError: [Errno 99] Cannot assign requested address
我注意到有 3 件事可以防止这种情况发生:
- 禁用 WiFi。
- 切换到不同的 WiFi 网络(从我的家用路由器到我的手机上的网络共享)。
- 将代码中的
'localhost'更改为'127.0.0.1'。
所以我的问题是,这里出了什么问题?为什么这段代码会失败?
附: Here is ip a's output when connected to my home router 和 here's its output when tethering。
【问题讨论】:
-
你试过其他可用的端口吗?端口 0 是系统或众所周知的端口,如 here 所述。
-
如果从
localhost更改为127.0.0.1可以修复它,这听起来像是DNS 问题。dig localhost显示什么? -
您的
ip a输出缺少重要的位,即接口lo。请添加此信息。