Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: Number of bits of an IP mask

Tags:

ip-address

go

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

like image 258
Adriano P Avatar asked Jan 07 '14 12:01

Adriano P


1 Answers

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

like image 56
ANisus Avatar answered Oct 24 '22 07:10

ANisus