Given IP address and Netmask, how can I calculate the subnet range using bash?

前端 未结 4 2031
南旧
南旧 2021-01-07 05:12

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

4条回答
  •  独厮守ぢ
    2021-01-07 05:47

    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...)

    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'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.

    (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.)

提交回复
热议问题