2016-01-29 56 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 :) –