Saturday, November 16, 2024

macos – Python on Terminal cannot resolve DNS queries

I have a weird issue with Python on macOS Sequoia for the last couple of days. It did not happen right after the upgrade, it worked initially. Python in Terminal.app cannot resolve any DNS queries. However, the Python console and the builtin Terminal in PyCharm works just fine.

Here’s a sample; the http command is HTTPie, a Python based utility:

% http google.com

http: error: gaierror: [Errno 8] nodename nor servname provided, or not known
Couldn’t resolve the given hostname. Please check the URL and try again.

% python3
Python 3.12.6 (main, Sep  6 2024, 19:03:47) [Clang 16.0.0 (clang-1600.0.26.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> socket.getaddrinfo('google.com', 80)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/homebrew/Cellar/[email protected]/3.12.6/Frameworks/Python.framework/Versions/3.12/lib/python3.12/socket.py", line 976, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
>>> ^D

% curl google.com
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
...

% dig google.com
...
;; ANSWER SECTION:
google.com.     41  IN  A   142.250.184.206

;; Query time: 14 msec
;; SERVER: 192.168.178.1#53(192.168.178.1)
;; WHEN: Fri Oct 04 10:13:02 CEST 2024
;; MSG SIZE  rcvd: 55

% http -v 142.250.184.206
GET / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: 142.250.184.206
User-Agent: HTTPie/3.2.3



HTTP/1.1 301 Moved Permanently
...

As you can see, network connections in general are fine, only DNS queries can’t be resolved. They time out after about 30 seconds. However, the same within PyCharm works fine.

I’ve read about HTTP_PROXY environment variables maybe being a problem, but I don’t have those set.

I don’t know enough about DNS resolution and how Python uses it to even know where to look. Any ideas?

Related Articles

Latest Articles