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

后端 未结 6 919
耶瑟儿~
耶瑟儿~ 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

    In addition to @Janci answer

    IP=10.20.30.240
    PREFIX=26
    IFS=. read -r i1 i2 i3 i4 <<< $IP
    D2B=({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})
    binIP=${D2B[$i1]}${D2B[$i2]}${D2B[$i3]}${D2B[$i4]}
    binIP0=${binIP::$PREFIX}$(printf '0%.0s' $(seq 1 $((32-$PREFIX))))
    # binIP1=${binIP::$PREFIX}$(printf '0%.0s' $(seq 1 $((31-$PREFIX))))1
    echo $((2#${binIP0::8})).$((2#${binIP0:8:8})).$((2#${binIP0:16:8})).$((2#${binIP0:24:8}))
    

提交回复
热议问题