HTTPServer:“无法在localhost与127.0.0.1上分配请求的地址”

时间:2017-12-25 07:06:50

标签: python sockets tcp ipv6

使用以下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件事情会阻止这种情况发生:

  1. 禁用WiFi。
  2. 切换到其他WiFi网络(从我的家用路由器到我手机上的网络共享)。
  3. 将代码中的'localhost'更改为'127.0.0.1'
  4. 所以我的问题是,这里出了什么问题?为什么这段代码会失败呢?

    P.S。 Here is ip a's output when connected to my home routerhere's its output when tethering

3 个答案:

答案 0 :(得分:0)

我想,你不能在0端口听。 我试过节点js和SocketTest。他们2可以(并且不能)听,但是/并且不能连接到端口。它的意思是它可以并且都不能这样做。
这个链接可以帮助你 https://unix.stackexchange.com/questions/180492/is-it-possible-to-connect-to-tcp-port-0
https://docs.python.org/2/library/simplehttpserver.html

答案 1 :(得分:0)

我认为问题是家庭WiFi网络上的DNS服务没有返回localhost的正确信息。我最终通过将地址硬编码为var dtos = (new Fixture()).CreateMany<YourObjectType>(numberRecords); 来解决此问题。

答案 2 :(得分:0)

在更改 vps 的 ip 后,我遇到了同样的错误,因此 ifconfig 将输出如下内容:

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo 接口没有 IP 地址。如果一切正常,这个ip地址应该是127.0.0.1,正常输出是这样的:

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

我不确定是什么导致了这个错误,但是这个错误与端口无关,而是与 IP 地址有关,您可以查看 ifconfig 的输出。< /p>

相关问题