#!/usr/bin/perl

# ipconverter.pl - examples

### Check for some arguments
if ($ARGV[0] eq "-h" || $ARGV[0] eq "--help" || ! $ARGV[0]) {
  die "Converts IP address to decimal/hex/binary.\n\nUsage: $0 ipaddress\n\n";
}

### Sanity check arguments and example regex of an IP address - almost...
if ($ARGV[0] !~ /[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}/ ) {
  die "Invalid IP address given\n";
}

### Convert to Hex
foreach $octet (split(/\./,$ARGV[0], 4)) {
  die "Invalid IP address given\n" if($octet < 0 || $octet > 255);
  $hex .= sprintf("%02x",$octet);
}
print "Hex is: $hex\n";

### Convert to binary

$binary = unpack("B32", pack("N", hex($hex)));
$binary =~ s/^0+(?=\d)//;   # otherwise you'll get leading zeros
print "Binary is: $binary\n";

### Convert to decimal
$decimal = hex($hex);
print "Decimal is: $decimal\n";

### Back to Hex
$hexagain = sprintf("%08x", $decimal);
print "Hex again is: $hexagain\n";

### Back to IP again
$octet1 = substr($hexagain,0,2);
$octet2 = substr($hexagain,2,2);
$octet3 = substr($hexagain,4,2);
$octet4 = substr($hexagain,6,2);
$dec1 = hex($octet1);
$dec2 = hex($octet2);
$dec3 = hex($octet3);
$dec4 = hex($octet4);
print "IP again is: $dec1.$dec2.$dec3.$dec4\n";

################ Documentation ################

=head1 NAME

ipconverter.pl


=head1 SYNOPSIS

ipconverter.pl x.x.x.x


=head1 DESCRIPTION

Examples for converting IP address between dotted quad, hex, binary and decimal


=head1 AUTHOR

Ed Blanchfield <Ed@E-Things.Org>


=head1 COPYRIGHT AND DISCLAIMER

This program is free software; you can redistribute it and/or
modify it under the terms of the Perl Artistic License or the
GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any
later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

If you do not have a copy of the GNU General Public License write to
the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
MA 02139, USA.

=cut

# End:


