From b9cb939785eb3595d8809af86670196c51a1b519 Mon Sep 17 00:00:00 2001 From: Benjamin Hesmans Date: Wed, 10 Nov 2021 12:51:04 +0000 Subject: [PATCH] Fix for BroadcastAddr It possible to get an IPv4 mapped into an IPv6, with an IPv4 mask. In this case len of the IP and the mask can be different and the function will panic with an out-of-bound. Signed-off-by: Benjamin Hesmans --- net_utils.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/net_utils.go b/net_utils.go index a9aceee..69f2eae 100644 --- a/net_utils.go +++ b/net_utils.go @@ -93,8 +93,15 @@ func NetworkAddr(n *net.IPNet) net.IP { func BroadcastAddr(n *net.IPNet) net.IP { // The golang net package doesn't make it easy to calculate the broadcast address. :( broadcast := NewIP(len(n.IP)) - for i := 0; i < len(n.IP); i++ { - broadcast[i] = n.IP[i] | ^n.Mask[i] + offset := 0 + + if len(n.IP) == net.IPv6len && len(n.Mask) == net.IPv4len { + offset = net.IPv6len - net.IPv4len + copy(broadcast, n.IP[:offset]) + } + + for i := 0; i < len(n.Mask); i++ { + broadcast[i+offset] = n.IP[i+offset] | ^n.Mask[i] } return broadcast }