The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague.
many solutions have been proposed in the article and in the comments. To summarize, you can build a function that accepts an argument and checks if that argument is a number and is between 0 and 255, and use that function to check that all four octets are valid. The skeleton of a program is as follows:
awk -F[.] '
function ok(n) {
# do something here to check the value of n,
# and return 1 if it's valid, 0 otherwise
}
{exit ( ok($1) && ok($2) && ok($3) && ok($4) )'
(to make it more robust, you may optionally check that the number of input fields (ie, octets) is exactly 4, no more and no less)
so you will call it as follows, for example:
echo "123.123.123.123" | awk -F[.] '...'
if [ $? -eq 1 ]; then
echo "valid IP address"
else
echo "invalid IP address"
fi
where the part '...' is the complete awk program.
Note that, to follow shell conventions, you may choose to have the awk program return 0 on success and 1 on failure instead.
That said, here are two ways to implement function ok:
function ok(n) {
# string check using a regex
return (n~/^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$/)
}
function ok(n) {
# check that n is a number, and then that
# it is in the range 0-255
return (n~/^[0-9]*$/ && n>=0 && n<=255)
}
Again, you might choose to negate the return values if you want to return 0 on success.
I am being sponsored by Syntress! They bought me an amazing dedicated server to run catonmat on. If you're looking web services, I highly recommend the Syntress guys!
@Rob:
many solutions have been proposed in the article and in the comments. To summarize, you can build a function that accepts an argument and checks if that argument is a number and is between 0 and 255, and use that function to check that all four octets are valid. The skeleton of a program is as follows:
awk -F[.] ' function ok(n) { # do something here to check the value of n, # and return 1 if it's valid, 0 otherwise } {exit ( ok($1) && ok($2) && ok($3) && ok($4) )'(to make it more robust, you may optionally check that the number of input fields (ie, octets) is exactly 4, no more and no less)
so you will call it as follows, for example:
where the part '...' is the complete awk program.
Note that, to follow shell conventions, you may choose to have the awk program return 0 on success and 1 on failure instead.
That said, here are two ways to implement function ok:
function ok(n) { # string check using a regex return (n~/^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$/) } function ok(n) { # check that n is a number, and then that # it is in the range 0-255 return (n~/^[0-9]*$/ && n>=0 && n<=255) }Again, you might choose to negate the return values if you want to return 0 on success.
Reply To This Comment