if( $ip=~ m{^\s*((\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}))\s*$}s)
{ $ip= $1;
my @fields=( $2, $3, $4, $5);
foreach (@fields)
{ die "wrong field value: $_" if( $_ > 255); }
}
| [reply] [d/l] |
The only way to _really_ test if a number is valid is to feed it
to one of the internal functions which lives and breathes IP
addresses, such as inet_aton from Socket:
use Socket;
sub IsValidIP
{
return $_[0] =~ /^[\d\.]*$/ && inet_aton($_[0]);
}
The validation for "numeric-only" prevents any unwanted host
name resolutions, which inet_aton will gladly do for you
if you give it even half a chance. Of course, if you want
those, by all means, but you might want to use Net::DNS if you
expect to do this a lot.
It is a common misconception that IP addresses must be exactly
'N.N.N.N' formatted, when in fact, they can be in other formats
that are just as useful, such as 'N.N.N' and 'N.N' or just one
big, fat, ugly 'N'.
These IP addresses are all equivalent and are all 100% valid:
3232235778
192.11010306
49320.258
192.168.258
12625921.2
192.43009.2
49320.1.2
192.168.1.2
The numbers in the IP address are only for us computationally
impaired humans. Internally they are treated as hex, or in this
case, 0xC0A80102, which is the 3232235778 version in decimal.
The dots just split up the big hex number into smaller ones
which are easier to type in and read. 0xC0A8,0x0102 or 0xC0,
0xA8,0x01,0x02 or whatever strikes your fancy, so long as each
compontent is composed of full bytes (2 hex digits per byte).
IP addresses can be represented in these different ways because
older implementations allowed you to specify the network as
a single number, with the host dangling off the end. There
aren't many people who still use them this way, but I have
yet to see many programs which reject addresses of this format.
Even Windows 'tracert' processes them correctly, as does
Netscape, and Internet Explorer. If they're valid, you shouldn't
really be rejecting them for old-school style.
| [reply] [d/l] [select] |