inet_ntoa and inet_aton in pure bash
Publishing date: 2025-09-14 08:45:00+0200
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?" [1]
at Stack Overflow.
Never mind, here my code.
```bash
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:
```
alex@zbox:~$ inet_aton 192.168.2.1
3232236033
alex@zbox:~$ 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.
HTML [1] How do I split a string on a delimiter in Bash?
___________________________________________________________________
Gophered by Gophernicus/3.1.1 on Raspbian/12 armv7l