Operating System - HP-UX
1819793 Members
3221 Online
109607 Solutions
New Discussion юеВ

use perl to check if IP ip address is valid

 
SOLVED
Go to solution
Mike_Ca Li
Regular Advisor

use perl to check if IP ip address is valid

want to check if ip is in range
0-254 for each of the octets. Could someone help with the regular expression match. Thank you.

$ perl -e 'if ( '123.150.45.46' =~ /^?[0-254].?[0-254].?[0-254].?[0-254]/ ) { p
rint "ip-is-ok" ;} else {print "ip-not-ok" ; }'
ip-not-ok
3 REPLIES 3
H.Merijn Brand (procura
Honored Contributor
Solution

Re: use perl to check if IP ip address is valid

lt09:/home/merijn 110 > perl -le'$_=shift;print$_,(m/^(?:(\d+)(??{$+>=0&&$+<255?q{\.|$}:q{X}})){4}/)?" ok":" not ok"' 123.123.123.1233
123.123.123.1233 not ok
lt09:/home/merijn 111 > perl -le'$_=shift;print$_,(m/^(?:(\d+)(??{$+>=0&&$+<255?q{\.|$}:q{X}})){4}/)?" ok":" not ok"' 123.123.123.123
123.123.123.123 ok
lt09:/home/merijn 112 >

Enjoy, Have FUN! H.Merijn [ Just one of many ways to do it ]
Enjoy, Have FUN! H.Merijn
Muthukumar_5
Honored Contributor

Re: use perl to check if IP ip address is valid

You can use split function to split it with . delimiter and check less than 256 and greater that 0.

# perl -e '$var="343.150.45.46"; @IP=split(/\./,$var); if ( ($IP[0] < 256 && $IP[0] > 0) && ($IP[1] < 256 && $IP[1] > 0) && ($IP[2] < 256 && $IP[2] > 0) && ($IP[3] < 256 && $IP[3] > 0)) { print "IP $var is ok";} else { print "IP $var is not ok"; }'

hth.
Easy to suggest when don't know about the problem!
Johnathan Loggie
New Member

Re: use perl to check if IP ip address is valid

Note that [0-254] means 0-2 (e.g 0,1,2)
plus 4 so you would not have matched (3,5,6,7,8,9)

Here is what I use ...


my @ip = split /\./, $ARGV[0];
print "ERROR\n" if (4 ne scalar @ip || 4 ne scalar map { $_ =~ /^(0|[1-9]\d*)$/ && $1 < 256 ? 1 : () } @ip)


This is how it works ...

Using split is the best bet to get the octets. You then need to check that you have 4 octets and that each one is valid.

The octet must be a valid number e.g /^\d+$/

You may not want it to be 0 prefixed but remember that '0' is valid, so this expression would catch that /^(0|[1-9]\d*)/

You then need to check that the octet is < 256. The () arround the expression will evaluate to $1 so you can do $1 < 256.

By using map over the list of octets you can run the regex and < check for each octet.

By returning any value when the condition succeeds (I used 1) and empty list () when the condition fails, map returns a list which is smaller than the source list. You would expect to get back 4 items in the list if all octets matched the condition. So compare 4 to scalar (number of items in list) of the map and if this != 4 then clearly one or more of the octets was not valid.