Validating the IP address with the socket package

We can use also the socket package to validate an IP address in both IPv4 and IPv6.

You can find the following code in the check_ip_address.py file:

import socket

def is_valid_ipv4_address(address):
try:
socket.inet_pton(socket.AF_INET, address)
except AttributeError:
try:
socket.inet_aton(address)
except socket.error:
return False
return address.count('.') == 3
except socket.error: # not a valid address
return False

return True

def is_valid_ipv6_address(address):
try:
socket.inet_pton(socket.AF_INET6, address)
except socket.error: # not a valid address
return False
return True

print("IPV4 127.0.0.1 OK:"+ str(is_valid_ipv4_address("127.0.0.1")))
print("IPV4 127.0.0.0.1 NOT OK:"+ str(is_valid_ipv4_address("127.0.0.0.1")))

print("IPV6 ::1 OK:"+ str(is_valid_ipv6_address("::1")))
print("IPV6 127.0.0.0 NOT OK:"+ str(is_valid_ipv6_address("127.0.0.0.1")))

This is the execution of the previous script, where we can see that 127.0.0.1 is a valid IPv4 address and ::1 is a valid IPv6 address:

IPV4 127.0.0.1 OK:True
IPV4 127.0.0.0.1 NOT OK:False
IPV6 ::1 OK:True
IPV6 127.0.0.0 NOT OK:False
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset