A few things, mostly technical notes...

Tuesday, July 07, 2015

dotted quad to decimal and back, in bash




bash snippet to convert IP address to decimal:

$ cat ip2d.sh
#!/bin/bash

IFS=.
set -- $*
echo $(( ($1*256**3) + ($2*256**2) + ($3*256) + ($4) ))


Conversely, to convert from decimal to dotted quad address:



$ cat d2ip.sh
#!/bin/bash

IFS=" " read -r a b c d  <<< $(echo  "obase=256 ; $1" |bc)
echo ${a#0}.${b#0}.${c#0}.${d#0}

Here they are in action:

google.com has address 216.58.216.142
$ ./ip2d.sh 216.58.216.142
3627735182
$ ./d2ip.sh 3627735182
216.58.216.142

No comments:

Followers


Creative Commons License
This work is licensed under a Creative Commons License.