10

When I run nslookup on an IP (These are all examples)

nslookup 192.168.1.123

Current output:

41.31.211.111

Desired output:

111.211.31.41

I have a script that works just seeing if there's a more efficient way or a built-in nslookup command.

2

2 Answers 2

13
echo 411.311.211.111 | awk -F. '{print $4"."$3"." $2"."$1}'

Output:

111.211.311.411

or

echo 411.311.211.111 | awk -F. '{OFS="."; print $4,$3,$2,$1}'
0
3

Here is a native function. Call it like reverseip 12.34.56.78 to have it print 78.56.34.12. Call it like reversed=$(reverseip 12.34.56.78) to capture the output into a variable.

reverseip () {
    local IFS
    IFS=.
    set -- $1
    echo $4.$3.$2.$1
}

set with a string argument tokenizes this string into $1, $2, etc based on the current value of IFS. So we are breaking up the function's input argument $1 into tokens, which now replace the original $1, $2, etc. Because IFS is a dot, the input value in the original $1 gets split up on dots. The dash -- is a safety measure to signal the end of options to set, in case the actual value of $1 would start with a dash (without the -- you would then get an "unknown option" error, or, worse, random or even insecure behavior).

3
  • It would be nice if the set -- $1 had a brief explanation.
    – ychaouche
    Commented Jun 7, 2022 at 15:13
  • 2
    @ychaouche Thanks for the feedback; added an explanation.
    – tripleee
    Commented Jun 8, 2022 at 4:23
  • awesome exaplanation, awesome solution awesome you.
    – ychaouche
    Commented Jun 9, 2022 at 11:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .