Golang:IP掩码的位数

huangapple go评论113阅读模式
英文:

Golang: Number of bits of an IP mask

问题

在Go语言中,你可以使用net.IPMask类型来获取IP掩码的位数。首先,你需要将IP掩码解析为net.IP类型和net.IPMask类型。然后,你可以使用net.IPMask类型的Size()方法来获取掩码的位数。

下面是一个示例代码:

package main

import (
	"fmt"
	"net"
)

func main() {
	ip := net.ParseIP("10.100.20.0")
	mask := net.IPMask(net.ParseIP("255.255.255.0").To4())

	ones, bits := mask.Size()
	fmt.Printf("Mask: %s\n", mask.String())
	fmt.Printf("Bits: %d\n", bits)
	fmt.Printf("Ones: %d\n", ones)
}

这段代码将输出:

Mask: ffffff00
Bits: 24
Ones: 24

这里,bits变量存储了掩码的位数,即24。你可以根据需要使用bits变量来比较掩码的大小。

英文:

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

答案1

得分: 13

net 包提供了一些函数来获取掩码的前缀大小,该值在 CIDR 表示法 中使用。具体用于位数的函数是:

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

要获取位数,请参考以下示例:

package main

import (
	"fmt"
	"net"
)

func main() {
	mask := net.IPMask(net.ParseIP("255.255.255.0").To4()) // 如果你有一个字符串形式的掩码
	//mask := net.IPv4Mask(255,255,255,0) // 如果你有一个由4个整数值表示的掩码
	
	prefixSize, _ := mask.Size()
	fmt.Println(prefixSize)
}

输出:

24

Playground

附注:

我假设你指的是掩码 255.255.255.0。

英文:

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

答案2

得分: 0

这可以使用IPAddress Go库来实现,无论是IPv4还是IPv6。免责声明:我是项目经理。

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

func main() {
	maskStr := "255.255.255.0"
	pref := ipaddr.NewIPAddressString(maskStr).GetAddress().
		GetBlockMaskPrefixLen(true)
	fmt.Printf("255.255.255.0的前缀长度为%d", pref.Len())
}

输出:

255.255.255.0的前缀长度为24
英文:

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

huangapple
  • 本文由 发表于 2014年1月7日 20:41:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/20971918.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定