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.

# The IP address in this example is simply harcoded.
# In actual use, I read and write this from a file.


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


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