Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to check if the given string is IPv4 or IPv6 or Invalid
An IP address is the short form of Internet Protocol address, which is a numerical label assigned to each device connected to a computer network that uses the Internet Protocol for communication. It serves as an identifier for the device, allowing it to send and receive data over the network.
IPv4 (Internet Protocol version 4): This is the most widely used version of IP addresses. It consists of four sets of numbers separated by periods, such as "192.168.0.1". Each set can have a value between 0 and 255.
IPv6 (Internet Protocol version 6): This is the newer version designed to address IPv4 limitations. IPv6 addresses are written in hexadecimal and separated by colons, such as "2001:0db8:85a3:0000:0000:8a2e:0370:7334".
Python provides several approaches to validate IP addresses. Let's explore the most effective methods ?
Using ipaddress Module
Python's ipaddress module provides the ip_address() function to check if a given string is a valid IP address. This is the most reliable approach ?
import ipaddress
def check_ip_address(ip):
try:
ipaddress.ip_address(ip)
if ":" in ip:
return "IPv6"
else:
return "IPv4"
except ValueError:
return "Invalid"
# Test with different IP addresses
test_ips = [
"192.168.0.1",
"2001:0db8:85a3:0000:0000:8a2e:0370:7334",
"256.300.1.1",
"invalid_ip"
]
for ip in test_ips:
result = check_ip_address(ip)
print(f"{ip} is {result}")
192.168.0.1 is IPv4 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is IPv6 256.300.1.1 is Invalid invalid_ip is Invalid
Using Regular Expressions
The re module allows pattern matching using regular expressions. We can define patterns for IPv4 and IPv6 addresses ?
import re
def check_ip_address_regex(ip):
# Pattern for IPv4: four groups of 1-3 digits separated by dots
ipv4_pattern = r'^(\d{1,3}\.){3}\d{1,3}$'
# Pattern for IPv6: eight groups of 1-4 hex digits separated by colons
ipv6_pattern = r'^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$'
if re.match(ipv4_pattern, ip):
# Additional check for valid IPv4 ranges (0-255)
parts = ip.split('.')
if all(0 <= int(part) <= 255 for part in parts):
return "IPv4"
else:
return "Invalid"
elif re.match(ipv6_pattern, ip):
return "IPv6"
else:
return "Invalid"
# Test the function
test_ips = [
"192.168.0.1",
"255.255.255.255",
"256.1.1.1",
"2001:0db8:85a3:0000:0000:8a2e:0370:7334"
]
for ip in test_ips:
result = check_ip_address_regex(ip)
print(f"{ip} is {result}")
192.168.0.1 is IPv4 255.255.255.255 is IPv4 256.1.1.1 is Invalid 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is IPv6
Using Socket Module
The socket module provides inet_pton() function to validate IP addresses by attempting to convert them ?
import socket
def check_ip_address_socket(ip):
try:
# Try IPv4 first
socket.inet_pton(socket.AF_INET, ip)
return "IPv4"
except socket.error:
try:
# Try IPv6
socket.inet_pton(socket.AF_INET6, ip)
return "IPv6"
except socket.error:
return "Invalid"
# Test the function
test_ips = [
"10.0.0.1",
"::1",
"2001:db8::1",
"invalid.ip.address"
]
for ip in test_ips:
result = check_ip_address_socket(ip)
print(f"{ip} is {result}")
10.0.0.1 is IPv4 ::1 is IPv6 2001:db8::1 is IPv6 invalid.ip.address is Invalid
Comparison
| Method | Accuracy | Performance | Best For |
|---|---|---|---|
ipaddress module |
Highest | Good | General validation |
| Regular expressions | Medium | Fast | Custom pattern matching |
socket module |
High | Good | Network programming |
Conclusion
The ipaddress module is the most reliable method for IP address validation in Python. Use regular expressions when you need custom pattern matching or the socket module for network-related applications.
