Python supports converting hostname or domain name to IP addresses without using an external program. The feature is provided by the gethostbyname function from the socket module.
gethostbyname outputs a single IP address for a given domain. If the host or domain has multiple IP addresses, you can use gethostbyname_ex(). gethostbyname_ex() returns the IP list as an array.
You can use gethostbyname and gethostbyname_ex() to resolve a hostname to IP address in Python by using the interactive shell or within a script.
$ 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.
In [1]: import socket
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.
#!/usr/bin/env python3 import socket import sys hostname = sys.argv[1] ip = socket.gethostbyname(hostname) print('Hostname: ', hostname, '\n' 'IP: ', ip)
$ python3 hostname-to-ip.py 'www.google.com' Hostname: www.google.com IP: 172.217.31.68
Comment anonymously. Login not required.