shell进行子网掩码(mask)和子网前缀(prefix)之间的转换

由于最近在利用shell编写一套自动化安装OpenStack的脚本,需要利用网络前缀计算子网掩码,因此在此记录一下它们之间的转换代码。

1. prefix---->mask

prefix_to_mask() {
    rpm -q --whatprovides bc >/dev/null 2>&1
    [ $? -ne 0 ] && yum install bc -y >/dev/null 2>&1

    bin_prefix=""
    prefix_cnt1=${1}
    for i in `seq 1 ${prefix_cnt1}`
    do
        bin_prefix="${bin_prefix}1"
    done
    prefix_cnt2=$((32 - ${prefix_cnt1}))
    for i in `seq 1 ${prefix_cnt2}`
    do
        bin_prefix="${bin_prefix}0"
    done

    INTERNAL_mask=""
    for i in `seq 0 8 31`
    do
        val=${bin_prefix:${i}:8}
        tmp_mask=$(echo "obase=10;ibase=2;${val}" | bc)
        if [ "${INTERNAL_mask}" = "" ];then
            INTERNAL_mask="${tmp_mask}"
        else
            INTERNAL_mask="${INTERNAL_mask}.${tmp_mask}"
        fi
    done
}
2. mask---->prefix

mask_to_prefix() {
    rpm -q --whatprovides bc >/dev/null 2>&1
    [ $? -ne 0 ] && yum install bc -y >/dev/null 2>&1

    mask=${1}
    prefix_cnt=0
    prefix=""
    local mask_list=($(echo ${mask} | awk -F. '{print $1,$2,$3,$4}'))
    local mask_cnt=${#mask_list[*]}
    mask_cnt=$((${mask_cnt} - 1))
    for i in `seq 0 ${mask_cnt}`
    do
        tmp=$(echo "obase=2;ibase=10;${mask_list[$i]}" | bc)
        prefix="${prefix}${tmp}"
    done
    prefix_cnt=$(echo ${prefix} | grep -o 1 | wc -l)
}

你可能感兴趣的:(shell,mask,NetWork,prefix)