To make DNS lookups for a domain or IP using Python3, you can use the socket
module, which provides functions for working with network sockets. Specifically, you can use the gethostbyname()
and gethostbyaddr()
functions to perform DNS lookups for domain names and IP addresses, respectively.
Here is an example of how you might use the gethostbyname()
function to look up the IP address associated with a domain name:
import socket
# Look up the IP address for a domain name
ip_address = socket.gethostbyname("www.google.com")
print(ip_address) # Prints "172.217.17.110"
In this example, we import the socket
module and use the gethostbyname()
function to look up the IP address for the domain name “www.google.com“. The function returns the IP address as a string, which we print to the console.
To use the gethostbyaddr()
function to look up the domain name associated with an IP address, you can use the following code:
import socket
# Look up the domain name for an IP address
domain_name = socket.gethostbyaddr("172.217.17.110")
print(domain_name) # Prints "google.com"
In this example, we use the gethostbyaddr()
function to look up the domain name associated with the IP address “172.217.17.110”. The function returns the domain name as a string, which we print to the console.
Note that these functions can only perform lookups for domain names and IP addresses that are registered with the DNS system. If you try to look up an unregistered domain name or IP address, these functions will return an error.