Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script for converting IP Addr string to Hexadecimal format

Tags:

bash

IP_ADDR=192.168.1.128

printf '%02X' ${IP_ADDR//./ }; echo

Can some one explain how this simple oneliner converts IP_ADDR to hexadecimal format? I am banging my head trying to find some documentation about this behavior.

like image 806
Santhosh Avatar asked May 27 '11 07:05

Santhosh


2 Answers

Shell Parameter Expansion

$ IP_ADDR=192.168.1.128
$ echo ${IP_ADDR//./ }
192 168 1 128
$ printf '%02X' 192 168 1 128 ; echo
C0A80180
like image 145
Ignacio Vazquez-Abrams Avatar answered Nov 15 '22 21:11

Ignacio Vazquez-Abrams


You can simply use gethostip (from syslinux-utils on Debian/Ubuntu):

$ gethostip -x 192.168.1.128
C0A80180
like image 41
Benjamin Drung Avatar answered Nov 15 '22 21:11

Benjamin Drung