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?

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • The most basic error is that you need whitespace on both sides of the `=~` operator. – tripleee Feb 06 '16 at 11:01
  • You probably don't want to use a [regular expression for IPv6 addresses](http://www.vankouteren.eu/blog/2009/05/working-ipv6-regular-expression/). – chepner Feb 06 '16 at 15:20

1 Answers1

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.

Community
  • 1
  • 1
Matthew
  • 7,440
  • 1
  • 24
  • 49
  • Thanks Mathew for the valuable input. – user2145274 Feb 07 '16 at 09:57
  • @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. – Matthew Feb 11 '16 at 07:31