Bash脚本来计算汇总IP地址范围 [英] Bash script to calculate summarize IP address ranges

查看:87
本文介绍了Bash脚本来计算汇总IP地址范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个bash脚本,当我输入两个IP地址时,它将为它们计算汇总地址.

I need to write a bash script that when I enter two ip addresses, it will calculate summarize address for them.

Examlpe:

192.168.1.27/25
192.168.1.129/25  

结果将是:

192.168.1.0/24  

您能帮我这个脚本吗?

Can you help me with this script?

我知道您会对我说:您尝试了什么?"

I know you will say to me "What did you try?"

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

I tried to find something in Google, but what I found that I must to convert to binary then calculate it, and it will be very hard.

我什至不知道如何开始.

I even don’t know how to start with it.

有什么想法或提示吗?

推荐答案

使用bash计算常见网络掩码:

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"

输出:


192.168.1.0/24

这篇关于Bash脚本来计算汇总IP地址范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