Search code examples
goip-address

Golang: Number of bits of an IP mask


In Go, how do I get the number of bits of an IP mask like this: 10.100.20.0 255.255.255.0 => 24 bits maks.

It would be helpful to check if a mask is lower or greater than a certain number of bits (like if one wants to block all adresses greater than /24).


Solution

  • The net package has functions for getting the prefix size of a mask, the value used in CIDR notation. The specific function for the bits is:

    func (m IPMask) Size() (ones, bits int)

    To get the bits, see the following example:

    package main
    
    import (
        "fmt"
        "net"
    )
    
    func main() {
        mask := net.IPMask(net.ParseIP("255.255.255.0").To4()) // If you have the mask as a string
        //mask := net.IPv4Mask(255,255,255,0) // If you have the mask as 4 integer values
    
        prefixSize, _ := mask.Size()
        fmt.Println(prefixSize)
    }
    

    Output:

    24

    Playground

    Ps.

    I assume you mean the bitmask 255.255.255.0