bashipsubnetnetmask

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


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 &-operator on both addresses. In the example, the result would be 192.168.0.0. Does someone have something like this ready? I'm looking for an elegant way to deal with ip addresses from bash


Solution

  • 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