tags:

views:

57

answers:

3

Is there is any Command to convert ip address in to binary form?

Eg: 10.110.11.116

output: 00001010.01101110.00001011.01110100

A: 

Here's one way to do it -- no leading zeros on the binary digits however:

IP=192.168.4.254
echo $IP | tr '.' '\n' | while read octet
do
        echo "2 o $octet p" | dc
done | tr '\n' '.'

Or as a single call to dc:

IP=192.168.4.254
echo $IP | tr '.' ' ' | while read octet1 octet2 octet3 octet4
do
        echo "2 o $octet1 p $octet2 p $octet3 p $octet4 p" | dc | tr '\n' '.'
done
Chris J
A: 

Well, here's one (very convoluted) way to do it:

pax> export ip=10.110.11.116

pax> for i in $(echo ${ip} | tr '.' ' '); do echo "obase=2 ; $i" | bc; done
     | awk '{printf ".%08d", $1}' | cut -c2-
00001010.01101110.00001011.01110100

The echo/tr statement gives you a space-separated list of the octets and the for processes these one at a time.

For each one, you pass it through bc with the output base set to 2 (binary). Those four lines of variable length binary numbers then go through awk to force them to a size of 8, put them back on a single line, and precede each with a . and the final cut just removes the first ..

I'm almost certain there are better ways to do this of course but this shows what you can do with a bit of ingenuity and too many decades spent playing with UNIX :-)

paxdiablo
A: 

Here's a way that will work in Bash without any external utilities:

tobin ()
{
    local val bits b c d;
    val=$1;
    bits="";
    (( val < 2 )) && bits=$val;
    b="";
    while (( val > 1 )); do
        bits=$b$bits;
        (( b = val % 2 ));
        (( c = ( val / 2 ) * ( val % 2 ) ));
        (( val = val / 2 ));
        (( d = val ));
    done;
    echo "$d$c$bits"
}

byte () { printf "%08d" $1; }

unset dot binary
saveIFS=$IFS
IFS=.
ip=($1)
IFS=saveIFS
for octet in ${ip[@]}
do
    binary=$binary$dot$(byte $(tobin $octet))
    dot=.
done
echo $binary

For a POSIX compliant Bourne shell:

tobin () {
    local val bits b c d
    val=$1
    bits=""
    if [ $val -lt 2 ]
    then
        bits=$val
    fi
    b=""
    while [ $val -gt 1 ]
    do
        bits=$b$bits
        b=$(($val%2))
        c=$((($val/2)*($val%2)))
        val=$(($val/2))
        d=$val
    done
    echo "$d$c$bits"
}

byte () { printf "%08d" $1; }    # printf may be an external utility in some shells

unset dot binary
saveIFS=$IFS
IFS=.
set -- $a
IFS=$saveIFS

for octet
do
    binary=$binary$dot$(byte $(tobin $octet))
    dot=.
done
echo $binary
Dennis Williamson