设定两个网段:net1是192.168.10.0/24,net2是192.168.10.128/25。使用Shell脚本,判断是net1包含net2还是net2包含net1. 解题思路:
将两个网段全部转换为二进制,且不带字段分隔符(即点号),取网络位。如果在net1的二进制字符串里面截取到了net2的二进制字符串,则net2包含net1.
#!/bin/bash
net1="192.168.10.0/24"
net2="192.168.10.128/25"
netID1D="`echo $net1 | cut -d "/" -f 1`"
netID2D="`echo $net2 | cut -d "/" -f 1`"
mask1="`echo $net1 | cut -d "/" -f 2`"
mask2="`echo $net2 | cut -d "/" -f 2`"
array1D[0]="`echo $netID1D | awk -v FS="." ‘{print $1}‘`"
array1D[1]="`echo $netID1D | awk -v FS="." ‘{print $2}‘`"
array1D[2]="`echo $netID1D | awk -v FS="." ‘{print $3}‘`"
array1D[3]="`echo $netID1D | awk -v FS="." ‘{print $4}‘`"
array2D[0]="`echo $netID2D | awk -v FS="." ‘{print $1}‘`"
array2D[1]="`echo $netID2D | awk -v FS="." ‘{print $2}‘`"
array2D[2]="`echo $netID2D | awk -v FS="." ‘{print $3}‘`"
array2D[3]="`echo $netID2D | awk -v FS="." ‘{print $4}‘`"
array1B[0]="`echo "obase=2;${array1D[0]}" | bc`"
array1B[1]="`echo "obase=2;${array1D[1]}" | bc`"
array1B[2]="`echo "obase=2;${array1D[2]}" | bc`"
array1B[3]="`echo "obase=2;${array1D[3]}" | bc`"
array2B[0]="`echo "obase=2;${array2D[0]}" | bc`"
array2B[1]="`echo "obase=2;${array2D[1]}" | bc`"
array2B[2]="`echo "obase=2;${array2D[2]}" | bc`"
array2B[3]="`echo "obase=2;${array2D[3]}" | bc`"
zeroArray=(0 0 00 000 0000 00000 000000 0000000)
for ((i=0;i<${#array1B[$i]};i++))
do
zeroNum=$((8 - ${#array1B[$i]}))
if [ $zeroNum -gt 0 ]
then
testStr="`awk -v zero="${zeroArray[$zeroNum]}" -v rawStr="${array1B[$i]}" ‘BEGIN {printf "%s%s",zero,rawStr}‘`"
array1B[$i]=$testStr
fi
done
for ((i=0;i<${#array2B[$i]};i++))
do
zeroNum=$((8 - ${#array2B[$i]}))
if [ $zeroNum -gt 0 ]
then
testStr="`awk -v zero="${zeroArray[$zeroNum]}" -v rawStr="${array2B[$i]}" ‘BEGIN {printf "%s%s",zero,rawStr}‘`"
array2B[$i]=$testStr
fi
done
netID1B=${array1B[0]}${array1B[1]}${array1B[2]}${array1B[3]}
netID2B=${array2B[0]}${array2B[1]}${array2B[2]}${array2B[3]}
netID1BNo0="`awk -v inNet="$netID1B" -v inMask="$mask1" ‘BEGIN {print substr(inNet,1,inMask)}‘`"
netID2BNo0="`awk -v inNet="$netID2B" -v inMask="$mask2" ‘BEGIN {print substr(inNet,1,inMask)}‘`"
echo -e "net1十进制为:$net1\tnet1二进制为:$netID1BNo0"
echo -e "net2十进制为:$net2\tnet2二进制位:$netID2BNo0"
netVS1="`awk -v inNet1="$netID1BNo0" -v inNet2="$netID2BNo0" ‘BEGIN {print index(inNet1,inNet2)}‘`"
netVS2="`awk -v inNet2="$netID1BNo0" -v inNet1="$netID2BNo0" ‘BEGIN {print index(inNet1,inNet2)}‘`"
if [ $netVS1 -ne 0 ]
then
echo "计算结果:$net2 包含 $net1"
fi
if [ $netVS2 -ne 0 ]
then
echo "计算结果:$net1 包含 $net2"
fi
运行结果
[[email protected] ~]# sh netCal.sh
net1十进制为:192.168.10.0/24 net1二进制为:110000001010100000001010
net2十进制为:192.168.10.128/25 net2二进制位:1100000010101000000010101
计算结果:192.168.10.0/24 包含 192.168.10.128/25
原文地址:http://blog.51cto.com/qinlouke/2327303
时间: 2024-10-16 19:44:48