snimmaka has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, Can anyone please help me out in wrting a perl program to differentiate IPV4 and IPv6 address.
  • Comment on program to differentitate IPV4 and IPV6 address

Replies are listed 'Best First'.
Re: program to differentitate IPV4 and IPV6 address
by sauoq (Abbot) on May 21, 2012 at 12:25 UTC

    Use Regexp::IPv6, IPv4, and/or any of several other modules available on CPAN.

    use Regexp::IPv6 qw($IPv6_re); use IPv4; my $address = ; # Add your address here. if ($address =~ /^$IPv6_re$/) { print "IPv6\n"; } elsif (IPv4::check_ip($address)) { print "IPv4\n"; } else { print "Neither.\n"; }

    -sauoq
    "My two cents aren't worth a dime.";
Re: program to differentitate IPV4 and IPV6 address
by marto (Cardinal) on May 21, 2012 at 09:20 UTC
Re: program to differentitate IPV4 and IPV6 address
by Anonymous Monk on May 21, 2012 at 17:38 UTC
    if ( $addr =~ /\./ ) { print "IPv4" } else { print "IPv6" }

    I know it's not exactly standards based, but there aren't any dots in IPv6 addresses. Yes, of course, the hostname could have dots, but that's not an IP address either.

      This is precisely where my mind was when I read the question, but to be accurate, you'd have to reverse the logic a bit. Because RFC 4291 allows for v4 mapped addresses (IPv4 addresses embedded within the v6 address), searching for a dot may give false positives in rare circumstances. The following corrects that problem unambiguously:

      if ( $addr =~ /:/ ) { print "IPv6"; } else { print "IPv4"; }