0

I have the following bash script to validate IP addresses:

#!/bin/bash
validFormatIP()
{
    grep -E -q '^(25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1]?[1-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' <<< "$1" && echo "Valid IP" || echo "Invalid IP" 
}

validFormatIP $1

It validates IP addresses properly for the first, second and third bytes but not the fourth byte.

Here's the output of my script to better illustrate what is going wrong:

$ ./script.bash 1000.33.0.1
Invalid IP
$ ./script.bash 34.1000.0.1
Invalid IP
$ ./script.bash 34.33.1000.1
Invalid IP
$ ./script.bash 34.33.0.1000
Valid IP
$ 

As you can see it accepts 1000 as a valid value for the last byte even though it's actually invalid.

Any one have any idea where the problem is?

TimP
  • 210
  • 2
  • 11
Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/48446/discussion-between-jkb-and-mortezalsc) – Jayesh Bhoi Feb 26 '14 at 08:59

2 Answers2

2

This is simply because you don't anchor it at the end, so it matches the "34.33.0.100" in "34.33.0.1000". Add a $ to the end of your expression:

    grep -E -q '^(25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1]?[1-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$' <<< "$1" && echo "Valid IP" || echo "Invalid IP" 
that other guy
  • 116,971
  • 11
  • 170
  • 194
2

You need to add $ to the end of the regex, it will tell regex to ensure the last character matches the pattern.

^(25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1]?[1-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$

Should work for you!

However, here is a much shorter patter that should do the same thing.

^((25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})$

You are able to use {x,X} to specify min and max x=min and X=MAX and of course you will need to drop it in some quotes.

Linx
  • 156
  • 2