nadzoring.dns_lookup.reverse module

Reverse DNS lookup functionality for IP address to hostname resolution.

nadzoring.dns_lookup.reverse.reverse_dns(ip_address: str, nameserver: str | None = None) dict[str, str | float | None][source]

Perform a reverse DNS lookup to resolve an IP address to a hostname.

Queries the PTR (Pointer) record for a given IP address to find the associated domain name. This is the reverse of a forward DNS lookup.

Parameters:
  • ip_address – IPv4 or IPv6 address to look up (e.g., “8.8.8.8” or “2001:4860:4860::8888”).

  • nameserver – Optional specific nameserver IP address to use for the query. If None, uses the system default resolvers.

Returns:

A dictionary containing:
  • ip_address (str): The original IP address that was queried.

  • hostname (Optional[str]): The resolved hostname if found, with trailing dot removed. None if resolution failed.

  • error (Optional[str]): Error message if lookup failed, None for successful lookups.

  • response_time (Optional[float]): Query response time in milliseconds, rounded to 2 decimal places. None if the query failed before timing could be recorded.

Return type:

Dict[str, Union[str, float, None]]

Examples

>>> # Successful reverse lookup
>>> result = reverse_dns("8.8.8.8")
>>> print(result["hostname"])
'dns.google'
>>> print(f"Resolved in {result['response_time']}ms")
>>> # Failed reverse lookup
>>> result = reverse_dns("192.168.1.1")
>>> print(result["error"])
'No PTR record'
>>> # Using specific nameserver
>>> result = reverse_dns("1.1.1.1", nameserver="9.9.9.9")

Notes

  • The function handles both IPv4 and IPv6 addresses automatically using dns.reversename.from_address().

  • Common errors include:
    • “No PTR record”: IP exists but has no reverse DNS configured

    • “No reverse DNS”: IP range has no reverse delegation

    • “Query timeout”: DNS server didn’t respond in time

  • Trailing dots are automatically removed from hostnames for consistency with forward lookup formats.

  • Debug logs are generated for failed lookups to aid troubleshooting.