Shortcut for IP conversion

I got sick of spending time converting IP addresses to various formats. ipconv.pl is a quickie CGI shortcut to convert a dotted-quad IP address to decimal, hex, octal and binary. And here's the quickie code: #!/usr/bin/perl -Tw use strict; my ($ipaddr, $octet, @octets, @octets8, $octet8, $iphex, $ipbin, $ipdec); use CGI qw/:standard/; my $version = "0.1"; sub do_results { @octets = split (/\./, $ipaddr); if (@oc

I got sick of spending time converting IP addresses to various formats. ipconv.pl is a quickie CGI shortcut to convert a dotted-quad IP address to decimal, hex, octal and binary.

And here's the quickie code:

#!/usr/bin/perl -Tw

use strict;

my ($ipaddr, $octet, @octets, @octets8, $octet8, $iphex, $ipbin, $ipdec);

use CGI qw/:standard/;

my $version = "0.1";
sub do_results {

        @octets = split (/\./, $ipaddr);

        if (@octets != 4) {
                print "Invalid IP address";
                exit;
        }
        foreach $octet (@octets) {
                if ($octet > 255) {
                        print "Invalid IP address";
                        exit;
                }
                $iphex .= sprintf("%2.2X", $octet);
                $octet8 = sprintf "%lo", $octet;
                push @octets8, ($octet8 > 7) ? "0$octet8" : $octet8;
        }

        $ipdec = hex($iphex);
        $ipbin = unpack("B*", pack("N", $ipdec));

        print("<table BORDER=1 CELLPADDING=5><th>Format</th><th>Value</th>",
        "<tr><td>Decimal</td><td>$ipdec</td><tr>",
        "<td>Octal</td><td> ", join('.', @octets8),
        "</td><tr>",
        "<td>Hex</td><td>0x$iphex</td><tr>",
        "<td>Binary</td><td>$ipbin</td><tr>",
        "</table>");

}

print header,
        start_html('ipconv.pl'),
        h1('ipconv.pl'),
        small('ipconv.pl v',$version),br,
        small('Paul Venezia, 01.26.04'),
        hr,
        start_form,
        "Enter a dotted-quad decimal IP address:  ",textfield('ipaddr'),p,
        submit,
        defaults('Reset'),
        end_form,
        hr;

$ipaddr = param('ipaddr');
&do_results if $ipaddr;

Recommended
Join the discussion
Be the first to comment on this article. Our Commenting Policies