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

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

Complementary video guide:

Get IP address from Hostname in Python

  1. Launch your favourite Python shell.
    $ ipython
    Python 3.7.0 (default, Jun 29 2018, 20:13:13)
    Type 'copyright', 'credits' or 'license' for more information
    IPython 6.5.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('')
    Out[2]: ''

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

  4. Create a Python script that accepts hostname as parameter and outputs IP address such as the following.
    #!/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 parameter to test.
    $ python3 ''

Discuss the article:

Comment anonymously. Login not required.