Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: IP Address Sanity

by jdporter (Canon)
on Nov 07, 2002 at 23:34 UTC ( #211290=note: print w/ replies, xml ) Need Help??


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";


Comment on Re: IP Address Sanity
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://211290]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2015-07-05 23:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (68 votes), past polls