Search code examples
pythondns

How can I do DNS lookups in Python, including referring to /etc/hosts?


dnspython will do my DNS lookups very nicely, but it entirely ignores the contents of /etc/hosts.

Is there a python library call which will do the right thing? ie check first in etc/hosts, and only fall back to DNS lookups otherwise?


Solution

  • I'm not really sure if you want to do DNS lookups yourself or if you just want a host's ip. In case you want the latter,

    /!\ socket.gethostbyname is deprecated, prefer socket.getaddrinfo

    from man gethostbyname:

    The gethostbyname*(), gethostbyaddr*(), [...] functions are obsolete. Applications should use getaddrinfo(3), getnameinfo(3),

    import socket
    print(socket.gethostbyname('localhost')) # result from hosts file
    print(socket.gethostbyname('google.com')) # your os sends out a dns query