Skip to content

Commit

Permalink
fix(routing): net.IPNet to netip.Prefix conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
qdm12 committed May 22, 2023
1 parent f712d77 commit 6d48f9c
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
12 changes: 11 additions & 1 deletion internal/routing/conversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
48 changes: 48 additions & 0 deletions internal/routing/conversion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down

0 comments on commit 6d48f9c

Please sign in to comment.