Ip to hex

From Alteeve Wiki
Jump to navigation Jump to search

 AN!Wiki :: How To :: Ip to hex

This script takes an IPv4 address and converts it to a hexadecimal string suitable for use with PXE server configuration file names.

Download the perl source: ip_to_hex.

#!/usr/bin/perl
# Author:  Digimer; digimer@alteeve.ca
# Date:    Jun. 21, 2010
# License: GPLv2

# Be clean
use strict;
use warnings;

# Read the IP address
my $ip=$ARGV[0];

# Sanity-check it.
usage() if not $ip;
my ($a, $b, $c, $d)=($ip=~/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/);
usage() if ((not defined $a) || (not defined $b) || (not defined $c) || (not defined $d));

# Convert and print
print $ip." = ".convert($a).convert($b).convert($c).convert($d), "\n";

exit (0);

sub convert
{
        my ($dec)=@_;

        # Convert the decimal to hexadecimal and pad the result with a leading
        # zero if needed.
        my $hex = sprintf("%x", $dec);
        $hex=length($hex) == 1 ? "0".$hex : $hex;

        # Return the upercase result.
        return (uc($hex));
}

# Useful death.
sub usage
{
        print "\nPlease pass in the IP address as the only argument.\n";
        print "Do not pass the netmask. Example:\n";
        print "\n\t./ip_to_hex 192.168.1.100\n\n";
        exit(1);
}

 

Any questions, feedback, advice, complaints or meanderings are welcome.
Alteeve's Niche! Enterprise Support:
Alteeve Support
Community Support
© Alteeve's Niche! Inc. 1997-2024   Anvil! "Intelligent Availability®" Platform
legal stuff: All info is provided "As-Is". Do not use anything here unless you are willing and able to take responsibility for your own actions.