Sobes.tech
Middle

How to get the IP address knowing the hostname?

sobes.tech AI

Answer from AI

To obtain an IP address by hostname, DNS queries are usually used. In different environments, this is done differently:

  • In Linux/macOS command line, you can use the command nslookup <hostname> or dig +short <hostname>.
  • In Windows — the command nslookup <hostname>.
  • In Python code, you can use the socket module:
import socket
ip = socket.gethostbyname('example.com')
print(ip)
  • In Node.js — the dns module:
const dns = require('dns');
dns.lookup('example.com', (err, address) => {
  if (err) throw err;
  console.log(address);
});

Thus, obtaining an IP address boils down to performing a DNS query by hostname.