Public domain
#!/bin/bash
##################################################
# Function : ip to hex convertor
##################################################
ip2hex() {
N4=$(echo $IP | sed -e "s,.*\.,,")
N3=$(echo $IP | sed -e "s,\.${N4}$,," -e "s,.*\.,,")
N2=$(echo $IP | sed -e "s,\.${N3}\.${N4}$,," -e "s,.*\.,,")
N1=$(echo $IP | sed -e "s,\.${N2}\.${N3}\.${N4}$,," -e "s,.*\.,,")
PREFIX=""
BINARY=""
MASK=""
echo $N4 | grep -q "/"
if [ "$?" == "0" ]; then
PREFIX=$(echo $N4 | sed -e 's,.*/,,')
N4=$(echo $N4 | sed -e "s,/$PREFIX,,")
ZERO=$(( 32 - $PREFIX ))
for I in $(seq 1 $PREFIX); do
BINARY="${BINARY}1"
done
for I in $(seq 1 $ZERO); do
BINARY="${BINARY}0"
done
MASK=$(echo "obase=16; ibase=2; $BINARY" | bc | tr '[:upper:]' '[:lower:]')
fi
HEXIP=$(printf "%02x%02x%02x%02x" ${N1} ${N2} ${N3} ${N4})
if [ "${MASK}" != "" ]; then
HEXIP="$HEXIP/$MASK"
fi
echo Debug : ${IP} ${N1} ${N2} ${N3} ${N4}
echo Debug : PREFIX=$PREFIX BINARY=$BINARY MASK=$MASK
}
##################################################
# Single IP
##################################################
IP=192.168.1.1
ip2hex
echo $HEXIP
##################################################
# Subnet
##################################################
echo
IP=10.20.30.10/28
ip2hex
echo $HEXIP
# Pejman Moghadam
# Sat Dec 25 09:42:42 IRST 2010
BY: Pejman Moghadam
TAG: sed, bc, bash-script, bash
DATE: 2010-12-25 09:42:42