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

后端 未结 6 955
耶瑟儿~
耶瑟儿~ 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 03:41

    Just adding an alternative if you have only network prefix available (no netmask):

    IP=10.20.30.240
    PREFIX=26
    IFS=. read -r i1 i2 i3 i4 <<< $IP
    IFS=. read -r xx m1 m2 m3 m4 <<< $(for a in $(seq 1 32); do if [ $(((a - 1) % 8)) -eq 0 ]; then echo -n .; fi; if [ $a -le $PREFIX ]; then echo -n 1; else echo -n 0; fi; done)
    printf "%d.%d.%d.%d\n" "$((i1 & (2#$m1)))" "$((i2 & (2#$m2)))" "$((i3 & (2#$m3)))" "$((i4 & (2#$m4)))"
    

提交回复
热议问题