Are there any existing libraries to parse a string as an ipv4 or ipv6 address, or at least identify whether a string is an IP address (of either sort)?
Are there any existing libraries to parse a string as an ipv4 or ipv6 address, or at least identify whether a string is an IP address (of either sort)?
You can use the netaddr library. It has valid_ipv4/valid_ipv6 methods:
import netaddr
if netaddr.valid_ipv4(str_ip) is True:
print("IP is IPv4")
else:
if netaddr.valid_ipv6(str_ip) is True:
print("IP is IPv6")
I prefer ip_interface because it handles situations both with and without prefix mask, for example, both "10.1.1.1/24" as well as simply "10.1.1.1". Needless to say, works for both v4 as well as v6
from ipaddress import ip_interface
ip_interface("10.1.1.1/24").ip
ip_interface("10.1.1.1/24").ip.version
ip_interface("10.1.1.1").ip
ip_interface("10.1.1.1").ip.version