Question

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).

Was it helpful?

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

OTHER TIPS

This is straightforward using the IPAddress Go library for either IPv4 or IPv6. Disclaimer: I am the project manager.

import (
    "fmt"
    "github.com/seancfoley/ipaddress-go/ipaddr"
)

func main() {
    maskStr := "255.255.255.0"
    pref := ipaddr.NewIPAddressString(maskStr).GetAddress().
        GetBlockMaskPrefixLen(true)
    fmt.Printf("prefix length for %s is %d", maskStr, pref.Len())
}

Output:

prefix length for 255.255.255.0 is 24
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top