I’m having trouble writing a regular expression that matches valid IPv6 addresses, including those in their compressed form (with
:: or leading zeros omitted from each byte pair).
Can someone suggest a regular expression that would fulfill the requirement?
I’m considering expanding each byte pair and matching the result with a simpler regex.
The following will validate IPv4, IPv6 (full and compressed), and IPv6v4 (full and compressed) addresses:
It sounds like you may be using Python. If so, you can use something like this:
import socket def check_ipv6(n): try: socket.inet_pton(socket.AF_INET6, n) return True except socket.error: return False print check_ipv6('::1') # True print check_ipv6('foo') # False print check_ipv6(5) # TypeError exception print check_ipv6(None) # TypeError exception
I don’t think you have to have IPv6 compiled in to Python to get
inet_pton, which can also parse IPv4 addresses if you pass in
socket.AF_INET as the first parameter. Note: this may not work on non-Unix systems.