Convert a Hex Address to an IP Address

Recently I have been using a proprietary application which stores IP address in a hex notation. Unfortunately this hex address is far from useful when doing troubleshooting or diagnosing. Originally I was told to pull each two hex digits and convert them via the calculator of my operating system. This was very manual and annoying to say the least. I decided to write a short script with the limited tools available on the machine I had to use for this purpose. While I am sure there would be a more elegant way of doing this, it gets the job done.

The script first converts the hex address to all upper-case (using 'tr' tool), as the 'bc' tool didn't like lowercase letters. The script next calculates each octet of the IP address, much like the manual method I was doing before. Finally, the script does some diagnostic tests (whois and nslookup) against the resulting IP address, which are useful for further research.


#!/bin/sh
#
# Convert hex to be uppercase for bc to accept it.
#
IN=`echo $1 | tr "[:lower:]" "[:upper:]" `
#
# Begin converting each octet
#
IN1=`echo $IN| sed 's/^\(..\).*/ibase=16;\1/'|bc`
IN2=`echo $IN| sed 's/^..\(..\).*/ibase=16;\1/'|bc`
IN3=`echo $IN| sed 's/^....\(..\).*/ibase=16;\1/'|bc`
IN4=`echo $IN| sed 's/^......\(..\)/ibase=16;\1/'|bc`
#
# Begin gathering info on the resulting IP.
#
whois "$IN1.$IN2.$IN3.$IN4"
echo "IP Address = $IN1.$IN2.$IN3.$IN4"
nslookup "$IN1.$IN2.$IN3.$IN4" 4.2.2.1

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.