Making Reverse DNS Lookups in Python with aiohttp

Mar 3, 2024 ยท 2 min read

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 8.8.8.8 and returns the hostname associated with it, in this case google-public-dns-a.google.com.

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:

  • We use an aiohttp client session for asynchronous HTTP requests
  • The Google DNS API endpoint can return PTR records for reverse DNS lookups
  • We await the JSON response and extract the hostname from the Answer data
  • Some tips when doing reverse DNS with aiohttp:

  • Handle errors - the hostname lookup could fail or return multiple names
  • Cache results - reverse DNS usually doesn't change often for an IP
  • Rate limit requests - don't overload DNS servers with too many queries
  • 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.

    Browse by tags:

    Browse by language:

    The easiest way to do Web Scraping

    Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


    Try ProxiesAPI for free

    curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

    <!doctype html>
    <html>
    <head>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    ...

    X

    Don't leave just yet!

    Enter your email below to claim your free API key: