Skip to main content

How to Resolve Python Error "socket.gaierror: [Errno 11001] getaddrinfo failed" and "[Errno -2] Name or service not known"

When your Python application performs network operations (like making HTTP requests, connecting to databases, or sending emails), it often needs to resolve a hostname (like google.com) into an IP address. If this resolution process fails, you might encounter socket.gaierror exceptions, commonly [Errno 11001] getaddrinfo failed (often on Windows) or [Errno -2] Name or service not known (common on Linux/macOS).

This guide explains the primary causes for these DNS resolution errors – incorrect hostnames, proxy configuration issues, and network connectivity problems – and provides practical solutions.

Understanding the Error: Hostname Resolution (getaddrinfo)

At its core, networking often relies on the Domain Name System (DNS) to translate human-readable hostnames (e.g., www.example.com) into numerical IP addresses (e.g., 93.184.216.34) that computers use to locate each other.

In Python, the low-level socket.getaddrinfo(host, port, ...) function (and similar mechanisms used by higher-level libraries like requests, urllib, database drivers, etc.) performs this lookup.

  • socket.gaierror: [Errno 11001] getaddrinfo failed: Typically seen on Windows, indicating a general failure during the address lookup process. This could be due to various reasons, including the host not being found, network issues, or configuration problems.
  • socket.gaierror: [Errno -2] Name or service not known: More common on Linux/macOS, specifically indicating that the DNS lookup failed to resolve the provided hostname or service name.

Both errors mean the system couldn't determine the IP address associated with the name you provided.

Cause 1: Invalid Hostname or Service Name

The hostname or service (port) you are trying to connect to might be incorrect:

  • Typo: A simple misspelling in the hostname (googgle.com instead of google.com).
  • Non-Existent Domain: The domain name truly doesn't exist or isn't registered in DNS.
  • Including Protocol Scheme: Providing http:// or https:// as part of the hostname to functions expecting only the hostname (like socket.getaddrinfo). Higher-level libraries like requests handle full URLs, but lower-level functions often don't.
  • Incorrect Port/Service: Providing an invalid port number or service name.

Solution 1: Verify Hostname and Service Arguments

Double-check the hostname and port you are using. Ensure they are correct and formatted as expected by the function or library you are calling.

Using socket.getaddrinfo() Directly

