Bash script to calculate summarize IP address ranges

眉间皱痕 提交于 2019-12-03 21:44:14

Calculation of common netmask with bash:

#!/bin/bash

D2B=({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})
declare -i c=0                              # set integer attribute

# read and convert IPs to binary
IFS=./ read -r -p "IP 1: " a1 a2 a3 a4     # e.g. 192.168.1.27
b1="${D2B[$a1]}${D2B[$a2]}${D2B[$a3]}${D2B[$a4]}"

IFS=./ read -r -p "IP 2: " a1 a2 a3 a4     # e.g. 192.168.1.129
b2="${D2B[$a1]}${D2B[$a2]}${D2B[$a3]}${D2B[$a4]}"

# find number of same bits ($c) in both IPs from left, use $c as counter
for ((i=0;i<32;i++)); do
  [[ ${b1:$i:1} == "${b2:$i:1}" ]] && c=c+1 || break
done    

# create string with zeros
for ((i=c;i<32;i++)); do
  fill="${fill}0"
done    

# append string with zeros to string with identical bits to fill 32 bit again
new="${b1:0:$c}${fill}"

# convert binary $new to decimal IP with netmask
new="$((2#${new:0:8})).$((2#${new:8:8})).$((2#${new:16:8})).$((2#${new:24:8}))/$c"
echo "$new"

Output:

192.168.1.0/24
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!