One of the ways to identify a public IP address is to translate it to an associated host name.

IP-related functions in Python are provided by the socket module and gethostbyaddr function within the module allows you to get the host name of an IP address.

Steps to get host 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('93.184.216.34')
    Out[2]: ('www.example.com', [], ['93.184.216.34'])

    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.
    ip-to-hostname.py
    #!/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 parameter.
    $ python3 ip-to-hostname.py 216.58.196.4
    Address:  216.58.196.4
    Host:  ('kul08s09-in-f4.1e100.net', [], ['216.58.196.4'])
Discuss the article:

Comment anonymously. Login not required.

Share!