Search code examples
gocidr

golang CIDR prefix notation to IP address/subnet mask (dot-decimal)


Is there something similar to 'npm netmask' in golang ? I need to convert i.e. 10.0.0.0/8 to 10.0.0.0/255.0.0.0 so basically netmask in CIDR format to dot-decimal.

var Netmask = require('netmask').Netmask
var block = new Netmask('10.0.0.0/8');
block.mask; // 255.0.0.0

I can't find it in /golang.org/src/net/ip.go


Solution

  • The go standard library does not have a function to create that representation. That being said, it is not difficult to do yourself:

    https://play.golang.org/p/XT_UXoy6ra

    func main() {
        _, ipv4Net, err := net.ParseCIDR("10.0.0.0/8")
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(ipv4MaskString(ipv4Net.Mask))
    }
    
    func ipv4MaskString(m []byte) string {
        if len(m) != 4 {
            panic("ipv4Mask: len must be 4 bytes")
        }
    
        return fmt.Sprintf("%d.%d.%d.%d", m[0], m[1], m[2], m[3])
    }
    

    Keep in mind this format only works for ipv4 masks. If you were to pass an ipv6 mask, this would panic.