Python: Get IP Address from Hostname using Socket Module
Learn how to use Python's socket module to get an IP address from a hostname. This guide covers the gethostbyname function, script examples, and error handling.
Drake Nguyen
Founder · System Architect
The Python standard library provides robust tools for network programming. One of the most common tasks in network automation and scripting is resolving a hostname (like google.com) to its underlying IP address. The built-in socket module handles this efficiently without requiring third-party installations.
Using the Python Socket Module
The socket module is part of the Python core. The primary function used to translate a host name to an IPv4 address is gethostbyname(). It accepts a string argument representing the hostname and returns the IP address as a string.
Here is a basic example of how to use this function in the Python interpreter:
>>> import socket
>>> socket.gethostbyname('google.com')
'142.250.190.46'
>>> socket.gethostbyname('example.com')
'93.184.216.34'
Understanding Dynamic IPs and CDNs
It is important to note that the IP address returned may vary based on your geographic location. Large websites often use Content Delivery Networks (CDNs) or load balancers. Consequently, looking up google.com or facebook.com might yield different results depending on which server is closest to your network request.
Python Script to Find IP Address
While the interpreter is useful for quick checks, you will often need to incorporate this functionality into scripts. Below are two methods to implement a hostname lookup tool.
Method 1: User Input Script
This script prompts the user to type a website address and then prints the resolved IP.
import socket
def get_ip_from_input():
hostname = input("Please enter website address (e.g., google.com):\n")
try:
ip_address = socket.gethostbyname(hostname)
print(f'The IP Address for {hostname} is {ip_address}')
except socket.error as err:
print(f"Error resolving {hostname}: {err}")
if __name__ == "__main__":
get_ip_from_input()
Note: The original article included a screenshot of this script in action. We recommend running the code locally to see the output in your own terminal.
Method 2: Command Line Arguments
For automation and pipeline integration, passing the hostname as a command-line argument is more efficient. We can use the sys module to access arguments passed to the script.
import socket
import sys
# Check if an argument was provided
if len(sys.argv) < 2:
print("Usage: python script.py ")
sys.exit(1)
hostname = sys.argv[1]
print(f'Resolving {hostname}...')
print(f'IP Address: {socket.gethostbyname(hostname)}')
Example Output:
$ python get_ip.py facebook.com
Resolving facebook.com...
IP Address: 157.240.23.35
Handling Errors and Exceptions
Network operations are prone to errors, such as typos in the domain name or DNS failures. If socket.gethostbyname() cannot resolve the hostname, it raises a socket.gaierror (Get Address Info Error).
To make your application robust, you should wrap the network call in a try-except block.
import socket
import sys
def resolve_hostname(hostname):
try:
ip = socket.gethostbyname(hostname)
print(f'The {hostname} IP Address is {ip}')
except socket.gaierror as e:
# Handle the specific error for invalid hostnames
print(f'Failed to resolve "{hostname}". Error: {e}')
except Exception as e:
# Handle other potential errors
print(f'An unexpected error occurred: {e}')
if __name__ == '__main__':
# Default to example.com if no argument is provided
target = sys.argv[1] if len(sys.argv) > 1 else 'example.com'
resolve_hostname(target)
Scenario: Invalid Hostname
$ python ip_lookup.py invalid-domain-name-xyz.com
Failed to resolve "invalid-domain-name-xyz.com". Error: [Errno 8] nodename nor servname provided, or not known
By implementing proper exception handling, your Python tools can gracefully handle invalid inputs without crashing, ensuring a smoother user experience.