为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
智慧大石 2023-01-03 11:19:08
问你如何计算提供的cidr低于一位的cidr?鉴于:网络 CIDR : (192.168.0.0/16)想要的结果192.168.0.0/17, 192.168.128.0/17使用默认net包和等包github.com/brotherpowers/ipsubnet,github.com/seancfoley/ipaddress-go/ipaddr没有得到想要的结果。
查看完整描述

2 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

要将网络一分为二,请将前缀的长度增加一。这给了你下半部分。要计算后半部分,请将网络部分加一(为简洁起见省略了错误处理):


package main


import (

    "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


查看完整回答
反对 回复 2023-01-03
?
隔江千里

TA贡献1906条经验 获得超10个赞

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

以下是如何使用github.com/seancfoley/ipaddress-go/ipaddr(注意此代码也适用于 IPv6 和前缀长度的任何更改):

package main


import (

    "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/17

192.168.128.0/17


查看完整回答
反对 回复 2023-01-03
  • 2 回答
  • 0 关注
  • 126 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号