简体   繁体   English

golang:将 IPv4 和 IPv6 地址从文本格式转换为二进制格式

[英]golang: convert IPv4 and IPv6 addresses from text to binary form

looking to send an ipv4 address across in 4 bytes, and ipv6 address in 16 bytes - What's similar to inet_pton() in go?希望发送 4 个字节的 ipv4 地址和 16 个字节的 ipv6 地址 - 与inet_pton()有何相似之处?

struct sockaddr_in sa;
char str[INET_ADDRSTRLEN];
inet_pton(AF_INET, "192.0.2.33", &(sa.sin_addr));

struct sockaddr_in6 sa;
char str[INET6_ADDRSTRLEN];
inet_pton(AF_INET6, "2001:db8:8714:3a90::12", &(sa.sin6_addr));

I know of https://play.golang.org/p/jn8t7zJzT5v - that is looking complicated for IPV6 addresses though.我知道https://play.golang.org/p/jn8t7zJzT5v - 虽然 IPV6 地址看起来很复杂。

Thanks!谢谢!

net.ParseIP() will take an IPv4 or IPv6 formatted string and return a net.IP containing the IP address. net.ParseIP()将采用 IPv4 或 IPv6 格式的字符串并返回包含 IP 地址的net.IP

The net.IP is what you'll need to feed to most other Go functions, such as to make a connection to the host. net.IP是您需要提供给大多数其他 Go 函数的内容,例如与主机建立连接。

Note that unlike most Go functions which return an error, net.ParseIP() simply returns nil if the string could not be parsed into an IP address.请注意,与大多数返回错误的 Go 函数不同,如果字符串无法解析为 IP 地址, net.ParseIP()只会返回nil

https://play.golang.org/p/Cgsrgth7JKY https://play.golang.org/p/Cgsrgth7JKY

Either you can use the net package: `您可以使用 net 包:`

a := net.ParseIP("127.0.0.1")
fmt.Printf("%b %s", net.IP.To4(a))

` https://play.golang.org/p/KzqYpk9OBh8 ` https://play.golang.org/p/KzqYpk9OBh8

Or, you can split the IP and convert each value into an integer using strconv.Atoi(), and thereafter convert each integer into byte()或者,您可以拆分 IP 并使用 strconv.Atoi() 将每个值转换为整数,然后将每个整数转换为 byte()

` `

ipString := "127.0.0.1"

octets := strings.Split(ipString, ".")

octet0, _ := strconv.Atoi(octets[0])
octet1, _ := strconv.Atoi(octets[1])
octet2, _ := strconv.Atoi(octets[2])
octet3, _ := strconv.Atoi(octets[3])

b := [4]byte{byte(octet0),byte(octet1),byte(octet2),byte(octet3)}

fmt.Printf("%s has 4-byte representation of %b\n", ipString, b)

` https://play.golang.org/p/2F3bC0df9wB ` https://play.golang.org/p/2F3bC0df9wB

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM