Go - 计算低于提供的 cidr 一位的 cidr

你如何计算提供的cidr低于一位的cidr?

鉴于:

网络 CIDR : (192.168.0.0/16)

想要的结果

192.168.0.0/17, 192.168.128.0/17

使用默认net包和等包github.com/brotherpowers/ipsubnetgithub.com/seancfoley/ipaddress-go/ipaddr没有得到想要的结果。


智慧大石
浏览 127回答 2
2回答

紫衣仙女

要将网络一分为二,请将前缀的长度增加一。这给了你下半部分。要计算后半部分,请将网络部分加一(为简洁起见省略了错误处理):package mainimport (    "fmt"    "math/big"    "net/netip")func main() {    p := netip.MustParsePrefix("192.168.0.0/16")    lo, hi := split(p)    fmt.Println(lo, hi) // 192.168.0.0/17 192.168.128.0/17}func split(p netip.Prefix) (lo, hi netip.Prefix) {    p = p.Masked()    lo, _ = p.Addr().Prefix(p.Bits() + 1)    delta := big.NewInt(1)    delta.Lsh(delta, uint(lo.Addr().BitLen()-lo.Bits()))    n := new(big.Int).SetBytes(lo.Addr().AsSlice())    n.Add(n, delta)    hiIP, _ := netip.AddrFromSlice(n.Bytes())    hi = netip.PrefixFrom(hiIP, lo.Bits())    return lo, hi}https://go.dev/play/p/0HLqUK0RmVC

隔江千里

“使用默认的net包和github.com/brotherpowers/ipsubnet、github.com/seancfoley/ipaddress-go/ipaddr等包没有得到想要的结果。”以下是如何使用github.com/seancfoley/ipaddress-go/ipaddr(注意此代码也适用于 IPv6 和前缀长度的任何更改):package mainimport (    "fmt"    "github.com/seancfoley/ipaddress-go/ipaddr")func main() {    cidr := ipaddr.NewIPAddressString("192.168.0.0/16").GetAddress()    for i := cidr.AdjustPrefixLen(1).PrefixBlockIterator(); i.HasNext(); {        fmt.Println(i.Next())    }}输出:192.168.0.0/17192.168.128.0/17
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go