1

I am using below script to validate IPV6 address but this script also pass invalid IP such as empty string, name etc.

if [[ "$IPv6ADDR"=~"^:?([a-fA-F0-9]{1,4}(:|.)?){0,8}(:|::)?([a-fA-F0-9]{1,4}(:|.)?){0,8}$" ]]; then
  echo "valid ipv6 addr"
else
  echo "Invalid IP Address"
fi

Can someone identify what's wrong in the regex, please?

2
  • The most basic error is that you need whitespace on both sides of the =~ operator. Commented Feb 6, 2016 at 11:01
  • You probably don't want to use a regular expression for IPv6 addresses. Commented Feb 6, 2016 at 15:20

1 Answer 1

2

The reason why it passes an empty string is that all of your content is optional or allowed to match 0 times:

  • ^ - match beginning of string
  • :? - optional colon
  • ([a-fA-F0-9]{1,4}(:|.)?){0,8} - matches 0 - 8 times (thus optional)
  • (:|::)? - optional colon or double colon
  • ([a-fA-F0-9]{1,4}(:|.)?){0,8} - matches 0 - 8 times (thus optional)
  • $ - matches end of string

Thus a blank string is allowed, as your pattern allows a string to not match any of the optional parts.


Looking at RFC 4291, which defines the IP 6 specification, section 2.2 defines three methods of representing the address. It may be easiest, if you need to match all forms to define them separately and combine the separate regex's together, as in

^(regex_pattern1|regex_pattern2|regex_pattern3)$

where pattern1, for example, is (?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4} and patterns 2 and 3 are for the other cases (pattern 1 taken from Regular Expressions Cookbook, 2nd Edition (O'Reilly, 2012))

Or, even better (for readability), test them in serial (pseudocode follows),

if (matches pattern 1)
    echo 'valid'
else if (matches pattern 2)
    echo 'valid'
else if (matches pattern 3)
    echo 'valid'
else
    echo 'invalid'

See, also, this question for some more information.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Mathew for the valuable input.
@user2145274, You're welcome. If you find an answer helpful, please consider accepting it. You are under no obligation to do so, but this awards both the author and yourself with a small amount of reputation, and lists the question as answered. Remember also that you can upvote particularly helpful answers on your own questions or any other question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.