Python offers native support for resolving hostnames or domain names to IP addresses using the socket module. This is essential for network programming, allowing scripts to interact with network resources efficiently. The primary functions for this are gethostbyname() and gethostbyname_ex().
gethostbyname() returns a single IP address for a given hostname. If the hostname has multiple IP addresses, use gethostbyname_ex() to retrieve all associated IP addresses. These functions are simple to use and integrate into Python scripts for tasks like logging and monitoring.
Python scripts can resolve hostnames both interactively and programmatically. This makes it a versatile tool for network-related tasks. Whether you're dealing with a single IP or a list, these functions provide the necessary capabilities to manage and interact with network systems effectively.
Steps to get IP address from hostname or domain in Python:
- 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.
- Import socket module.
In [1]: import socket
- 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.
- 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)
- 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
Mohd Shakir Zakaria is an experienced cloud architect with a strong development and open-source advocacy background. He boasts multiple certifications in AWS, Red Hat, VMware, ITIL, and Linux, underscoring his expertise in cloud architecture and system administration.
Comment anonymously. Login not required.