Home > python > validate an IP address (either IPv4 or IPv6)

validate an IP address (either IPv4 or IPv6)

Problem
You want to validate an IP address. However, it can be either IPv4 or IPv6.

Solution
Python 3 has a built-in module for this: ipaddress. Example:

>>> ipaddress.ip_address('192.168.0.1')
IPv4Address('192.168.0.1')
>>> ipaddress.ip_address('2001:db8::')
IPv6Address('2001:db8::')

If the IP is invalid, you get a ValueError exception.

Advertisements
Categories: python Tags: , , ,
  1. October 23, 2017 at 12:17

    In Python 2.7 you can also do this :

    def check_ip(ip_addr, version):
    
        if version == 4:
            try:
                socket.inet_aton(ip_addr)
            except socket.error:
                return 1
            else:
                return 0
    
        elif version == 6:
            try:
                socket.inet_pton(socket.AF_INET6, ip_addr)
            except socket.error:
                return 1
            else:
                return 0
    
  2. October 23, 2017 at 15:17

    The code I wrote in my previous comment lacks of efficiency because inet_aton() also accepts strings with less than three dots (like 192.168.1 for example).

    So the code I wrote before is not good enough to test an IPv4 address and should be like this instead :

    def check_ip(ip_addr, version):
    
        if version == 4:
    
            if ip_addr.count('.') != 3:
                return 1
            try:
                socket.inet_aton(ip_addr)
            except socket.error:
                return 1
            else:
                return 0
    
        elif version == 6:
    
            if ip_addr.count(':') != 7:
                return 1
            try:
                socket.inet_pton(socket.AF_INET6, ip_addr)
            except socket.error:
                return 1
            else:
                return 0
    

    I might also add that the function inet_pton() is only available on Unix systems (and maybe not on all platforms according to Python official documentation).

    Sorry for the mistakes and the lack of precision.

  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: