One of the ways to identify a public IP address is to translate it to an associated host or domain name. This could be done by performing reverse IP lookup to the DNS servers.

The socket module provides IP-related functionalities in Python with gethostbyaddr function allows you to get the host name of an IP address.

Steps to get domain name from IP address in Python:

  1. Launch your preferred Python shell.
    $ ipython3
    Python 3.8.2 (default, Apr 27 2020, 15:53:34)
    Type 'copyright', 'credits' or 'license' for more information
    IPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help.
  2. Import socket module.
    In [1]: import socket
  3. Use socket.gethostbyaddr to get host name from an IP address.
    In [2]: socket.gethostbyaddr('')
    Out[2]: ('', [], [''])

    Hostname in this context refers to Fully Qualified Domain Name or FQDN.

  4. Create a Python script that accepts an IP address as parameter and outputs corresponding host information.
    #!/usr/bin/env python3
    import socket
    import sys
    address = sys.argv[1]
    host = socket.gethostbyaddr(address)
    print('Address: ', address, '\n' 'Host: ', host)
  5. Run the script from the command line and provide an IP address as a parameter.
    $ python3
    Host:  ('', [], [''])
Discuss the article:

Comment anonymously. Login not required.