<<< Back to the Linux Tips Index

11th October 2016

Convert IP Address to Hexadecimal

PXE Boot is a great way to install clients over the network. They get their IP address by DHCP, which also sends them extra information - specifically, the IP address of a boot server, and the name of a file to request from the boot server.

Typically, they will be instructed to download pxelinux.0, which will be passed to the CPU, and result in the client requesting a further file, either the BIOS UUID, or if that fails, then the client MAC address, or if that fails, then the client IP address (which it retries with ever-reducing accuracy: 192.168.1.47, then 192.168.1, then 192.168, then 192). However, it asks for these in hexidecimal format, which is a bit of a pain if you don't happen to be 100% fluent in all hex values between 0-255.

Hex Calculator

The conversion looks like this:

Decimal IP Address192168147
Hexadecimal FilenameC0A8012F

So you need to provide files in the /var/lib/tftpboot/pxelinux.cfg/ directory, with names like C0A8012F.

http://www.syslinux.org/wiki/index.php?title=PXELINUX explains the full process.

It's possible to sit down with a Hex Calculator (there are many online, mobile apps, etc), and work out each one. However, this little function will do it for you:

#!/bin/bash
printf '%02X' ${1//./ }

You can convert this into a function, and use the information in any way you like:

convert_ip_to_hex.sh
#!/bin/bash

[ "$#" -eq "1" ] && echo "You asked for $1 which is `ip_to_hex $1`"

IP1=`ip_to_hex 192.168.1.47`
echo "IP1 is $IP1, from 192.168.1.47"

echo "I am about to convert 10.97.2.31 into hex:"
ip_to_hex 10.97.2.31

IP_ADDRESS=172.17.3.193
echo "$IP_ADDRESS = `ip_to_hex $IP_ADDRESS`"

When you run this script, it will display this output:

$ ./convert_ip_to_hex.sh
IP1 is C0A8012F, from 192.168.1.47
I am about to convert 10.97.2.31 into hex:
0A61021F
172.17.3.193 = AC1103C1

If you run it with an IP address as an argument, such as "./convert_ip_to_hex.sh 172.17.231.96", it will display that, too:

$ ./convert_ip_to_hex.sh 172.17.231.96
You asked for 172.17.231.96 which is AC11E760
IP1 is C0A8012F, from 192.168.1.47
I am about to convert 10.97.2.31 into hex:
0A61021F
172.17.3.193 = AC1103C1

OG Image credit: https://locus-engineering.com/product-portfolio/e2090-64-bit-hexadecimal20-digit-calculator/

 

Invest in your career. Buy my Shell Scripting Tutorial today:

 

Steve Parker - Linux / DevOps Consultant
Share on Twitter Share on Facebook Share on LinkedIn Share on Identi.ca Share on StumbleUpon
Join the Facebook page for more tips and tricks:
Linux UK

Promote your Page too