英文:
How to Get Broadcast Address of (IPv4) net.IPNet?
问题
net.IPNet
结构体的广播地址计算是否有内置函数?
英文:
Is there a built-in function to calculate the broadcast address of a net.IPNet
struct?
答案1
得分: 4
链接@Dsafds有答案。为了历史记录和方便起见,以及让你不必自己阅读整个线程。代码是Mikio Hara的,我进行了一些小的修改。
func lastAddr(n *net.IPNet) (net.IP, error) { // works when the n is a prefix, otherwise...
if n.IP.To4() == nil {
return net.IP{}, errors.New("不支持IPv6地址。")
}
ip := make(net.IP, len(n.IP.To4()))
binary.BigEndian.PutUint32(ip, binary.BigEndian.Uint32(n.IP.To4())|^binary.BigEndian.Uint32(net.IP(n.Mask).To4()))
return ip, nil
}
英文:
The link @Dsafds has the answer. Here for history's sake, and so you don't have to read through the thread yourself. Code is Mikio Hara's with minor modifications made by me.
func lastAddr(n *net.IPNet) (net.IP, error) { // works when the n is a prefix, otherwise...
if n.IP.To4() == nil {
return net.IP{}, errors.New("does not support IPv6 addresses.")
}
ip := make(net.IP, len(n.IP.To4()))
binary.BigEndian.PutUint32(ip, binary.BigEndian.Uint32(n.IP.To4())|^binary.BigEndian.Uint32(net.IP(n.Mask).To4()))
return ip, nil
}
答案2
得分: 0
IPAddress Go库提供了这样的功能。免责声明:我是项目经理。
// 从net.IPNet中获取
_, ipNet, _ := net.ParseCIDR("1.2.3.4/16")
addr, _ := ipaddr.NewIPAddressFromNetIPNet(ipNet)
bcast, _ := addr.ToIPv4().ToBroadcastAddress()
fmt.Println("广播地址是", bcast)
输出:
广播地址是 1.2.255.255/16
// 或者直接从字符串中获取
addr = ipaddr.NewIPAddressString("1.2.3.4/16").GetAddress()
bcast, _ = addr.ToIPv4().ToBroadcastAddress()
fmt.Println("广播地址是", bcast)
输出:
广播地址是 1.2.255.255/16
英文:
The IPAddress Go library library provides such functionality. Disclaimer: I am the project manager.
// from a net.IPNet
_, ipNet, _ := net.ParseCIDR("1.2.3.4/16")
addr, _ := ipaddr.NewIPAddressFromNetIPNet(ipNet)
bcast, _ := addr.ToIPv4().ToBroadcastAddress()
fmt.Println("broadcast address is", bcast)
Output:
broadcast address is 1.2.255.255/16
// or from a string directly
addr = ipaddr.NewIPAddressString("1.2.3.4/16").GetAddress()
bcast, _ = addr.ToIPv4().ToBroadcastAddress()
fmt.Println("broadcast address is", bcast)
Output:
broadcast address is 1.2.255.255/16
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论