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 |