工作需要, 在cu上搜到的一个解法, “网中人”写的, 很牛:
#!/bin/bash
#ip=$(cat "$@" | awk 'BEGIN{ FS="/" }{ print $1 }')
kk=$(cat "$@")
all=(${kk//[!0-9]/ })
[ "${#all[@]}" != "8" ] && {
echo "Usage: "
echo "${0##*/} ip.ip.ip.ip/mask.mask.mask.mask"
exit 1
}
get_addr () {
if [ "$1" = "-b" ]; then
op='|'; op1='^'; arg='255'
shift
else
op='&'
fi
unset address
while [ "$5" ]; do
num=$(( $1 $op ($5 $op1 $arg) )) # 广播地址的算法: 掩码先按位取反, 然后跟ip做位或操作, 这里跟位1作异或操作跟位反操作等价
shift
address="$address.$num"
done
}
get_addr ${all[@]}
network="${address#.}"
get_addr -b ${all[@]}
broadcast="${address#.}"
echo "$network $broadcast"
这个是awk版的:
##!/bin/bash
# G_network () {
# echo $@ | awk 'BEGIN{FS="[./]";OFS="."}
# END{
# print and($1,$5),and($2,$6),and($3,$7),and($4,$8)
# }'
# }
#
# G_broadcast () {
# echo $@ | awk 'BEGIN{FS="[./]";OFS="."}
# END{
# print or($1,xor($5,255)),or($2,xor($6,255)),or($3,xor($7,255)),or($4,xor($8,255))
# }'
# }
#
# ###
# # main
# ###
# ALL_IP=192.168.23.32/255.255.252.0
# G_network $ALL_IP
# G_broadcast $ALL_IP
原文地址:
阅读(1204) | 评论(0) | 转发(0) |