这是一篇旧时习作,Shell脚本练得多了,想练练移位计算,就有了下面的脚本。


#!/bin/bash
IPPattern="(\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>\.){3}\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>"
maskPattern="[1-9]|[12][0-9]|3[01]"

while :
do
  echo -e -n "Please input a legal IP address [such as 192.168.1.1/16]: "
  read userInput
  
  IPMask=`echo $userInput | egrep "$IPPattern/$maskPattern"`  
  #Such as 192.168.1.1/24
  if [ -z "$IPMask" ] ;then
    echo "Please input the right format. [such as 192.168.1.1/1-31] "
    continue
  fi
  
  IPAddr=`echo $IPMask | cut -d/ -f1`
  IPType[1]=`echo $IPAddr | cut -d. -f1`
  IPType[2]=`echo $IPAddr | cut -d. -f2`
  IPType[3]=`echo $IPAddr | cut -d. -f3`
  IPType[4]=`echo $IPAddr | cut -d. -f4`
  mask=`echo $IPMask | cut -d/ -f2`
  echo "IP address is ${IPType[1]}*${IPType[2]}*${IPType[3]}*${IPType[4]} , Mask is $mask ."
  
  ((IPHex[1]=IPType[1]<<24))
  ((IPHex[2]=IPType[2]<<16))
  ((IPHex[3]=IPType[3]<<8))
  ((IPHex[4]=IPType[4]))
  
  #192 c0 ; 1 1 1
  ((iph=${IPHex[1]}+${IPHex[2]}+${IPHex[3]}+${IPHex[4]}))
  #echo $iph
  #0xffffffff
  #declare -i strMask1=4294967295
  declare -i strMask1=0xffffffff
  #echo $strMask1
  ((strMask1=strMask1<<(32-mask) & 0xffffffff))
  #echo $strMask1
  ((strMask2=~strMask1))
  #echo $strMask2
  ((networkAddr=iph & strMask1))
  ((bcastAddr= (iph | strMask2) &  0xffffffff))
  #echo $networkAddr | awk '{printf "%x\n",$0}'
  #echo $bcastAddr | awk '{printf "%x\n",$0}'
  
  
  ((IPHex[1]=networkAddr>>24 & 0x000000ff))
  ((IPHex[2]=networkAddr>>16 & 0x000000ff))
  ((IPHex[3]=networkAddr>>8 & 0x000000ff))
  ((IPHex[4]=networkAddr & 0x000000ff))
  echo -e "Network Address   : ${IPHex[1]}.${IPHex[2]}.${IPHex[3]}.${IPHex[4]}"
  
  ((IPHex[1]=bcastAddr>>24 & 0x000000ff))
  ((IPHex[2]=bcastAddr>>16 & 0x000000ff))
  ((IPHex[3]=bcastAddr>>8 & 0x000000ff))
  ((IPHex[4]=bcastAddr & 0x000000ff))
  echo -e "Broadcast Address : ${IPHex[1]}.${IPHex[2]}.${IPHex[3]}.${IPHex[4]}"
done