将netip.Addr转换为net.IP以获取Go中的IPv4地址。

huangapple go评论89阅读模式
英文:

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

huangapple
  • 本文由 发表于 2022年9月25日 23:23:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/73845670.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定