inet_ntoa and inet_aton in pure bash
Do not ask me why, but today I needed a pure implementation of the
C-functions inet_aton and inet_ntoa. It’s really not a big deal,
but I always have to look up how splitting a string works in bash,
and Eris, I so hate the bash manual page, so I cheated and found
How do I split a string on a delimiter in
Bash?
at Stack Overflow.
Never mind, here my code.
function inet_aton () {
IN=$1
arrIN=(${IN//./ })
out=$((${arrIN[0]} << 24))
out=$(($out ^ ${arrIN[1]} << 16))
out=$(($out ^ ${arrIN[2]} << 8))
out=$(($out ^ ${arrIN[3]}))
echo $out
}
function inet_ntoa () {
IN=$1
a=$((IN >> 24 & 0xFF))
b=$((IN >> 16 & 0xFF))
c=$((IN >> 8 & 0xFF))
d=$((IN & 0xFF))
echo ${a}.${b}.${c}.${d}
}
Simple test:
$ inet_aton 192.168.2.1
3232236033
$ inet_ntoa 3232236033
192.168.2.1
Check inet_aton against the Python implementation:
In [1]: import socket
In [2]: int.from_bytes(socket.inet_aton("192.168.2.1"))
Out[2]: 3232236033
Have fun.