Ip to hex

From AN!Wiki
Jump to: navigation, 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.

# 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\n\n";


Any questions, feedback, advice, complaints or meanderings are welcome.
Us: Alteeve's Niche! Support: Mailing List IRC: #clusterlabs on Freenode   © Alteeve's Niche! Inc. 1997-2019
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.
Personal tools