in reply to RE: Matching an IP address
in thread Matching an IP address

Hmm.. A small issue: Your code allows IP addresses that contain "255" in an octet, or "0" as the last octet, which isn't bad if you're trying to match subnets or broadcasts but won't work perfectly for hosts. Subtle, but how about:
unless ($get && $get =~ /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[1-9]{1,3}$/ && !grep { $_ < 0 || $_ > 254 } split(/\./, $get) ) { print "MYSTIFYING: invalid target specified\n"; exit +(-1);}

Signature void where prohibited by law.

Replies are listed 'Best First'.
(tye)RE: Matching an IP address
by tye (Sage) on Feb 22, 2001 at 10:57 UTC

    Sorry, but 255 and 0 are both valid values for octets. Not that you aren't the first person to make that mistake. Part of the installation process for WinNT doesn't allow 0 octets, which caused us interesting problems. For example, 11.0.255.1 is a perfectly valid IP address. Now you could play lots of games with determining which values are valid for the first octet and/or require that the netmask be passed in and use that to do a proper check... But I don't think such is at all worth it.

            - tye (but my friends call me "Tye")
      I think you misunderstood me (and read my flawed code for help), because what I meant was that 0 and 255 are *NOT* valid values for a *host* in the last octet, but you're right, they're valid anywhere else (except of course, a 0 in the first octet unless you're using all-zeros broadcast, which is non-standard by modern convention, or a 255 in the first octet, which is valid only for broadcast addresses). But that's pedantic.

      If you want to do a complete test, the NetAddr::IP module from CPAN (or just use the trick of trying to open a socket with the address and see if it works).

      But I did make a mistake; the regexp I wrote does needs to account for 0's in the last octet, provided that the last octet does not contain *only* zeros. So a more correct version would be this, if you wanted to ONLY verify *HOST* addresses and not broadcasts or subnets (please note: the regexp below does not prohibit '255' values in the first or last octet, which are technically invalid for *host* addresses):

      unless ($get && $get =~ /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[1-9][0-9]{0, +2}$/ && !grep { $_ < 0 || $_ > 255 } split(/\./, $get) ) { print "BAFFLING: invalid target specified\n"; exit(- +1);}

      Signature void where prohibited by law.

        Actually, what is not allowed for hosts is to have the "host" half of the address (based on the netmask) be all 0 bits or all 1 bits. That still allows for the last octet to be 0 (though not for standard Class C IP addresses, which are the most common for most people).

        So I still think trying to disallow such is a mistake.

                - tye (but my friends call me "Tye")