Reputation: 2832
I have a large set of strings which I already know it holds an IP address and I want to determine if it's IPv4 or IPv6. Currently I'm checking whether the string contains a colon:
version = 4
if ':' in ip_string:
version = 6
Is there a faster way to determine the IP version, given that we already know it's an IP address. Is there any possibility that the above simple check can return the wrong result (for example is it possible to have an IPv6 address without a colon)?
Upvotes: 2
Views: 2288
Reputation: 2933
Use ipaddress in python to check the version. Below is the example-
import ipaddress
#str1='10.10.10.2/24'
str1 = '2b11::327a:7b00/120'
[address, netmask] = str1.split('/')
ip_ver = ipaddress.ip_address(str(address))
if ip_ver.version == 4:
print('IPv4')
else:
print('IPv6')
Output:
IPv6
Note: Tested in Python 3.7.2
Upvotes: 3