nmask 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/bin/sh
  2. # Convert netmask in dot notation to CIDR
  3. mask2cidr() {
  4. nbits=0
  5. IFS=.
  6. for dec in $1 ; do
  7. case $dec in
  8. 255) nbits=$(expr $nbits + 8);;
  9. 254) nbits=$(expr $nbits + 7);;
  10. 252) nbits=$(expr $nbits + 6);;
  11. 248) nbits=$(expr $nbits + 5);;
  12. 240) nbits=$(expr $nbits + 4);;
  13. 224) nbits=$(expr $nbits + 3);;
  14. 192) nbits=$(expr $nbits + 2);;
  15. 128) nbits=$(expr $nbits + 1);;
  16. 0);;
  17. *) return 1;;
  18. esac
  19. done
  20. echo "$nbits"
  21. return 0
  22. }
  23. #cidr2mask() {
  24. # local i mask=""
  25. # local full_octets=$(($1/8))
  26. # local partial_octet=$(($1%8))
  27. #
  28. # for ((i=0;i<4;i+=1)); do
  29. # if [ $i -lt $full_octets ]; then
  30. # mask+=255
  31. # elif [ $i -eq $full_octets ]; then
  32. # mask+=$((256 - 2**(8-$partial_octet)))
  33. # else
  34. # mask+=0
  35. # fi
  36. # test $i -lt 3 && mask+=.
  37. # done
  38. #
  39. # echo $mask
  40. #}
  41. ## main ##
  42. if [ $# -lt 2 ]; then
  43. return 1
  44. fi
  45. # if dot notation
  46. if [ "$1" = "-d" ]; then
  47. mask=$2
  48. numbits=$(mask2cidr $mask)
  49. if [ "x$numbits" != "x" ]; then
  50. echo "$numbits"
  51. fi
  52. exit 0
  53. elif [ "$1" = "-c" ]; then
  54. echo "Under construction"
  55. fi