DEV Community

DAPA Checker
DAPA Checker

Posted on

Resolving a Domain to Its IP Address in Python and Node.js (and Why Results Differ)

Looking up the IP behind a domain sounds like a one-liner, and it mostly is. But if you have ever compared results between your laptop, a server and an online tool and got three different answers, it helps to know what is going on. Here is a short tour.

Python

The quickest option uses the standard library:

import socket

print(socket.gethostbyname("example.com"))  # first IPv4 address only
Enter fullscreen mode Exit fullscreen mode

gethostbyname returns a single IPv4 address. To see everything the resolver returns, including IPv6:

import socket

infos = socket.getaddrinfo("example.com", 443, proto=socket.IPPROTO_TCP)
for family, _, _, _, sockaddr in infos:
    print(family.name, sockaddr[0])
Enter fullscreen mode Exit fullscreen mode

Node.js

Node has two different APIs, and the difference matters:

const dns = require('node:dns').promises;

// Uses the OS resolver (same as most apps, respects /etc/hosts)
const { address } = await dns.lookup('example.com');

// Queries DNS servers directly, returns all A records
const ips = await dns.resolve4('example.com');
console.log(address, ips);
Enter fullscreen mode Exit fullscreen mode

lookup goes through the operating system, so a hosts-file entry or a local DNS override changes the result. resolve4 asks DNS servers directly and ignores the hosts file.

Why different tools show different IPs

  1. CDNs and load balancers. Many sites return different IPs depending on where you ask from. A request from Pakistan and one from Germany can legitimately get different answers.
  2. Multiple A records. Round-robin DNS returns several addresses; tools that show only the first one will disagree with each other.
  3. Caching and TTLs. Your OS, router and ISP may cache an old answer until its TTL expires, especially right after a DNS change.
  4. IPv4 vs IPv6. Some tools only show A records, others include AAAA.
  5. Hosts file overrides. Anything using the OS resolver respects local overrides.

Quick sanity check from outside your network

When I need to confirm what the rest of the world sees, rather than my local resolver, I use a domain IP lookup tool that runs the query from a server. If its answer differs from dns.lookup() on my machine, the usual suspects are a stale cache or a hosts-file entry.

Takeaways

  • Use getaddrinfo / dns.resolve4 when you want all records.
  • Use dns.lookup when you want to match what other apps on the machine will connect to.
  • Expect different answers across locations for any site behind a CDN; that is normal, not a bug.

Top comments (0)