Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any better way to check string for valid IPv4 and IPv6?

Tags:

python

ipv6

ipv4

I have the following task:

Identify if the string has a valid IPv4 or IPv6 address using just the default modules. I've found an interesting method using socket module here it is:

import socket

ip = '10.1.0.10'
try:
    # test for IPv4
    socket.inet_pton(socket.AF_INET, ip)
except socket.error:
    try:
        # test for IPv6 
        socket.inet_pton(socket.AF_INET6, ip)
    except socket.error:
        print(ip, " is not valid")

It seems ugly to have a try under a try in such case, is there a better way? Is there a different module that could accomplish the same in a better way considering the fact that I have to check about 100 IP's.

like image 217
Attila Avatar asked Nov 27 '15 16:11

Attila


People also ask

How do I know if a string is IPv4 or IPv6?

Given a string S consisting of N characters, the task is to check if the given string S is IPv4 or IPv6 or Invalid. If the given string S is a valid IPv4, then print “IPv4”, if the string S is a valid IPv6, then print “IPv4”. Otherwise, print “-1”.

How do I check if my IPv6 address is valid?

An IPv6 address looks like XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX separated by 'colon'. A valid IPv6 address might be in the range ([0-9a-fA-F]){1,4})\:){7}([0-9a-fA-F]){1,4}) in which the first digit will be in the ranges from 0-9, second is hexadecimal alphanumeric digit.

How can you tell if an IP address is valid or invalid?

An IP address is considered valid or invalid based on the subnet mask of the network. A network contains a network ID, the usable(host) IP range and a broadcast ID. The Network ID and Broadcast ID cannot be used and this network ID and Broadcast IDs are determined by its subnet mask.

How do I find IPv4 and IPv6 addresses?

IPv4 is a 32-bit address. IPv6 is a 128-bit address. IPv4 is a numeric address that consists of 4 fields which are separated by dot (.). IPv6 is an alphanumeric address that consists of 8 fields, which are separated by colon.


1 Answers

You can use the ipaddress module. Documentation can be found here: https://docs.python.org/3/library/ipaddress.html

Sample code:

>>> ipaddress.ip_address('192.168.0.1')
IPv4Address('192.168.0.1')
>>> ipaddress.ip_address('2001:db8::')
IPv6Address('2001:db8::')
>>> ipaddress.ip_address('323.4.7.8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/ipaddress.py", line 54, in ip_address
    address)
ValueError: '323.4.7.8' does not appear to be an IPv4 or IPv6 address
>>> ipaddress.ip_address('ffff::4543:1f1f::134')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/ipaddress.py", line 54, in ip_address
    address)
ValueError: 'ffff::4543:1f1f::134' does not appear to be an IPv4 or IPv6 address
like image 154
Kacper Reutt Avatar answered Sep 22 '22 17:09

Kacper Reutt