linux脚本获取广播地址,Shell脚本之IP网络地址和广播地址计算

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

#!/bin/bash

IPPattern="(\\.){3}\"

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<

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值