in reply to IP Address Sanity
The problem with your general approach is that IP addresses aren't really textual strings, they're 32-bit integers. The dotted-quad is just one convenient representation. But it's not the only one.
A proper solution to your stated need is to use the inet_aton and inet_ntoa functions provided by the Socket module, which is part of the standard library.
inet_aton translates any valid IP address -- regardless of notation format -- or domain name into a packed string containing the 32-bit integer. Such a string can be converted into a dotted-quad representation by the inet_ntoa function.
Example:
use Socket; # load inet_aton, inet_ntoa $_ = <>; # read user's input chomp; # convert to packed string. succeeds if valid address. my $ip = inet_aton( $_ ); # length will be 4 for IPv4 addresses. length($ip) or die "Sorry, '$_' is invalid.\n"; $ip = inet_ntoa($ip); # convert to dotted quad. print "$_ is valid; its IP address is $ip\n";
|
---|
In Section
Seekers of Perl Wisdom