Given the IP and netmask, how can I calculate the network address using bash?

后端 未结 6 945
耶瑟儿~
耶瑟儿~ 2020-12-24 03:20

In a bash script I have an IP address like 192.168.1.15 and a netmask like 255.255.0.0. I now want to calculate the start address of this network, that means using the &

6条回答
  •  孤独总比滥情好
    2020-12-24 04:07

    Use bitwise & (AND) operator:

    $ 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
    

    Example with another IP and mask:

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

提交回复
热议问题