给定IP地址和网络掩码,如何使用bash计算子网范围? [英] Given IP address and Netmask, how can I calculate the subnet range using bash?

查看:230
本文介绍了给定IP地址和网络掩码,如何使用bash计算子网范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash脚本中,我有一个像140.179.220.200这样的IP地址和一个像255.255.224.0这样的网络掩码。我现在想要计算网络地址(140.179.192.000),第一个可用的主机IP(140.179.192.1),最后一个可用的主机IP(140.179.220.254)和广播地址(140.179.223.255)。我能够找到一个干净的方式来做下面的网络地址。我可以手动进行子网计算,但主要是难以将其转换为bash脚本。提前致谢

In a bash script I have an IP address like 140.179.220.200 and a netmask like 255.255.224.0. I now want to calculate the Network address(140.179.192.000), first usable Host IP(140.179.192.1), last usable Host IP(140.179.220.254), and the Broadcast Address(140.179.223.255). I was able to find a clean way to do the network address below. I'm able to do subnet calculations by hand, but mainly having difficulties translating that into a bash script. Thanks in advance

$ IFS=. read -r i1 i2 i3 i4 <<< "192.168.1.15"
$ IFS=. read -r m1 m2 m3 m4 <<< "255.255.0.0"
$ printf "%d.%d.%d.%d\n" "$((i1 & m1))" "$((i2 & m2))" "$((i3 & m3))" "$((i4 & m4))"
192.168.0.0


推荐答案

嗯,你已经有了网络地址。第一个主机地址只比网络地址高一个,这很容易计算,因为你知道低阶位是零(所以没有溢出到高字节......)

Well, you already have the network address. The first host address is just one higher than the network address, which is easy to calculate since you know the low-order bits are zeroes (so there's no overflow to high bytes...)

然后是广播地址。这只是所有主机地址位都设置为1的地址。这些是子网掩码为零的位。因此,要获取广播地址,请反转掩码并按位执行。最后一个主机地址只有一个。

Then the broadcast address. That's just the address where all the host address bits are set to ones. Those are the bits where the subnet mask is zero. So, to get the broadcast address, invert the mask and do a bitwise or. The last host address is just one less from that.

Bash的算术支持与C和大多数其他语言相同的按位运算符,因此& 对于 | 对于 ^ 用于xor,用于否定。从你已经拥有的,你应该能够产生缺失的。

Bash's arithmetic supports the same bitwise operators as C and most other languages, so & for and, | for or, ^ for xor and ~ for negation. From what you already have, you should be able to produce the missing ones.

(是的,使用shell执行此操作看起来有点icky,但如果您要手动实施计算,那么在任何情况下它都会完全相同编程语言。)

(And yes, doing that with the shell seems a bit icky, but if you're going to implement the calculation manually it's going to be pretty much the same in any programming language.)

这篇关于给定IP地址和网络掩码,如何使用bash计算子网范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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