awk

awk: converting subnet mask to prefix


I have a script where I am comparing the actual routing table from "netstat -rn" with the routing table configured in a security vendors own configuration. The problem is that while netstat -rn gives the netmask in format of "255.255.255.0" the command for displaying the routing table within the vendor gives it in the form of /24

I need to find a way to create a function, using only awk, to convert from subnet mask, example 255.255.255.0, to prefix, example: /24

function subnetmaskToPrefix(subnetmask) {
doing magic
}

subnetmask="255.255.255.0"
prefix=subnetmaskToPrefix(subnetmask)

Solution

  • If the prefix number comes from the number of 1's in the subnet mask when converted to binary. example:

    mask 255.255.255.0 is 11111111.11111111.11111111.00000000 in binary. This is 24 1's.

    echo "255.255.255.0" | awk '
    function count1s(N){
        c = 0
        for(i=0; i<8; ++i) if(and(2**i, N)) ++c
        return c
    }
    function subnetmaskToPrefix(subnetmask) {
        split(subnetmask, v, ".")
        return count1s(v[1]) + count1s(v[2]) + count1s(v[3]) + count1s(v[4])
    }
    {
        print("/" subnetmaskToPrefix($1))
    }'
    

    you get,

    /24