From 6d48f9c2ba66da3d98b0cd9251a8cc5d7394885e Mon Sep 17 00:00:00 2001 From: Quentin McGaw Date: Mon, 22 May 2023 05:56:27 +0000 Subject: [PATCH] fix(routing): net.IPNet to netip.Prefix conversion --- internal/routing/conversion.go | 12 +++++++- internal/routing/conversion_test.go | 48 +++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/internal/routing/conversion.go b/internal/routing/conversion.go index 439a114b..6e2f77cc 100644 --- a/internal/routing/conversion.go +++ b/internal/routing/conversion.go @@ -21,7 +21,17 @@ func NetipPrefixToIPNet(prefix *netip.Prefix) (ipNet *net.IPNet) { } func netIPNetToNetipPrefix(ipNet net.IPNet) (prefix netip.Prefix) { - return netip.MustParsePrefix(ipNet.String()) + if len(ipNet.IP) != net.IPv4len && len(ipNet.IP) != net.IPv6len { + return prefix + } + var ip netip.Addr + if ipv4 := ipNet.IP.To4(); ipv4 != nil { + ip = netip.AddrFrom4([4]byte(ipv4)) + } else { + ip = netip.AddrFrom16([16]byte(ipNet.IP)) + } + bits, _ := ipNet.Mask.Size() + return netip.PrefixFrom(ip, bits) } func netIPToNetipAddress(ip net.IP) (address netip.Addr) { diff --git a/internal/routing/conversion_test.go b/internal/routing/conversion_test.go index a30dfbb5..53002956 100644 --- a/internal/routing/conversion_test.go +++ b/internal/routing/conversion_test.go @@ -8,6 +8,54 @@ import ( "github.com/stretchr/testify/assert" ) +func Test_netIPNetToNetipPrefix(t *testing.T) { + t.Parallel() + + testCases := map[string]struct { + ipNet net.IPNet + prefix netip.Prefix + }{ + "empty ipnet": {}, + "custom sized IP in ipnet": { + ipNet: net.IPNet{ + IP: net.IP{1}, + }, + }, + "IPv4 ipnet": { + ipNet: net.IPNet{ + IP: net.IP{1, 2, 3, 4}, + Mask: net.IPMask{255, 255, 255, 0}, + }, + prefix: netip.PrefixFrom(netip.AddrFrom4([4]byte{1, 2, 3, 4}), 24), + }, + "IPv4-in-IPv6 ipnet": { + ipNet: net.IPNet{ + IP: net.IPv4(1, 2, 3, 4), + Mask: net.IPMask{255, 255, 255, 0}, + }, + prefix: netip.PrefixFrom(netip.AddrFrom4([4]byte{1, 2, 3, 4}), 24), + }, + "IPv6 ipnet": { + ipNet: net.IPNet{ + IP: net.IPv6loopback, + Mask: net.IPMask{0xff}, + }, + prefix: netip.PrefixFrom(netip.IPv6Loopback(), 8), + }, + } + + for name, testCase := range testCases { + testCase := testCase + t.Run(name, func(t *testing.T) { + t.Parallel() + + prefix := netIPNetToNetipPrefix(testCase.ipNet) + + assert.Equal(t, testCase.prefix, prefix) + }) + } +} + func Test_netIPToNetipAddress(t *testing.T) { t.Parallel()