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)?
Try
apt-get install python-ipaddr
or get the source code from here