Wednesday, September 01, 2010

Converting an Integer to an IPv4 IP Address in Bash Using Bitwise Operations

I needed a script to automate the generation of statically assigned IP addresses, but I could not find any good example. It's a simple algorithm, so I decided I'd just write it up myself, but then I discovered that I could not find a good example of using bitwise operators in Bash. I found many pages where the operators are listed, but there is always the mention that they really aren't used in scripts all that often. Well, thanks for that, but how about one example of how to use them?

I came up with the following code, though I'm not sure if the $(( )) constructs are really necessary, but I simply could not make things work without them. Please let me know if you know a simpler syntax.

#!/bin/sh
#
# The IP address in this example is simply harcoded.
# In actual use, I read and write this from a file.
#
# 192.168.1.100
ipint=3232235876

MASKA=0xFF000000
MASKB=0x00FF0000
MASKC=0x0000FF00
MASKD=0x000000FF

a=$(( ($ipint & $MASKA) >> 24 ))
b=$(( ($ipint & $MASKB) >> 16 ))
c=$(( ($ipint & $MASKC) >> 8 ))
d=$(( $ipint & $MASKD ))

ipstr="$a.$b.$c.$d"

echo "The IP Address is ${ipaddr}."

No comments:

Post a Comment