Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a IPv6 address format with shell?

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.

like image 753
Qiu Yangfan Avatar asked Nov 07 '14 08:11

Qiu Yangfan


1 Answers

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

like image 146
tripleee Avatar answered Sep 21 '22 00:09

tripleee