When building network applications in Python, you may need to perform reverse DNS lookups to convert an IP address to a hostname. The aiohttp library provides an easy way to make asynchronous reverse DNS lookups.
A reverse DNS lookup takes an IP address like
Here is how to make a reverse DNS lookup with aiohttp:
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get(f'https://dns.google.com/resolve?name={ip}&type=PTR') as resp:
data = await resp.json()
hostname = data['Answer'][0]['data']
The key things to note:
Some tips when doing reverse DNS with aiohttp:
You may also want to validate hostnames after the reverse lookup to check if they resolve back to the original IP.
Here is an example wrapper function that does a reverse lookup along with forward validation:
async def reverse_dns(ip):
async with aiohttp.ClientSession() as session:
try:
resp = await session.get(f'https://dns.google.com/resolve?name={ip}&type=PTR')
data = await resp.json()
hostname = data['Answer'][0]['data']
except:
return None
forward_resp = await session.get(f'https://dns.google.com/resolve?name={hostname}&type=A')
forward_data = await forward_resp.json()
if ip not in [answer['data'] for answer in forward_data['Answer']]:
return None
return hostname
This provides robust reverse DNS lookups from Python with aiohttp and handles some of the potential pitfalls like invalid responses.