#!/bin/bash #History: # 2012-02-20 DanielW|Kernel First release # PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin export PATH #二进制转十进制 function multiply_2(){ declare -i n n=$1 multiply_result=1 while [ $n -gt 0 ] do multiply_result=$(( $multiply_result*2 )) n=$n-1 done export multiply_result } ##十进制转二进制,得出ip和mask的某一段的二进制 function cal(){ declare -i a declare -i b declare -i len a=$1 b=$2 m="" n="" m=$(( a%2 )) while [ $(( a/2 )) -gt 0 ] do a=$(( a/2 )) m=$((a%2))$m done len=8-$( expr length $m ) while [ $len -gt 0 ] do m=0$m len=$(( len-1 )) done n=$(( b%2 )) while [ $(( b/2 )) -gt 0 ] do b=$(( b/2 )) n=$((b%2))$n done len=8-$(expr length $n) while [ $len -gt 0 ] do n=0$n len=$(( len-1 )) done export m export n } #做与运算,并输出十进制 function ip_and_mask(){ declare -i int ten="" ip="0" int=8 a="" b="" result="" while [ $int -gt 0 ] do a=$( expr substr $1 $int 1 ) b=$( expr substr $2 $int 1 ) if [ "$a" == "1" -a "$b" == "1" ];then result=1${result} else result=0${result} fi int=$int-1 done if [ "$( expr substr $result 8 1 )" == "1" ];then ip=1 else ip=0 fi int=7 while [ $int -ge 0 ] do if [ "$( expr substr $result $int 1 )" == "1" ];then tmp_n=$(( 8-int )) ip=$(( ip+$( multiply_2 $tmp_n ) )) fi int=$int-1 done export ip } read -p "Enter the IP Address:" ip_input read -p "Enter the NETMASK Address:" mask declare -i M1=$( echo $mask | awk 'BEGIN{FS="."}{print $1}' ) declare -i M2=$( echo $mask | awk 'BEGIN{FS="."}{print $2}' ) declare -i M3=$( echo $mask | awk 'BEGIN{FS="."}{print $3}' ) declare -i M4=$( echo $mask | awk 'BEGIN{FS="."}{print $4}' ) declare -i P1=$( echo $ip_input | awk 'BEGIN{FS="."}{print $1}' ) declare -i P2=$( echo $ip_input | awk 'BEGIN{FS="."}{print $2}' ) declare -i P3=$( echo $ip_input | awk 'BEGIN{FS="."}{print $3}' ) declare -i P4=$( echo $ip_input | awk 'BEGIN{FS="."}{print $4}' ) if [ $M1 -ne 255 ];then cal $M1 $P1 ip_and_mask $m $n echo -e "Net Address:"$ip.0.0.0 elif [ $M2 -ne 255 ];then cal $M2 $P2 ip_and_mask $m $n echo "Net Address:"$P1.$ip.0.0 elif [ $M3 -ne 255 ];then cal $M3 $P3 ip_and_mask $m $n echo "Net Address:"$P1.$P2.$ip.0 else [ $M4 -ne 255 ] cal $M4 $P4 ip_and_mask $m $n echo "Net Address:"$P1.$P2.$P3.$ip fi echo "END"
这个版本还没有对输入的数据进行判断,而且没有使用位运算(原来不会啊),导致了代码过长过复杂,等待下个版本更新。