I need to write a small bit of code that will print an error if I cannot resolve the name to IP.
I see that you can use the "socket.gethostbyaddr" methods but I cant seem to find a simple method/exception for when it does not find an IP address.

Also if I change the timeout on this would it affect the dns timeout`s for the whole machine ?

Or is there a simpler method ?

Thanks,

Dani AI

Generated

Short answer: let the socket resolver raise its error and catch only the resolution-related exceptions, and use a wrapper (thread/process or a DNS library) if you need a lookup timeout.

As showed, Python's socket functions will raise when a name or IP can't be resolved; that behavior is what you should rely on. Prefer socket.getaddrinfo for forward lookups (it handles both IPv4 and IPv6) and socket.gethostbyaddr for reverse lookups. Don't use a blanket except socket.error as suggested unless you really want to swallow unrelated OS/socket problems.

To enforce a timeout for a blocking platform resolver, run the lookup in a short-lived thread and apply a Python-level timeout. Example pattern:

import socket
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout

def lookup_with_timeout(host, timeout=2):
    def _resolve():
        infos = socket.getaddrinfo(host, None, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM)
        return {ai[4][0] for ai in infos}
    with ThreadPoolExecutor(max_workers=1) as ex:
        future = ex.submit(_resolve)
        try:
            return list(future.result(timeout=timeout))
        except FutureTimeout:
            raise TimeoutError("DNS lookup timed out")
        except socket.gaierror as e:
            raise RuntimeError("Name resolution failed: {}".format(e))

Note on timeouts: socket.setdefaulttimeout (or socket.socket.settimeout) controls socket I/O timeouts, not how long the system DNS resolver (getaddrinfo) may block. If you need fine-grained DNS control (timeouts, retries, specifying servers), use a DNS library such as dnspython or perform resolver calls in a separate process you can kill.

Troubleshooting tips: log the exact exception and errno, check your OS resolver config (resolv.conf / nsswitch), test with dig/nslookup, and cache results (lru_cache) if you do many repeated lookups. The ThreadPool approach complements 's try/except by giving you deterministic timeout behavior while keeping error handling explicit.

Recommended Answers

All 2 Replies

You can look at this and see if it helps.

>>> import socket 
>>> socket.gethostbyname_ex('python.org')
('python.org', [], ['82.94.164.162'])
>>> socket.gethostbyaddr('82.94.164.162')
('dinsdale.python.org', [], ['82.94.164.162'])
>>> socket.gethostbyaddr('111.111')
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
gaierror: [Errno 11004] getaddrinfo failed
>>> socket.gethostbyaddr('11.111.111.111')
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
herror: [Errno 11004] host not found
import socket

def foo(ip):
    try:
        name = socket.gethostbyaddr(ip)
        return name[0]
    except (socket.gaierror,socket.herror):
        return 'No DNS name found for this ip'

#ip = '82.94.164.162'
#dinsdale.python.org

ip = '11.111.111.111'
#No DNS name found for this ip

print foo(ip)

I think except socket.error will catch all errors from module socket.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.