Saturday, November 15, 2008

Netmask in decimal form

In Solaris, the ifconfig <interface> gives you hex format for netmask. What if you want to conver that "ffff0000" to "255.255.0.0", you will need some utility to do this. Below shell function is able to solve your problem:
$ netmask_h2d()
{
set -- `echo $1 | sed -e 's/\([0-9a-fA-F][0-9a-fA-F]\)/\1\ /g'`
perl -e '$,=".";print 0x'$1',0x'$2',0x'$3',0x'$4
}

$ netmask_h2d ffff0000
255.255.0.0
Although Perl has been in Solaris since version 8, we may want to use more primitive unix utility to do the job. "bc" (arbitrary precision arithmetic language) can work with any input base and output base. The default is base 10. By setting ibase=16, any input will be treated as base 16. Note that "bc" only take upper case [A-F]. Here is a function to convert Hex to Dec, also it auto convert to uppercase.
$ h2d()
{
(echo ibase=16; echo $1 | tr '[a-z]' '[A-Z]') | bc
}
So we can have a more "portable" version of netmask_h2d without having to reply on Perl.
$ netmask_h2d()
{
set -- `echo $1 | sed -e 's/\([0-9a-fA-F][0-9a-fA-F]\)/\1\ /g'`
echo "`h2d $1`.`h2d $2`.`h2d $3`.`h2d $4`"
}

$ netmask_h2d ffff0000
255.255.0.0

Labels: ,

0 Comments:

Post a Comment

<< Home