You're replying to a comment by waldner.

waldner Permalink
November 10, 2008, 22:41

@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:

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.

Reply To This Comment

(why do I need your e-mail?)

(Your twitter name, if you have one. (I'm @pkrumins, btw.))

Type the first letter of your name: (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.