在 Go 中将 IPv4 地址的 netip.Addr 转换为 net.IP

lch*_*lus 3 ip network-programming go

我有一个 IPv4 地址netip.Addr(Go 1.18 中引入的新包/类型)https://pkg.go.dev/net/netip#Addr

我想将我的 IPv4 地址转换为net.IP类型 ( https://pkg.go.dev/net#IP )。

我已经有 2 种方法将 IPv4 从一种类型转换为另一种类型:

// ip is an netip.Addr 

var dst_ip net.IP

dst_ip := net.ParseIP(ip.String())

// or

dst_ip := net.IPv4(ip.As4()[0], ip.As4()[1], ip.As4()[2], ip.As4()[3])
Run Code Online (Sandbox Code Playgroud)

有没有更有效的方法来进行这种类型转换?

Bar*_*ski 6

下面是一个如何更有效地做到这一点的示例,因为net.IP基础类型是字节,我们可以转换[]bytenet.IP类型:

package main

import (
    "fmt"
    "net"
    "net/netip"
)

func main() {
    // example Addr type
    addr, err := netip.ParseAddr("10.0.0.1")
    fmt.Println(addr, err)

    // get Addr as []byte
    s := addr.AsSlice()
    // cast bytes slice to net.IP (it works as net.IP underlying type is also []byte so net.IP and []byte are identical)
    ip := net.IP(s)
    fmt.Println(ip.IsPrivate())

    // lets see if everything works creating netip.Addr from net.IP (here you can also see how types work as netip.AddrFromSlice accepts []byte)
    addrFromIp, ok := netip.AddrFromSlice(ip)
    fmt.Println(addrFromIp, ok)
}
Run Code Online (Sandbox Code Playgroud)

游乐场链接:https://go.dev/play/p/JUAMNHhdxUj