How to find the domain name given an IP address
Overview
Domain names and IP addresses are relayed through the Domain Name System (DNS). The domain name connected to an IP address is given via a DNS pointer record, or PTR.
Reverse DNS lookups make use of DNS PTR records. A DNS lookup happens when a user types in a domain name to access it in their browser, comparing the domain name to the IP address. In contrast, a reverse DNS lookup is a request that starts with an IP address and gets a domain name.
The domain name for the given IP address can be fetched using the gethostbyaddr() function of the socket module in python.
The gethostbyaddr() function
The gethostbyaddr() function is used to retrieve the domain name for the given IP address.
Note: Refer to Socket programming in Python to learn more about socket module in python.
Syntax
socket.gethostbyaddr(ip_address)
Parameter
ip_address: This is the IP address for which the domain name has to be retrieved.
Return value
The method returns a tuple, (hostname, aliaslist and ipaddrlist).
hostname: This is the domain name.aliaslist: This is a list of alternative host names for the same address.ipaddrlist: This is a list of IPv4/v6 addresses for the same interface on the same host.
Example
import socketdef domain_name(ip_addr):dom_name = socket.gethostbyaddr(ip_addr)print("The domain name for " + ip_addr + " is", dom_name)ip_addr = "8.8.8.8"domain_name(ip_addr)
Explanation
- Line 1: We import the
socketmodule. - Lines 3–5: We define a function called
domain_namethat takes in an IP address and uses thegethostbyaddr()function to find the domain name function. - Line 7: We define an IP address, such as
ip_addr. - Line 8: We invoke the
domain_namefunction is withip_addras an argument.