2016-01-29 51 views
0

我需要编写一个bash脚本,当我输入两个ip地址时,它会为它们计算summerize地址。bash脚本来计算汇总ip地址

Examlpe:

192.168.1.27/25 
192.168.1.129/25 

结果将是:

192.168.1.0/24 

你能帮我这个剧本?

我知道你会对我说什么你试试。

我试图在Google中找到某些东西,但是我发现我必须将其转换为二进制,然后计算出来,这将非常困难。

我甚至不知道如何开始使用它:)

任何想法或暗示吗?

感谢,
阿拉

+3

什么是你想在这里究竟做什么?找到包含给定IP地址的最小网络? –

+0

如果我有很多子网,请尝试总结它们(最常见的地址) – Miron

+1

https://www.youtube.com/watch?v=8TFV2VycauM – Miron

回答

6

常见的网络掩码的计算使用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 m # e.g. 192.168.1.27/25 
b1="${D2B[$a1]}${D2B[$a2]}${D2B[$a3]}${D2B[$a4]}" 

IFS=./ read -r -p "IP 2: " a1 a2 a3 a4 m # e.g. 192.168.1.129/25 
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" 

输出:

 
192.168.1.0/24 
+1

这是一些严重的bash-fu :) –