Archive

Posts Tagged ‘ip’

validate an IP address (either IPv4 or IPv6)

January 9, 2017 Leave a comment

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: , , ,