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();

In reply to Re: IP Address Sanity by lestrrat
in thread IP Address Sanity by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.