Python has a built-in function to convert hostname to IP addresses without using an external program.

It is provided by the socket module and you can use the gethostbyname function within the module to resolve hostname to IP address.

Step-by-step video guide:

You can resolve a hostname to IP address in Python by using the interactive shell or writing a script.

Steps to get IP address from Hostname in Python:

  1. Launch your favourite 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. Get IP from hostname by calling socket.gethostbyname function with hostname as parameter .
    In [2]: socket.gethostbyname('www.google.com')
    Out[2]: '216.58.196.4'

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

    Use gethostbyname_ex() instead if the domain has multiple IP addresses.

  4. Create a Python script that accepts hostname as parameter and outputs IP address such as the following.
    hostname-to-ip.py
    #!/usr/bin/env python3
     
    import socket
    import sys
     
    hostname = sys.argv[1]
    ip = socket.gethostbyname(hostname)
     
    print('Hostname: ', hostname, '\n' 'IP: ', ip)
  5. Run the script from the command line with hostname as a parameter to test.
    $ python3 hostname-to-ip.py 'www.google.com'
    Hostname:  www.google.com
    IP:  172.217.31.68

Discuss the article:

Comment anonymously. Login not required.

Share!