fix(routing): net.IPNet to netip.Prefix conversion
This commit is contained in:
@@ -21,7 +21,17 @@ func NetipPrefixToIPNet(prefix *netip.Prefix) (ipNet *net.IPNet) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func netIPNetToNetipPrefix(ipNet net.IPNet) (prefix netip.Prefix) {
|
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) {
|
func netIPToNetipAddress(ip net.IP) (address netip.Addr) {
|
||||||
|
|||||||
@@ -8,6 +8,54 @@ import (
|
|||||||
"github.com/stretchr/testify/assert"
|
"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) {
|
func Test_netIPToNetipAddress(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user