Working on a Python web automation project, I needed to get the IP addresses of several websites dynamically. At first, I thought it would be as simple as sending a request and getting the IP, but I quickly realized that Python provides multiple ways to handle this task, each suitable for different use cases.
In this tutorial, I’ll show you how to get an IP address from a URL in Python using a few simple and reliable methods.
I’ve been developing in Python for over a decade, and I’ll share some practical insights and examples that I personally use in real-world projects.
Method 1 – Get IP Address from URL Using Python’s socket Module
The easiest and most common way to get an IP address from a URL in Python is by using the socket module. This module comes built-in with Python, so you don’t need to install anything extra.
Here’s how I usually do it in my projects.
import socket
# Get IP address from a URL
def get_ip_from_url(url):
try:
ip = socket.gethostbyname(url)
print(f"The IP address of {url} is: {ip}")
except socket.gaierror as e:
print(f"Unable to get IP for {url}. Error: {e}")
# Example usage
get_ip_from_url("www.python.org")I executed the above example code and added the screenshot below.

This Python code uses the socket.gethostbyname() function to resolve the domain name to its corresponding IP address. If the domain is invalid or unreachable, it raises a socket.gaierror, which we handle gracefully.
In my experience, this method works best for quick lookups or when you’re working with small scripts that don’t require advanced network handling.
Method 2 – Get IP Address from URL Using getaddrinfo()
Sometimes, a domain may have multiple IP addresses (for example, IPv4 and IPv6).
In such cases, using socket.getaddrinfo() gives you a more complete picture.
Here’s how you can use it in Python:
import socket
def get_all_ips_from_url(url):
try:
addresses = socket.getaddrinfo(url, None)
ips = set()
for result in addresses:
ip = result[4][0]
ips.add(ip)
print(f"All IP addresses for {url}:")
for ip in ips:
print(ip)
except socket.gaierror as e:
print(f"Error resolving {url}: {e}")
# Example usage
get_all_ips_from_url("www.google.com")I executed the above example code and added the screenshot below.

This version of the Python script returns all available IP addresses for the given URL. It’s especially useful when you’re working with global domains or load-balanced servers, where multiple IPs are expected.
Method 3 – Get IP Address from a URL Using Python requests and socket
Sometimes, you might want to fetch the IP of the host you’re actually connecting to, especially when working with APIs or HTTPS websites. In such cases, you can combine the requests library with socket to get the IP of the resolved connection.
Here’s how I usually handle it:
import requests
import socket
from urllib.parse import urlparse
def get_ip_using_requests(url):
try:
parsed_url = urlparse(url)
hostname = parsed_url.netloc or parsed_url.path
ip = socket.gethostbyname(hostname)
response = requests.get(url)
print(f"Connected to {hostname} ({ip}) with status code: {response.status_code}")
except Exception as e:
print(f"Failed to connect to {url}. Error: {e}")
# Example usage
get_ip_using_requests("https://www.python.org")I executed the above example code and added the screenshot below.

In this Python example, we first parse the URL to extract the hostname and then use socket.gethostbyname() to get its IP. The requests library is used to confirm the connection and ensure that the IP is reachable.
This is a very practical approach when you’re testing API endpoints or validating URLs in automation scripts.
Method 4 – Get IP Address Using Python dns.resolver (Advanced)
If you work with DNS-heavy applications or need more control over how DNS queries are resolved, Python’s dnspython library is a great choice. It allows you to perform DNS lookups directly and even specify record types like A, AAAA, or MX.
Here’s a simple example:
import dns.resolver
def get_ip_with_dns(url):
try:
result = dns.resolver.resolve(url, 'A')
print(f"IP addresses for {url}:")
for ipval in result:
print(ipval.to_text())
except Exception as e:
print(f"DNS resolution failed for {url}. Error: {e}")
# Example usage
get_ip_with_dns("www.python.org")This Python code uses dns.resolver.resolve() to fetch all A records (IPv4 addresses) for the given domain. You can also change ‘A’ to ‘AAAA’ if you want to fetch IPv6 addresses.
This method is ideal when you need detailed DNS-level control or when you’re building a Python-based network monitoring or cybersecurity tool.
Tip: You can install the
dnspythonlibrary using:pip install dnspython
Method 5 – Get Local System IP Address in Python
Sometimes, you might also want to find out the IP address of your own system (the machine running the Python script).
This can be helpful in network diagnostics, logging, or configuration scripts.
Here’s a quick way to do it:
import socket
def get_local_ip():
try:
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
print(f"My system name is: {hostname}")
print(f"My local IP address is: {local_ip}")
except Exception as e:
print(f"Could not get local IP. Error: {e}")
# Example usage
get_local_ip()This Python function retrieves your computer’s hostname and then resolves it to your local IP address. It’s a lightweight and reliable way to check your local network configuration.
Bonus – Verify if an IP Address is Valid in Python
After getting an IP address, it’s often useful to verify whether it’s a valid IPv4 or IPv6 address.
Python’s ipaddress module makes this super simple.
Here’s how you can do it:
import ipaddress
def validate_ip(ip):
try:
ip_obj = ipaddress.ip_address(ip)
print(f"{ip} is a valid IP address ({ip_obj.version})")
except ValueError:
print(f"{ip} is not a valid IP address")
# Example usage
validate_ip("192.168.1.1")
validate_ip("999.999.999.999")This Python snippet checks whether the given IP is valid and also tells you whether it’s IPv4 or IPv6. It’s a great addition if you’re building tools that handle dynamic IP validation or network logging.
Real-World Example: Mapping Multiple URLs to IPs
Let’s take a more practical example where we have a list of popular U.S. websites, and we want to map each to its IP address. This is something I often do when testing network latency or API response times across different domains.
import socket
websites = [
"www.google.com",
"www.nasa.gov",
"www.nytimes.com",
"www.python.org",
"www.whitehouse.gov"
]
for site in websites:
try:
ip = socket.gethostbyname(site)
print(f"{site} ➜ {ip}")
except Exception as e:
print(f"Failed to resolve {site}: {e}")This Python script loops through each domain, resolves it, and prints the corresponding IP address. It’s a simple yet powerful way to verify network reachability or monitor DNS changes.
Common Errors and Troubleshooting Tips
When working with network-related Python functions, you may encounter a few common issues.
Here are some quick tips I’ve learned from experience:
- socket.gaierror: [Errno -2] Name or service not known
→ The domain name might be invalid or unreachable. Double-check your URL. - Timeouts or SSL errors
→ Use therequestsmodule with a timeout parameter, or verify your network connection. - DNS resolution delays
→ Try using dns.resolver for more control or switch DNS servers (e.g., Google DNS 8.8.8.8). - Permission errors
→ Run your Python script with appropriate permissions, especially on restricted networks.
These small adjustments can save you hours of debugging when dealing with real-world network applications.
Getting an IP address from a URL in Python is simple once you know the right tools.
The built-in socket module is usually enough for most cases, but if you need more control or DNS-level details, dnspython is a great choice.
Over the years, I’ve used all these methods in various Python automation and network projects across the U.S., and they’ve proven to be reliable and efficient. I hope this tutorial helps you confidently retrieve and validate IP addresses in your own Python applications.
You may also like to read:
- Use Static Variables in Python Functions
- Sort a List in Python Without Using the sort() Function
- Use the Pow() Method in Python
- Call Function by String Name in Python

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.