In my shell, I need check if a string is a valid IPv6 address.
I find two ways, neither of them is ideal enough to me.
One is http://twobit.us/2011/07/validating-ip-addresses/, while I wonder if it must be such complex for such a common requirement.
The other is expand ipv6 address in shell script, this is simple, but for major distribution of Linux, sipcalc isn't a common default utility.
So my question, is there a simple way or utility to validate a IPv6 address with shell?
Thanks in advance.
The code in the first link isn't particularly elegant, but modulo stylistic fixes, I don't think you can simplify much beyond that (and as indicated in a comment, it may already be too simple). The spec is complex and mandates a number of optional features, which is nice for the end user, but cumbersome for the implementor.
You could probably find a library for a common scripting language which properly encapsulates this logic in a library. My thoughts would go to Python, where indeed Python 3.3 includes a standard module called ipaddress
; for older versions, try something like
#!/usr/bin/env python
import socket
import sys
try:
socket.inet_pton(socket.AF_INET6, sys.argv[1])
result=0
except socket.error:
result=1
sys.exit(result)
See also Checking for IP addresses
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With