Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1492261
  • 博文数量: 263
  • 博客积分: 10851
  • 博客等级: 上将
  • 技术积分: 2627
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-26 22:40
文章分类

全部博文(263)

文章存档

2013年(4)

2012年(25)

2011年(33)

2010年(50)

2009年(138)

2008年(13)

分类: LINUX

2009-11-18 16:31:51

工作需要, 在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) |
0

上一篇:awk中使用位运算

下一篇:oom killer

给主人留下些什么吧!~~