I have a file which consist of some class 4 IP address as
172.16.112.50
172.16.112.50
172.16.112.50
172.16.112.100
192.168.1.30
172.16.112.100
172.16.112.50
172.16.112.50
172.16.112.50
i want to store them in pure decimal notations instead of the given dotted decimal formats
e.g. for address
172.16.112.100
the equivalent binary would be
1010 1100. 0001 0000. 0111 0000. 0110 0100
and finally the required decimal number will be a equivalent of above binary representation excluding dots(.)
i.e final binary is
1010 1100 0001 0000 0111 0000 0110 0100
and its decimal equivalent is
2886758500
which should be the output
Thanks in advance
Ygor
2
Try...
$ echo "172.16.112.100"|awk -F '\\.' '{printf "%d\n", ($1 * 2^24) + ($2 * 2^16) + ($3 * 2^8) + $4}'
2886758500
1 Like
You can also calculate the decimal equivalent of an IP4 address using shell bit arithmetic. For example
#!/bin/ksh93
[[ $# != 1 ]] && {
echo "Usage: $0 ipaddress"
exit 1
}
SaveIFS=$IFS
IFS="."
typeset -a IParr=($1)
IFS=$SaveIFS
typeset -i2 ip1=${IParr[0]}
typeset -i2 ip2=${IParr[1]}
typeset -i2 ip3=${IParr[2]}
typeset -i2 ip4=${IParr[3]}
typeset -ui2 d=$(( (ip1 << 24) | (ip2 << 16) | (ip3 << 8) | ip4 ))
print "Inputted IP$ address: $((ip1)).$((ip2)).$((ip3)).$((ip4))"
print " Binary equivalent: $d"
print " Decimal equivalent: $((d))"
$ ./example 172.16.112.100
Inputted IP$ address: 172.16.112.100
Binary equivalent: 2#10101100000100000111000001100100
Decimal equivalent: 2886758500
$
1 Like