没有合适的资源?快使用搜索试试~ 我知道了~
shell实现netmask掩码和cidr掩码位转换1
需积分: 0 0 下载量 101 浏览量
2022-08-03
19:37:09
上传
评论
收藏 73KB PDF 举报
温馨提示
试读
5页
shell实现netmask掩码和cidr掩码位转换1
资源推荐
资源详情
资源评论
shell实现netmask掩码和cidr掩码位转换
Net wo rk IP Net m a s k CIDR
在写⼀个脚本时需要实现掩码位和掩码之间的转换,想简单的通过shell 实现,在openwrt程序上刚好有此脚本,内
容如下:
上⾯的代码看起来⽐较⽞妙,其具体解释可以看下英⽂解释。
mask2cdr()
To get the CIDR prefix from a dot- decimal netmask like this one:
you first have to convert the four octets to binary and then count the most significant bits (i.e. the number of leading
ones):
This function does that rather creatively. First, we strip off all of the leading 255 octets (i.e. the octets that are all
ones in binary) and store the results in variable x:
This step uses parameter expansion, which the entire script relies on pretty heavily. If we continue with our
example netmask of 255.255.192.0, we now have the following values:
#!/bin/bash
# code from www.361way.com
mask2cdr ()
{
# Assumes there's no "255." after a non-255 byte in the mask
local x=${1##*255.}
set -- 0^^^128^192^224^240^248^252^254^ $(( (${#1} - ${#x})*2 )) ${x%%.*}
x=${1%%$3*}
echo $(( $2 + (${#x}/4) ))
}
cdr2mask ()
{
# Number of args to shift, 255..255, first non-255 byte, zeroes
set -- $(( 5 - ($1 / 8) )) 255 255 255 255 $(( (255 << (8 - ($1 % 8))) & 255 )) 0 0
0
[ $1 -gt 1 ] && shift $1 || shift
echo ${1-0}.${2-0}.${3-0}.${4-0}
}
# examples:
mask2cdr 255.255.192.0
cdr2mask 18
255.255.192.0
11111111.11111111.11000000.00000000 # 18 ones = /18 in CIDR
local x=${1##*255.}
$1: 255.255.192.0
$x: 192.0
shell实现netmask掩码和cidr掩码位转换
1/5
资源评论
余青葭
- 粉丝: 37
- 资源: 303
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功