When using the low-level socket.getaddrinfo, provide only the hostname (without http:// or https://) and a valid port number or service name.

import socket

host_ok = 'google.com'
host_bad = 'https://google.com' # Incorrect - includes scheme
port_ok = 443 # Standard HTTPS port
port_bad_str = 'invalid-port'

try:
# ✅ Correct usage
info_ok = socket.getaddrinfo(host_ok, port_ok)
print(f"Info for {host_ok}:{port_ok} (first result): {info_ok[0]}")
except socket.gaierror as e:
print(f"Error getting info for {host_ok}:{port_ok}: {e}")

try:
# ⛔️ Incorrect usage - includes scheme
info_bad = socket.getaddrinfo(host_bad, port_ok)
print(info_bad)
except socket.gaierror as e:
print(f"\nError getting info for {host_bad}:{port_ok}: {e}") # Likely [Errno -2] or similar

# ✅ Using localhost
try:
info_local = socket.getaddrinfo('localhost', 8000)
# Or use '127.0.0.1' which sometimes resolves more reliably than 'localhost'
# info_local = socket.getaddrinfo('127.0.0.1', 8000)
print(f"\nInfo for localhost:8000 (first result): {info_local[0]}")
except socket.gaierror as e:
print(f"\nError getting info for localhost:8000: {e}")

Handling Errors with try...except

Wrap network calls that might fail resolution in a try...except socket.gaierror block to handle the error gracefully.

import socket

host = "nonexistent-domain-blah.xyz"
port = 80

try:
addr_info = socket.getaddrinfo(host, port)
# ... proceed with connection using addr_info ...
print("Lookup successful (unexpected).")
except socket.gaierror as e:
# Handle the resolution failure
print(f"Failed to resolve hostname '{host}': {e}")
except Exception as e:
# Handle other potential socket errors
print(f"An unexpected socket error occurred: {e}")

Cause 2: Proxy Configuration Issues

If your computer is behind a corporate or network proxy, incorrect proxy settings can interfere with DNS resolution. Python libraries often check standard environment variables like HTTP_PROXY and HTTPS_PROXY. If these are set incorrectly (or set when they shouldn't be), they can prevent connections.

Solution 2: Check and Correct Proxy Environment Variables

Checking Proxy Variables

Check if these variables are set in your current shell environment:

  • Linux/macOS (Bash/Zsh):
    echo $http_proxy
    echo $https_proxy
    echo $HTTP_PROXY # Check uppercase too
    echo $HTTPS_PROXY
  • Windows (Command Prompt - CMD):
    echo %http_proxy%
    echo %https_proxy%
    echo %HTTP_PROXY%
    echo %HTTPS_PROXY%
  • Windows (PowerShell):
    echo $env:http_proxy
    echo $env:https_proxy
    echo $env:HTTP_PROXY
    echo $env:HTTPS_PROXY

If they output a value, a proxy is configured for that session/system.

Unsetting Proxy Variables

If you are not supposed to be using a proxy, or suspect the settings are wrong, try unsetting them for your current session:

  • Linux/macOS (Bash/Zsh):
    unset http_proxy
    unset https_proxy
    unset HTTP_PROXY
    unset HTTPS_PROXY
  • Windows (Command Prompt - CMD): (Sets to empty for the current session)
    set http_proxy=
    set https_proxy=
    set HTTP_PROXY=
    set HTTPS_PROXY=
  • Windows (PowerShell): (More persistent removal might need registry/system settings edits, but for session:)
    Remove-Item Env:\http_proxy -ErrorAction SilentlyContinue
    Remove-Item Env:\https_proxy -ErrorAction SilentlyContinue
    Remove-Item Env:\HTTP_PROXY -ErrorAction SilentlyContinue
    Remove-Item Env:\HTTPS_PROXY -ErrorAction SilentlyContinue
    # Or to try removing persistent ones (needs elevated privileges potentially):
    # [Environment]::SetEnvironmentVariable('http_proxy', $null, 'User')
    # [Environment]::SetEnvironmentVariable('https_proxy', $null, 'Machine') # Needs Admin

After unsetting, retry your Python script.

Setting Proxy Variables Correctly

If you do need to use a proxy, ensure the variables are set correctly. The format is typically http://[user:password@]proxy.server.com:port.

  • Linux/macOS (Bash/Zsh):
    # No authentication
    export http_proxy="http://proxy.example.com:8080"
    export https_proxy="http://proxy.example.com:8080"

    # With authentication
    # export http_proxy="http://user:[email protected]:8080"
    # export https_proxy="http://user:[email protected]:8080"

    # Set uppercase versions too for wider compatibility
    export HTTP_PROXY="$http_proxy"
    export HTTPS_PROXY="$https_proxy"
  • Windows (Command Prompt - CMD):
    set http_proxy=http://proxy.example.com:8080
    set https_proxy=http://user:[email protected]:8080
    set HTTP_PROXY=%http_proxy%
    set HTTPS_PROXY=%https_proxy%
  • Windows (PowerShell):
    $env:http_proxy="http://proxy.example.com:8080"
    $env:https_proxy="http://user:[email protected]:8080"
    $env:HTTP_PROXY=$env:http_proxy
    $env:HTTPS_PROXY=$env:https_proxy

Consult your network administrator for the correct proxy address, port, and authentication details.

Using pip install Behind a Proxy (--proxy)

If the error specifically occurs during pip install, you can provide the proxy directly to pip:

# With authentication
pip install --proxy http://user:[email protected]:port package_name

# Without authentication
pip install --proxy http://proxy.server:port package_name

Setting the environment variables (as above) usually makes the --proxy flag unnecessary for pip.

Cause 3: Network Connectivity Problems

Basic network issues can prevent DNS lookups:

  • No internet connection.
  • Flaky Wi-Fi or network cable.
  • DNS server configured on your machine is down or incorrect.
  • Firewall (local or network) blocking DNS requests (port 53) or connections to the target host.
  • VPN issues (either required but not connected, or connected but interfering with DNS).

Solution 3: Verify Network Connectivity and DNS

  • Basic Check: Can you access websites (like the target host or google.com) in your browser?
  • Ping (if allowed): ping google.com or ping your_target_host.com. Does it resolve the IP and get replies?
  • DNS Servers: Check your system's network settings. Are the DNS servers correct? Can you try public DNS servers like Google's (8.8.8.8, 8.8.4.4) or Cloudflare's (1.1.1.1) temporarily?
  • Firewall: Temporarily disable local firewall software to test if it's blocking the connection. Check network firewall rules if applicable.
  • VPN: If you use a VPN, try disconnecting it. If you need the VPN to reach the host, ensure it's connected properly. Sometimes restarting the VPN client helps.

Conclusion

The socket.gaierror: [Errno 11001] getaddrinfo failed or [Errno -2] Name or service not known indicates a failure in resolving a hostname to an IP address.

The primary steps to resolve this are:

  1. Verify the hostname/address: Ensure it's spelled correctly, exists, and doesn't include the protocol scheme (http://) when passed to low-level functions like socket.getaddrinfo.
  2. Check Proxy Settings: Verify, unset, or correctly set the http_proxy and https_proxy environment variables according to your network requirements. Use pip install --proxy if needed specifically for pip.
  3. Check Network Connectivity: Ensure basic internet access, functional DNS servers, and check for interference from firewalls or VPNs.

By systematically investigating these three areas, you can usually pinpoint and fix the cause of the getaddrinfo failure.