Go - Golang Number of bits of an IP mask

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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

Answers

http://en.wikipedia.org/wiki/CIDR_notation#CIDR_notation http://en.wikipedia.org/wiki/CIDR_notation#CIDR_notation

http://golang.org/pkg/net/#IPMask.Size http://golang.org/pkg/net/#IPMask.Size

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

http://play.golang.org/p/twUUxzJ7FX http://play.golang.org/p/twUUxzJ7FX

  Ps.   

I assume you mean the bitmask 255.255.255.0

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/20971918/golang-number-of-bits-of-an-ip-mask

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils