shell code to check IP v4

Hi,

Is there any tool or part of a script that I can use in my shell scripts to check if an IP v4 is correct (dotted-quad and in the right form) and possibly if it is a range {IP, Mask}?
 
First one should be easy, just some form of regular expression like
Code:
[1-255]\.[0-255]\.[0-255]\.[0-255]
should be fine (except not checking for reserved address space etc.)

Second is more challenging, I will try to split octets, transform them to binary form with bc(), join them and check if
  • Input matches range in first X bites defined by mask
  • Rest of input (non-masked part) is between rest of network address and all 1
 
ondra_knezour said:
First one should be easy, just some form of regular expression like
Code:
[1-255]\.[0-255]\.[0-255]\.[0-255]
should be fine (except not checking for reserved address space etc.)

Regex ranges only work on single characters, though. Splitting out the octets is probably a better way.

Code:
input="192.168.1.1"

IFS='.'
for octet in $input; do
  if [ $octet > 255 ]; then
    echo "$octet greater than 255"
    exit
  fi
done

Note that this doesn't count the octets, since--technically--four are not required. That's another test that a more-strict script could do.

Or just go with Perl and use net-mgmt/p5-Data-Validate-IP.
 
Back
Top