Search code examples
pythonsocketstcpipv6

HTTPServer: "Cannot assign requested address" on localhost vs 127.0.0.1


With the below Python 3 code:

from http.server import HTTPServer, SimpleHTTPRequestHandler
s = HTTPServer(('localhost', 0), SimpleHTTPRequestHandler)

I get the following error:

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

I've noticed that 3 things will prevent this from happening:

  1. Disabling WiFi.
  2. Switching to a different WiFi network (from my home router to tethering on my phone).
  3. Changing 'localhost' in the code to '127.0.0.1'.

So my question is, what's going wrong here? Why does this code fail when it does?

P.S. Here is ip a's output when connected to my home router, and here's its output when tethering.


Solution

  • I believe the issue was that the DNS service on my home WiFi network was not returning the correct information for localhost. I ended up working around this issue by hardcoding the address as 127.0.0.1.