如何获取(IPv4)net.IPNet的广播地址?

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

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

huangapple
  • 本文由 发表于 2016年3月23日 06:56:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/36166791.html
匿名

发表评论

匿名网友

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

确定