Last modified: Sep 13, 2026
Parse IP Address in Python: A Beginner's Guide
IP addresses are essential for network communication. Parsing them in Python helps validate, categorize, or process network data. This guide explains how to parse and handle IPv4 and IPv6 addresses using Python’s built-in ipaddress module.
What is an IP Address?
An IP address identifies devices on a network. IPv4 uses 32-bit numbers (e.g., 192.168.1.1), while IPv6 uses 128-bit addresses (e.g., 2001:0db8:85a3::8a2e:0370:7334). Parsing converts these strings into structured objects for analysis.
Python’s ipaddress module simplifies this process. It supports both IPv4 and IPv6, making validation and manipulation straightforward.
Using the ipaddress Module
The ipaddress.ip_address() function parses a string into an IPv4 or IPv6 object. Here’s how:
import ipaddress
# Parse an IPv4 address
ipv4 = ipaddress.ip_address("192.168.1.1")
print(ipv4)
# Parse an IPv6 address
ipv6 = ipaddress.ip_address("2001:0db8:85a3::8a2e:0370:7334")
print(ipv6)
192.168.1.1
2001:db8:85a3::8a2e:370:7334
This code creates objects that expose properties like version, compressed, and exploded formats.
Validating IP Addresses
Invalid IP strings raise a ValueError. Use a try-except block to validate:
def validate_ip(ip_str):
try:
ip_obj = ipaddress.ip_address(ip_str)
print(f"Valid IP: {ip_obj}")
return True
except ValueError:
print("Invalid IP address")
return False
# Test invalid input
validate_ip("999.999.999.999")
Invalid IP address
Validation ensures your application rejects malformed inputs gracefully.
Handling IPv4 and IPv6 Differences
The version attribute identifies the IP type. Use it to branch logic:
ip = ipaddress.ip_address("10.0.0.1")
if ip.version == 4:
print("IPv4 address")
else:
print("IPv6 address")
IPv4 address
IPv4 and IPv6 have distinct use cases.
Common Errors and Solutions
1. **Invalid strings**: Use ip_address() with try/except. 2. **Network ranges**: Use ip_network() for subnets. 3. **Compression**: Use compressed for shorter IPv6 outputs.
# Example: Compressed IPv6
ipv6_compressed = ipaddress.ip_address("2001:0db8:85a3:0000:0000:8a2e:0370:7334").compressed
print(ipv6_compressed)
2001:db8:85a3::8a2e:370:7334
Handling these errors improves code robustness.
Conclusion
Python’s ipaddress module is a powerful tool for parsing and validating IP addresses. By mastering ip_address(), you can handle IPv4 and IPv6, validate inputs, and avoid common pitfalls.
With this knowledge, you’re ready to process network data efficiently. Start coding today!