How to read an IP address backwards?

Just for curiosity value... using tac from GNU coreutils: given a variable ip in the form 192.168.1.1 then

$(printf %s "$ip." | tac -s.)in-addr.arpa

i.e.

$ ip=192.168.1.1
$ rr=$(printf %s "$ip." | tac -s.)in-addr.arpa
$ echo "$rr"
1.1.168.192.in-addr.arpa

You can do it with AWK. There are nicer ways to do it, but this is the simplest, I think.

echo '192.168.1.1' | awk 'BEGIN{FS="."}{print $4"."$3"."$2"."$1".in-addr.arpa"}'

This will reverse the order of the IP address.

Just to save a few keystrokes, as Mikel suggested, we can further shorten the upper statement:

echo '192.168.1.1' | awk -F . '{print $4"."$3"."$2"."$1".in-addr.arpa"}'

OR

echo '192.168.1.1' | awk -F. '{print $4"."$3"."$2"."$1".in-addr.arpa"}'

OR

echo '192.168.1.1' | awk -F. -vOFS=. '{print $4,$3,$2,$1,"in-addr.arpa"}'

AWK is pretty flexible. :)


If you want to use only shell (zsh, ksh93, bash), here's another way:

IFS=. read w x y z <<<'192.168.1.1'
printf '%d.%d.%d.%d.in-addr.arpa.' "$z" "$y" "$x" "$w"

Or in plain old shell:

echo '192.168.1.1' | { IFS=. read w x y z; echo "$z.$y.$w.$x.in-addr.arpa."; }