英文:
Convert netip.Addr to net.IP for IPv4 address in Go
问题
我有一个IPv4地址,类型是netip.Addr
(在Go 1.18中引入的新包/类型)。我想将我的IPv4地址转换为net.IP
类型(https://pkg.go.dev/net#IP)。
我已经有两种方法可以将我的IPv4地址从一种类型转换为另一种类型:
// ip 是一个 netip.Addr
var dst_ip net.IP
dst_ip := net.ParseIP(ip.String())
// 或者
dst_ip := net.IPv4(ip.As4()[0], ip.As4()[1], ip.As4()[2], ip.As4()[3])
有没有更高效的方法来进行这种类型转换?
英文:
I have an IPv4 address as an netip.Addr
(new package/type introduced with Go 1.18) https://pkg.go.dev/net/netip#Addr
I would like to convert my IPv4 address to net.IP
type (https://pkg.go.dev/net#IP).
I already have 2 methods to convert my IPv4 from one type to another :
// 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])
Is there a more efficient way to do this type conversion ?
答案1
得分: 5
以下是翻译好的内容:
这是一个示例,展示了如何更高效地进行操作。由于net.IP
的底层类型是字节,我们可以将[]byte
转换为net.IP
类型:
package main
import (
"fmt"
"net"
"net/netip"
)
func main() {
// 示例 Addr 类型
addr, err := netip.ParseAddr("10.0.0.1")
fmt.Println(addr, err)
// 将 Addr 转换为 []byte
s := addr.AsSlice()
// 将字节切片转换为 net.IP(由于 net.IP 的底层类型也是 []byte,因此 net.IP 和 []byte 是相同的)
ip := net.IP(s)
fmt.Println(ip.IsPrivate())
// 看看是否一切正常,从 net.IP 创建 netip.Addr(在这里您还可以看到类型如何工作,因为 netip.AddrFromSlice 接受 []byte)
addrFromIp, ok := netip.AddrFromSlice(ip)
fmt.Println(addrFromIp, ok)
}
Playground 链接:https://go.dev/play/p/JUAMNHhdxUj
英文:
Here is an example how you could do this more efficient, as net.IP
underlying type is bytes we are able to cast []byte
to net.IP
type:
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)
}
Playground link: https://go.dev/play/p/JUAMNHhdxUj
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论