Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: IP Address Sanity

by lestrrat (Deacon)
on Nov 07, 2002 at 22:42 UTC ( [id://211278]=note: print w/replies, xml ) Need Help??


in reply to IP Address Sanity

I don't like the regexp approach for this type of problems, I find it easier to dissect things one by one...

#!/usr/local/bin/perl use strict; sub ipverify { my( $ip ) = @_; if($ip =~ /[^\d.]/) { die "Found illegal characters in ip: $ip"; } my @octets = split( /\./, $ip ); if(@octets != 4) { die "number of octets must be 4"; } foreach my $octet (@octets) { ## numerical sanity if($octet < 0 || $octet > 255) { die "octet $octet is out of range ( 0 <= x <= 255 )"; } ## $octet should not start with a 0 if it evaluates to ## less than 100 if( $octet < 100 ) { ## if 0, octet should be single digit if($octet == 0 && length($octet) != 1) { die "bad representation '$octet'. rewrite as '0'"; } if($octet =~ /^0+(\d+)$/) { die "bad representation '$octet'. rewrite as '$1'"; } } } return 1; } sub hostname_verify { my($hostname) = @_; my $iaddr = gethostbyname($hostname); if(!$iaddr) { die "Hostname '$hostname' did not resolve"; } return 1; } sub main { while(1) { print "Type in IP address or hostname to verify (enter to quit +): "; chomp(my $input = <STDIN>); if(!length($input)) { last; } if($input =~ /\D/) { eval{ hostname_verify($input) }; } else { eval{ ip_verify($input) }; } if($@) { (my $err = $@) =~ s/ at .*$//; print STDERR " ERROR: $err\n"; } else { print "$input is a valid address\n"; } } } main();

Replies are listed 'Best First'.
Re: Re: IP Address Sanity
by FamousLongAgo (Friar) on Nov 07, 2002 at 22:46 UTC
    The test for an octet < 0 is not necessary, since a negative number won't get past the initial regex test.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2024-04-23 22:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found